BuildBot

SQL, Refreshed

Querying: SELECT, WHERE, ORDER, LIMIT

Lesson 2 of 5

What you'll learn

  • Project columns and filter rows with SELECT and WHERE
  • Sort results with ORDER BY and cap them with LIMIT
  • Understand the logical order a query is evaluated in

SELECT is how you read data back. You name the columns you want (the projection), choose which rows with WHERE (the filter), then optionally sort and trim.

SELECT name, age
FROM users
WHERE age >= 18
ORDER BY age DESC
LIMIT 3;

Read it as a pipeline: start with all rows in users, keep only those where age >= 18, sort the survivors by age highest-first, then hand back the first 3 — projecting just name and age.

The order Postgres actually runs it

You write SELECT first, but the engine evaluates FROMWHEREORDER BYLIMIT → and the projection. That's why you can sort or filter on a column you didn't select: the row still exists internally until the projection step throws the unused columns away.

SELECT name FROM users WHERE age >= 18 ORDER BY age DESC LIMIT 1;
-- Sorts by age even though only name comes back.

LIMIT without ORDER BY is arbitrary

Without ORDER BY, Postgres may return rows in any order — whatever is convenient. A LIMIT on unsorted data gives you some rows, not the "first" or "top" ones. Pair LIMIT with ORDER BY whenever order matters.

That filter-then-sort-then-cut pipeline is plain array work in JavaScript. The challenge models it.

WHERE + ORDER BY + LIMIT in JS

Run it. Filter rows, sort them, then take the first N — the same pipeline a SELECT runs.

Loading editor…

Next: relating rows across tables with joins.

Sign in to save your progress across devices.