appDBMSname priceEspresso 2.50Latte 3.80Flat white 3.70Cappuccino 3.50?1SELECT name, price2FROM drinks3WHERE kind = 'coffee'4 AND price < 45ORDER BY price DESC6LIMIT 212345name priceLatte 3.80Flat white 3.70id name kind price1 Espresso coffee 2.502 Latte coffee 3.803 Green tea tea 2.204 Mocha coffee 4.205 Chai latte tea 3.906 Flat white coffee 3.707 Cappuccino coffee 3.50
Back row: the app, the DBMS and its working rowsFront: the SELECT query, the result, and the drinks tableNumbered badges: the order the clauses run inAt the back: the café app that asks, the DBMS that answers, and the working rows where the DBMS builds the answer. In front: the SELECT query, the result the app gets back, and the drinks table. The clauses run in the order FROM, WHERE, SELECT, ORDER BY, LIMIT: take every row, keep the cheap coffees, keep two columns, sort by price from highest, keep the first two. Without ORDER BY, LIMIT keeps whichever rows come first, which SQL does not promise.

Asking a table

  1. A café keeps its menu in a table called drinks. Each row is one drink. The columns are id, name, kind and price. SELECT is how you ask a table a question.

Running the clauses

The answer

What happens

;; step 1/10 · table
table drinks
  column id     type integer
  column name   type text
  column kind   type text
  column price  type numeric(4,2)

  id name       kind   price
  1  Espresso   coffee 2.50
  2  Latte      coffee 3.80
  3  Green tea  tea    2.20
  4  Mocha      coffee 4.20
  5  Chai latte tea    3.90
  6  Flat white coffee 3.70
  7  Cappuccino coffee 3.50

7 rows x 4 columns
numeric(4,2): up to 4 digits, 2 after the point

FROM, WHERE, SELECT, ORDER BY, LIMIT is the logical order the PostgreSQL SELECT reference describes. The query planner may do the work in another way (for example using an index), but the answer is always the one this order gives. If two rows had the same price, ORDER BY price would not say which comes first. Add a second sort column, such as ORDER BY price DESC, id, to make the order complete.