A table is a set of rows: your first SELECT
Meet a tiny canteen table and learn the three clauses every query starts with: SELECT, FROM, WHERE.
The school canteen sells four things and writes down every day how many of each it moved. In a database that log is one table: every row is one item, every column is one fact about it. The table has a name, sales, and you will ask it questions all lesson long.
sales
+----+----------+-------+--------+
| id | item | price | count |
+----+----------+-------+--------+
| 1 | soup | 2.50 | 40 |
| 2 | sandwich | 3.20 | 55 |
| 3 | salad | 2.80 | 23 |
| 4 | juice | 1.90 | 60 |
+----+----------+-------+--------+The sales table the canteen keeps: one row per item.You already know sets from the logic module, and a table is a set in disguise: rows are its elements, and no two rows are the same. Asking the table a question means computing a new set out of it. SQL is the language of those questions — Structured Query Language, and every word in that name is honest.
A query is a sentence with fixed word order. SELECT says which columns to keep, FROM names the table, WHERE filters rows. This order never changes, even though the database mentally executes it in another order — FROM first, then WHERE, and SELECT last.
SELECT count, item
FROM sales
WHERE price < 3.00Keep the columns count and item from sales, but only rows where price is below 3.00.Read a query as a small pipeline. FROM produces the whole table. WHERE throws out every row that fails the condition. SELECT keeps the asked columns and discards the rest. Here soup and salad survive the filter, and only their two columns reach the result.
sales 4 rows
|
+-- WHERE price < 3.00 --> soup (2.50), salad (2.80)
|
+-- SELECT count, item --> soup: 40, salad: 23
|
+-- result 2 rowsThe same query, drawn as a pipeline over four rows.Notice what came back: not a sentence, not a number — a smaller table. Two rows, two columns. Every SQL answer is itself a table, which means you can keep querying it, feeding one answer into the next question.
Practice
The canteen manager asks: what did we actually sell today? Which query answers that question about the sales table?
Hints
- The question is about which items sold, not about prices or ids.
- A column is chosen by SELECT; the table is named by FROM.
Write a query that shows the names of the dishes costing more than 2.90 euros: which column to take, from which table, and which rows to keep.
Hints
- Write the clauses in this order: SELECT, then FROM, then WHERE.
- You need the item column from the sales table, so: SELECT item FROM sales.
- The condition compares price with the number: WHERE price > 2.90.