PostgreSQL NULL Values
A NULL value represents missing, unknown data.
By default, columns of a table can hold NULL values.
This chapter explains the IS NULL and IS NOT NULL operators.
Syntax
When creating a table, the basic syntax for NULL is as follows:
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
Here, NOT NULL means the field is forced to always contain a value. This means that if no value is added to the field, a new record cannot be inserted or an existing record updated.
A field with a NULL value means it can be left empty when the record is created.
When querying data, NULL values can cause some problems, because comparing an unknown value with any other value always yields an unknown result.
In addition, NULL cannot be compared with 0, because they are not equivalent.
Example
Example
Create the COMPANY table (Download the COMPANY SQL file ), with the following data:
runoobdb# select * from COMPANY;
id | name | age | address | salary
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
Next, we use the UPDATE statement to set several fields that can be empty to NULL:
runoobdb=# UPDATE COMPANY SET ADDRESS = NULL, SALARY = NULL where ID IN(6,7);
The COMPANY table now looks like this::
runoobdb=# select * from company;
id | name | age | address | salary
----+-------+-----+---------------------+--------
1 | Paul | 32 | California | 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | |
7 | James | 24 | |
(7 rows)
IS NOT NULL
Now, we use the IS NOT NULL operator to list all records whose SALARY (salary) value is not null:
runoobdb=# SELECT ID, NAME, AGE, ADDRESS, SALARY FROM COMPANY WHERE SALARY IS NOT NULL;
The result is as follows:
id | name | age | address | salary
----+-------+-----+------------+--------
1 | Paul | 32 | California | 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
(5 rows)
IS NULL
IS NULL is used to find fields with NULL values.
The following is the usage of the IS NULL operator, listing records whose SALARY (salary) value is null:
runoobdb=# SELECT ID, NAME, AGE, ADDRESS, SALARY FROM COMPANY WHERE SALARY IS NULL;
The result is as follows:
id | name | age | address | salary
----+-------+-----+---------+--------
6 | Kim | 22 | |
7 | James | 24 | |
(2 rows)