Which shelf needs restocking? By exercise 30 you can answer that with a query that names the bin and the item. Start with five invented catalog entries and two questions: which rows do you need, and which columns should the answer show?
Run the exercises without a database file
Use the SQLite command-line shell (tested with SQLite 3.50.4). Start it with sqlite3 :memory:, or use an empty SQLite query editor. These exercises only read literal values. No account, tables, downloads of sample data, or cleanup are needed; closing the session discards it.
For each exercise, paste the shared prefix below, then its numbered SELECT immediately underneath. Run the two parts as one statement. There is deliberately no semicolon at the end of the prefix. Think of the two names after WITH as local variables: unlike stored tables, they exist only until that statement ends. If you get “no such table: product,” paste the prefix again.
WITH product(id, item, dept, cents, qty) AS (
VALUES (1, 'pen', 'Office', 150, 2),
(2, 'pen', 'Office', 200, 0),
(3, 'lamp', 'Home', 900, 3),
(4, 'mug', 'Home', 450, NULL),
(5, 'rope', 'Trail', 300, 1)
), location(dept, bin) AS (
VALUES ('Office', 'A1'), ('Home', 'B2'), ('Books', 'C3')
)One product row is one catalog entry, not one unit sold. The ID distinguishes two pens; cents is the unit price in US cents and qty is the quantity on hand. The mug has not been counted. The location list has one bin per mapped department. No bin is listed for Trail, and no product belongs to Books. Try predicting each answer before reading the result. We show headers and use NULL for missing values; your client may display a blank instead.
1–10: Choose columns, filter, and sort
Think of a spreadsheet filter: you can hide rows or choose columns without changing the underlying records. Unlike a worksheet, a query result has no dependable row order unless you ask for one.
1. Inspect every field
What does a catalog row contain? The star returns every column, which is useful for inspection but brittle if your application expects a fixed schema.
SELECT * FROM product ORDER BY id;Result
id | item | dept | cents | qty 1 | pen | Office | 150 | 2 2 | pen | Office | 200 | 0 3 | lamp | Home | 900 | 3 4 | mug | Home | 450 | NULL 5 | rope | Trail | 300 | 1
2. Choose two columns
For a compact lookup, request just the identifier and item name. Selecting fewer columns does not remove any rows.
SELECT id, item FROM product ORDER BY id;Result
id | item 1 | pen 2 | pen 3 | lamp 4 | mug 5 | rope
3. Keep items with stock on hand
Which items have at least two units? The boundary is inclusive: the pen with exactly two qualifies.
SELECT item, qty FROM product WHERE qty >= 2 ORDER BY id;Result
item | qty pen | 2 lamp | 3
4. Require both conditions
Which office supplies have at least two units? Both tests must pass for the same row.
SELECT item FROM product WHERE dept = 'Office' AND qty >= 2 ORDER BY id;Result
item pen
5. Allow either condition
Now keep anything in Office or anything with at least two units. Unlike exercise 4, a row can qualify on just one test.
SELECT item FROM product WHERE dept = 'Office' OR qty >= 2 ORDER BY id;Result
item pen pen lamp
6. Remove repeated combinations
Which department and item pairs exist? Two pens have different IDs but the same pair; DISTINCT returns that pair once.
SELECT DISTINCT dept, item FROM product ORDER BY dept, item;Result
dept | item Home | lamp Home | mug Office | pen Trail | rope
7. Exclude missing counts
Which items have a recorded quantity? A known zero stays; a missing count does not. NULL means unknown here, not zero.
SELECT id, qty FROM product WHERE qty IS NOT NULL ORDER BY id;Result
id | qty 1 | 2 2 | 0 3 | 3 5 | 1
8. Sort alphabetically
List the distinct item labels in ascending order. Without ORDER BY, the database does not promise an order.
SELECT DISTINCT item FROM product ORDER BY item;Result
item lamp mug pen rope
9. Break a sort tie
Sort labels in reverse alphabetical order, then put the lower ID first when labels match. Look for the two pens.
SELECT item, id FROM product ORDER BY item DESC, id ASC;Result
item | id rope | 5 pen | 1 pen | 2 mug | 4 lamp | 3
10. Match a text pattern
Find labels containing the letter e. Each percent sign matches any number of characters, including none.
SELECT id, item FROM product WHERE item LIKE '%e%' ORDER BY id;Result
id | item 1 | pen 2 | pen 5 | rope
11–16: Calculate fields and combine lists
Stacking two lists puts values below one another. Joining them is closer to a lookup: add a bin beside each matching item. Unlike a single-value lookup, a join returns every matching pair; repeated department keys on both sides would multiply rows.
11. Build a display label
Join two text values with SQLite's concatenation operator. This changes the result label, not the catalog.
SELECT dept || ': ' || item AS label FROM product ORDER BY id;Result
label Office: pen Office: pen Home: lamp Home: mug Trail: rope
12. Calculate inventory value
Multiply unit price in cents by recorded quantity. The unknown count gives an unknown value; the known zero gives zero.
SELECT id, cents * qty AS value_cents FROM product ORDER BY id;Result
id | value_cents 1 | 300 2 | 0 3 | 2700 4 | NULL 5 | 300
13. Stack lists without deduplication
Combine department names from the catalog and the location list. UNION ALL stacks rows vertically and keeps repeats; both branches return one column.
SELECT dept FROM product
UNION ALL SELECT dept FROM location ORDER BY dept;Result
dept Books Home Home Home Office Office Office Trail
14. Find shared values
Which departments appear in both lists? INTERSECT returns each shared value once, even when several items belong to it.
SELECT dept FROM product
INTERSECT SELECT dept FROM location ORDER BY dept;Result
dept Home Office
15. Match items to bins
Which items have a known bin? An inner join matches rows side by side on department. An item without a matching location drops out.
SELECT product.id, location.bin FROM product
JOIN location ON product.dept = location.dept ORDER BY product.id;Result
id | bin 1 | A1 2 | A1 3 | B2 4 | B2
16. Name the inputs and output
Use short table aliases for the same match, and give the display column a readable name. Aliases are local to this statement.
SELECT p.item AS label, l.bin FROM product AS p
JOIN location AS l ON p.dept = l.dept ORDER BY p.id;Result
label | bin pen | A1 pen | A1 lamp | B2 mug | B2
17–23: Count and summarize
An aggregate folds several input rows into one answer, like a subtotal. Grouping gives each department its own subtotal. A missing value and a zero do not contribute in the same way.
17. Count rows versus known values
How many catalog rows are there, and how many have a stock count? COUNT(*) includes every row; COUNT(qty) skips NULL.
SELECT COUNT(*) AS items, COUNT(qty) AS counted FROM product;Result
items | counted 5 | 4
18. Average unit prices
What is the mean price per catalog row? This is not weighted by stock: every listed row contributes one price.
SELECT AVG(cents) AS mean_cents FROM product;Result
mean_cents 400.0
19. Sum known stock
How many units are accounted for? SUM skips the missing count, so the result is a known subtotal, not a promise about all inventory.
SELECT SUM(qty) AS known_units FROM product;Result
known_units 6
20. Find the lowest price
What is the cheapest unit price in cents? MIN gives the value, not the name of the item that carries it.
SELECT MIN(cents) AS lowest_cents FROM product;Result
lowest_cents 150
21. Find the highest price
What is the most expensive unit price? Compare it with the average to see how much prices vary.
SELECT MAX(cents) AS highest_cents FROM product;Result
highest_cents 900
22. Summarize each department
How many catalog entries belong to each department? GROUP BY makes one result row per distinct group, not one per item.
SELECT dept, COUNT(*) AS entries FROM product GROUP BY dept ORDER BY dept;Result
dept | entries Home | 2 Office | 2 Trail | 1
23. Filter whole groups
Keep only departments with more than one catalog entry. WHERE filters individual rows; HAVING filters the groups after counting.
SELECT dept, COUNT(*) AS entries FROM product
GROUP BY dept HAVING COUNT(*) > 1 ORDER BY dept;Result
dept | entries Home | 2 Office | 2
24–30: Turn the catalog into a report
Use the same rows to answer operational questions. In the final exercise, check whether a missing quantity belongs on a restock list or on a list of items to count.
24. Pick the two costliest entries
If you could inspect just two price tags, which would they be? Sort before applying LIMIT and use the ID to settle ties.
SELECT id, item, cents FROM product ORDER BY cents DESC, id LIMIT 2;Result
id | item | cents 3 | lamp | 900 4 | mug | 450
25. Find stock counts that need a check
Return only items whose counts are unknown. An equality comparison with NULL cannot establish that a value is missing; use IS NULL.
SELECT id, item FROM product WHERE qty IS NULL ORDER BY id;Result
id | item 4 | mug
26. Keep items without a matching bin
Use a left join for a complete catalog report. The unmatched item's bin is NULL instead of the whole item disappearing as in exercise 15.
SELECT p.id, l.bin FROM product AS p
LEFT JOIN location AS l ON p.dept = l.dept ORDER BY p.id;Result
id | bin 1 | A1 2 | A1 3 | B2 4 | B2 5 | NULL
27. Label stock status without changing it
Classify each row for a stock report. Test the unknown count explicitly so it cannot fall through to the available label.
SELECT id, CASE WHEN qty IS NULL THEN 'unchecked'
WHEN qty = 0 THEN 'empty' ELSE 'available' END AS status
FROM product ORDER BY id;Result
id | status 1 | available 2 | empty 3 | available 4 | unchecked 5 | available
28. Find prices above the catalog average
Use the single number from exercise 18 as a threshold, without hard-coding it. The inner query computes the mean; the outer query keeps the rows above it.
SELECT id, item FROM product
WHERE cents > (SELECT AVG(cents) FROM product) ORDER BY id;Result
id | item 3 | lamp 4 | mug
29. Find departments still missing a location
Start with catalog departments and subtract those that have bins. Unlike exercise 14, EXCEPT is directional: reversing its inputs answers another question.
SELECT dept FROM product
EXCEPT SELECT dept FROM location ORDER BY dept;Result
dept Trail
30. Build a restock report
Which mapped bin holds a known out-of-stock item? Join for the bin, filter for an actual zero, and return only the fields someone checking the shelf needs.
SELECT l.bin, p.item FROM product AS p
JOIN location AS l ON l.dept = p.dept WHERE p.qty = 0 ORDER BY l.bin, p.id;Result
bin | item A1 | pen
Check your interpretation
Bin A1 has a pen entry with zero units. That does not mean every pen is gone: the other pen entry has two units. A report grouped only by item name would hide that distinction. For analysis beyond the catalog, start by deciding what one row represents and how to handle missing counts. Those choices matter before using numeric columns in principal component analysis. For the broader workflow from stored data to models, see our introduction to big data and machine learning.
Sources and further practice
The earlier article followed Dorota Wdzięczna’s The Most Important SQL Queries for Beginners (LearnSQL.com, 2019). This edition keeps its progression through filtering, joining, and aggregation, with a new inventory dataset and seven read-only reporting tasks in place of data or schema changes.
SQLite documents the statement-local dataset in the WITH clause, row and group processing in the SELECT reference, NULL handling in aggregate functions, and pattern matching and concatenation under expression operators. All 30 prefix-and-query pairs were run against an empty in-memory SQLite database, and their outputs were checked before publication.
For chapter-length practice, Alan Beaulieu’s third edition covers SQL beyond this inventory exercise; it is not required to run the examples. As an Amazon Associate I earn from qualifying purchases. Learning SQL: Generate, Manipulate, and Retrieve Data (Amazon US).



