SQL NULL VALUES

In SQL, a NULL value represents the absence of a value or an unknown value. It is different from an empty string or a number with a value of zero. NULL is used to indicate that a data value does not exist in the database.

Using NULL in SQL

You can use NULL values in various SQL operations, including inserting data, querying, and updating records.

Inserting NULL Values


-- Insert a record with NULL in a column
INSERT INTO Employees (Name, Age, Position, Salary)
VALUES ('Jane Doe', NULL, 'Manager', NULL);

        

In this example:

  • The Age and Salary columns are set to NULL for the new employee record.

Querying NULL Values


-- Select records where Age is NULL
SELECT * FROM Employees
WHERE Age IS NULL;

        

To filter records with NULL values, use the IS NULL condition. Note that NULL cannot be compared using the usual equality operators (e.g., =, !=).

Updating NULL Values


-- Update a record to set Age to NULL
UPDATE Employees
SET Age = NULL
WHERE Name = 'Jane Doe';

        

You can update a record to set a column value to NULL using the UPDATE statement. Remember that NULL values do not replace existing data but rather represent the absence of data.

Handling NULL Values

  • Default Values: Set default values to handle NULL entries if necessary.
  • IS NULL and IS NOT NULL: Use these conditions to check for NULL values in queries.
  • COALESCE Function: Use COALESCE() to provide a default value if a column contains NULL.