← العودة إلى الدورة: SQL and databases from scratch

ORDER BY, LIMIT and week 2 review

الفيديو قريبًا

A table in SQL is a set of rows, and sets have no order. If you do not ask for an order, the engine returns the rows however is most convenient for it, and that order can change from one execution to another, especially after updating data. Never rely on the default order. When order matters, you must ask for it with ORDER BY, which goes at the end of the query, after WHERE.

sql
-- Cheapest first (ASC is the default)
SELECT name, price FROM products ORDER BY price;

-- Most expensive first
SELECT name, price FROM products ORDER BY price DESC;

-- Several keys: by category A-Z, and inside each one by price high to low
SELECT category, name, price
FROM products
ORDER BY category ASC, price DESC;

ASC is ascending (smallest to largest, A to Z, oldest date to newest) and is the default; DESC is descending. You can sort by several columns separated by commas: the second one only breaks ties when the first has equal values. You can also sort by an expression, by an alias from the SELECT (here it is allowed, because ORDER BY is evaluated last) or by column position (ORDER BY 2), although the latter is fragile and discouraged.

NULL when sorting

Where do NULL values go when sorting? It depends on the engine. In PostgreSQL, NULL is considered greater than any value: it appears last in ascending order and first in descending. In MySQL and SQLite the opposite happens. To avoid depending on that, PostgreSQL and SQLite let you write NULLS FIRST or NULLS LAST explicitly.

sql
-- Hugo (NULL city) goes last, whatever the engine
SELECT name, city FROM customers ORDER BY city ASC NULLS LAST;

LIMIT and OFFSET

LIMIT n returns at most n rows; OFFSET m skips the first m. Combined with ORDER BY they serve for rankings (the 3 most expensive) and for paginating results (page 2 with 10 rows per page: LIMIT 10 OFFSET 10). Without ORDER BY, LIMIT returns arbitrary rows, so they almost always go together. LIMIT exists in PostgreSQL, MySQL and SQLite; standard SQL uses FETCH FIRST n ROWS ONLY, which PostgreSQL also accepts, and SQL Server uses TOP n.

sql
-- Top 3 most expensive products
SELECT name, price FROM products ORDER BY price DESC LIMIT 3;

-- Page 2, with 4 products per page
SELECT product_id, name FROM products ORDER BY product_id LIMIT 4 OFFSET 4;

-- Standard SQL version of the first query
SELECT name, price FROM products ORDER BY price DESC FETCH FIRST 3 ROWS ONLY;

Before the quiz, review the week's path. With WHERE you decide which rows get in; with operators such as LIKE, IN, BETWEEN and IS NULL you express richer conditions; with ORDER BY you decide in which order they come out; and with LIMIT and OFFSET you trim the result. Practice combining everything in a single query, for example the five cheapest products with stock available. When something does not work, read it aloud clause by clause and check each one separately: it is the fastest way to find the error. One last important detail: the order of rows is only guaranteed if you ask for it with ORDER BY. If your query seems to always return the same order without asking, it is a coincidence that can break tomorrow, when the table grows or the engine changes its execution plan. Also do not forget that LIMIT without ORDER BY returns arbitrary rows.

اختبر ما تعلمته

السؤال 1 من 6

What does WHERE email = NULL return?

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →