Sub topic 2
How DISTINCT Treats NULL Values
This chapter assumes you can write a basic SELECT ... FROM ... WHERE query, sort results with ORDER BY, and understand that a NULL means "no value recorded."
How DISTINCT treats NULL values
DISTINCT treats all NULL values as equal to each other, so repeated NULLs collapse into a single row. Compare this with a WHERE condition, where NULL = NULL is not true.
SELECT DISTINCT city
FROM customers;If five customers have no city, the result contains one NULL row, not five.
COUNT(DISTINCT city) works differently. It ignores NULLs entirely and counts only the distinct non-NULL values.
Restricting rows with LIMIT
LIMIT n returns at most n rows. It does not change which rows match. It only cuts off the output after the matching rows are found and sorted.
SELECT order_id, total
FROM orders
ORDER BY order_id
LIMIT 5;Why LIMIT needs ORDER BY
Without ORDER BY, SQL does not guarantee which rows come back. The database may return any five matching rows, and the set can change between runs. Always pair LIMIT with an ORDER BY that ends in a unique column, such as an ID, so the result is repeatable.
Skipping rows with OFFSET
OFFSET m skips the first m rows before LIMIT takes its rows. To show page 3 with 10 rows per page, skip 20 rows:
SELECT order_id, total
FROM orders
ORDER BY order_id
LIMIT 10 OFFSET 20;Exercise
A customers table has 3 rows where city is NULL and 2 rows where city is 'Oslo'. How many rows does SELECT DISTINCT city return?
Show answer
Two rows: one NULL row and one 'Oslo' row.