Tables and Select
Where and Order
Filtering Rows
WHERE keeps rows that match a condition. ORDER BY sorts the remaining rows.
Program
Play the script to filter in-stock products and sort by price.
where_order.sql
Replay: real traced execution (multi-file project)
CREATE TABLE products (name TEXT, price INTEGER, stock INTEGER);
INSERT INTO products VALUES ('pen', 3, 10), ('bag', 25, 0), ('book', 12, 4);
SELECT name, price FROM products WHERE stock > 0 ORDER BY price;
tables ← 1 row
1CREATE TABLE products (name TEXT, price INTEGER, stock INTEGER);2INSERT INTO products VALUES ('pen', 3, 10), ('bag', 25, 0), ('book', 12, 4);values this step1 rowtablesproducts ← 3 rows
1CREATE TABLE products (name TEXT, price INTEGER, stock INTEGER);2INSERT INTO products VALUES ('pen', 3, 10), ('bag', 25, 0), ('book', 12, 4);3SELECT name, price FROM products WHERE stock > 0 ORDER BY price;values this step3 rowsproductsresult ← 2 rows
2INSERT INTO products VALUES ('pen', 3, 10), ('bag', 25, 0), ('book', 12, 4);3SELECT name, price FROM products WHERE stock > 0 ORDER BY price;values this step2 rowsresult
Follow the Filter
productsstarts withpen,bag, andbook.WHERE stock > 0keeps rows with stock left.baghas stock0, so it is not returned.ORDER BY priceputspenbeforebook. | name | price | stock | result | | --- | --- | --- | --- | | pen | 3 | 10 | kept | | bag | 25 | 0 | filtered out | | book | 12 | 4 | kept |
WHERE
`WHERE stock > 0` keeps only rows with available stock.
comparison
`>` compares each row's value.
sort
`ORDER BY price` sorts the filtered rows.
Exercise: where_order.sql
Reproduce the kept rows pen and book, then change bag stock to a positive number and predict the price order.