PostgreSQL NULL 值


PostgreSQL NULL Values

In PostgreSQL, NULL represents a missing or unknown value. NULL is not the same as zero, space, or an empty string. The concept of NULL is used in databases to indicate the absence of an actual value. For example, if a particular field has no value, it will be represented by NULL.

Handling NULL Values

PostgreSQL provides several operators and functions to correctly handle NULL values.

Comparison

When comparing values, PostgreSQL uses the “unknown” result when one or both values are NULL. The “unknown” result is neither true nor false. The following are comparison operators in PostgreSQL:

  • = (equals)
  • <> or != (not equals)
  • < (less than)
  • (greater than)

  • <= (less than or equals)
  • = (greater than or equals)

IS NULL and IS NOT NULL

The IS NULL operator checks if a value is NULL. The IS NOT NULL operator checks if it is not NULL. These operators do not use the “unknown” result like comparison operators do. Here is an example:

SELECT name FROM employees WHERE department IS NULL;

This example returns the names of employees who do not have a department assigned.

COALESCE

The COALESCE function allows you to return the first non-NULL value in a list of values. Here is an example:

SELECT COALESCE(nullvalue, 'default value') FROM mytable;

This example returns “default value” if the nullvalue field is NULL.

NULLIF

The NULLIF function returns NULL if two given values are equal, otherwise it returns the first value. Here is an example:

SELECT NULLIF('apple', 'apple');

This example returns NULL because the two values are equal.

Aggregate Functions

NULLs are excluded from aggregate functions such as SUM(), AVG(), MAX(), and MIN(). However, you can use the COALESCE function to include NULLs in your calculations. Here is an example:

SELECT SUM(COALESCE(salary, 0)) AS total_salary FROM employees;

This example returns the total salary of all employees, treating NULL values as 0.

Conclusion

Understanding NULL values is essential for working with databases. PostgreSQL has various functions and operators to deal with NULL values, depending on the situation. Remember that NULL is not the same as zero, space, or an empty string, and should be treated accordingly.