ORDER BY, LIMIT, DISTINCT
Six products sit in the table in whatever order the engine stored them. Ask for them by price and they line up neatly; ask for only the first two and you get a gamble until you say which two.
- ▸Rows arrive however the engine found them, with no order of their own, until you ask for one.
- ▸Ask for the top few rows without sorting first, and a write can change which rows come back.
- ▸Removing duplicates folds two blank cells into one, treating them as equal, the opposite of how
= NULLmatched nothing.
The products table holds six rows, and when you ask for them with SELECT name, price FROM products, they come back in no order you chose: the engine hands over rows in whatever sequence it finds them. That sequence is not a promise. A write to the table, or a different plan (the steps the engine picks to run the query; the simplest, a Seq Scan, reads the table top to bottom), can hand them back arranged differently.
To pin the order, add a sort instruction after the table: SELECT name, price FROM products ORDER BY price. Now the rows line up by price, smallest first: Cable at 4.50, then the two rows at 17.50, up to Monitor at 299.00, and Stand, which has no price, last. Ascending is the default direction, written ASC when you want it explicit. Flip it with DESC and the same rows come out high to low: Stand first, then Monitor, and Cable at the bottom. On PostgreSQL, a missing price sorts as if it were larger than any number.
The sort comes after the rows are chosen: the engine builds the rows from FROM, filters them, picks the columns, and only then arranges what is left. So ORDER BY never changes which rows come back or how many, only the sequence they arrive in. Six rows in, six rows out, rearranged.