360 likes | 1.43k Views
NULL Values in SQL. CSE 4504/6504 Lab. Null Values. Special values that SQL provides for the column values - either unknown or inapplicable Example: -- Rating for a new Sailor INSERT INTO Sailors (sid, sname, rating, age) VALUES (101, ‘John Doe’, null, 18);
E N D
NULL Values in SQL CSE 4504/6504 Lab
Null Values • Special values that SQL provides for the column values - either unknown or inapplicable • Example: -- Rating for a new Sailor INSERT INTO Sailors (sid, sname, rating, age) VALUES (101, ‘John Doe’, null, 18); -- Maiden name for a male Student
Comparisons Using Null Values • The column value with Null is defined as unknown • The result of the comparison (>, <, =, etc.) between Null values or between a Null value and a known value is always unknown. • In SQL: -- IS NULL -- IS NOT NULL
Logical Connectives AND, OR, and NOT Third-value logic: NOT unknown = unknown attrA OR unknown = true (when attrA = true) = unknown (when attrA = false) attrA AND unknown = false (when attrA = false) = unknown (when attrA = true)
Impact on SQL Constructs • SQL queries eliminates rows that evaluate unknown. • Two rows are duplicates if corresponding columns are both null. • Arithmetic operations +, -, *, and / all return null if one their arguments is null.
In Aggregate Operations • Null values get counted in COUNT (*). • All the other aggregate operations (SUM, AVG, MIN, MAX, and variations using DISTINCT) simply discard null values.
Outer Joins Instance of Sailors Instance of Reserves SELECT Sailors.sid, Reserves.bid FROM Sailors NATURAL LEFT OUTER JOIN Reserves;
Disallowing Null Values • Null values can be disallowed by specifying NOT NULL as part of the field definition. • There is an implicit NOT NULL constraint for primary keys.