Five stocks, 26 years, 33,493 daily bars in one table. Which days did a stock rise or fall more than 12% from open to close, and which day was the busiest for JPM? A short SQL query answers each, and you will write them from scratch.
The idea in plain words
Where we are. This is the first topic of the SQL skill, so nothing comes before it. By the end you can read rows out of a table, keep only the ones you want, put them in order and cut the list short. The next topics add totals per group, missing values, and joins between tables.
A SQL query describes the table you want, not the steps to build it. You name the columns, say which rows qualify, and say how to order them; the database decides how to find them. A query has the same few parts every time, and they are written in a fixed order: SELECT the columns, FROM a table, WHERE a condition, ORDER BY a sort, LIMIT a count.
The true-or-false test in a WHERE. A row stays only if its test is true; a row where it is false, or unknown, is dropped.
Select, filter, sort, limit
The table is bars, one row per stock per day. Start with the five most recent closes of one stock: pick two columns, keep one symbol, sort newest first, keep five rows.
# The five latest closes of AAPLprint(con.sql(""" SELECT date, close FROM bars WHERE symbol = 'AAPL'1 ORDER BY date DESC2 LIMIT 5"""))
┌────────────┬────────┐ │ date │ close │ │ date │ double │ ├────────────┼────────┤ │ 2026-08-21 │ 309.35 │ │ 2026-08-20 │ 311.3 │ │ 2026-08-19 │ 316.83 │ │ 2026-08-18 │ 310.03 │ │ 2026-08-17 │ 305.59 │ └────────────┴────────┘
- 1The predicate: only AAPL rows pass.
- 2
DESCsorts newest first; withoutORDER BYthe order is not promised.
Columns can be computed. The move from open to close is (close - open) / open; naming it with AS lets you reuse the name in ORDER BY. Filter on the same expression to keep only the big days.
# A computed column and a filter on the same expressionprint(con.sql(""" SELECT symbol, date, round((close - open) / open * 100, 2) AS move_pct1 FROM bars WHERE abs((close - open) / open) >= 0.122 ORDER BY abs(move_pct) DESC LIMIT 5"""))
┌─────────┬────────────┬──────────┐ │ symbol │ date │ move_pct │ │ varchar │ date │ double │ ├─────────┼────────────┼──────────┤ │ JPM │ 2002-07-24 │ 22.57 │ │ JPM │ 2008-09-26 │ 18.98 │ │ JPM │ 2008-10-10 │ 18.87 │ │ JPM │ 2009-01-21 │ 17.31 │ │ JPM │ 2001-01-03 │ 16.53 │ └─────────┴────────────┴──────────┘
- 1
AS move_pctnames the computed column. - 2
abs(...)keeps both rises and falls.
Two more predicates cover most filters. IN (...) tests membership in a list, BETWEEN a AND b tests a range with both ends included, and AND, OR, NOT combine tests. A date is written as text, '2026-08-17', and the database reads it as a date.
# IN and BETWEEN: the days KO and XOM closed above their open in one weekprint(con.sql(""" SELECT symbol, date, open, close FROM bars WHERE symbol IN ('KO', 'XOM') AND date BETWEEN '2026-08-17' AND '2026-08-21' AND close > open ORDER BY symbol, date"""))
┌─────────┬────────────┬────────┬────────┐ │ symbol │ date │ open │ close │ │ varchar │ date │ double │ double │ ├─────────┼────────────┼────────┼────────┤ │ KO │ 2026-08-18 │ 88.4 │ 88.82 │ │ KO │ 2026-08-19 │ 88.59 │ 90.35 │ │ KO │ 2026-08-20 │ 90.18 │ 90.5 │ │ KO │ 2026-08-21 │ 90.85 │ 91.1 │ │ XOM │ 2026-08-17 │ 160.1 │ 161.46 │ │ XOM │ 2026-08-18 │ 164.35 │ 165.56 │ └─────────┴────────────┴────────┴────────┘
Building a query from Python
In the lab each function receives a symbol or a date and returns the query text. The tempting way is to paste the value into the string. It works until a value contains a single quote, as in the name O'Neil: the quote ends the string early and the rest becomes broken SQL. Worse, a value from a user could add its own SQL. The safe habit is to write every value through quote(), which wraps it in quotes and doubles any quote inside.
# A name with a quote breaks hand-built text; quote() doubles the quotename = "O'Neil"print(quote(name))1try: con.sql(f"SELECT count(*) FROM bars WHERE symbol = '{name}'")except Exception as error: print("pasted by hand:", type(error).__name__)print("quoted:", run(con, f"SELECT count(*) FROM bars WHERE symbol = {quote(name)}"))
'O''Neil' pasted by hand: ParserException quoted: [(0,)]
- 1
'O''Neil': the doubled quote is one quote inside the text.
Building SQL from text is how injection happens. In this lab the grader tries a symbol like x' OR '1'='1; with quote() it is just a name that matches nothing. Later topics send values separately from the query text, which is better still, but writing every value through quote() is the rule when you must build the text yourself.
What the tasks ask
- 1`recent_bars`Date and close of one symbol on or after a date, oldest first.
- 2`big_moves`A computed
movecolumn, a filter on its size, biggest first with ties broken by symbol then date. - 3`top_volume_days` and `up_days_in_range`
ORDER BY ... LIMITfor the busiest days, andINplusBETWEENfor several symbols over a date range. Every value goes throughquote().
ORDER BY volume DESC LIMIT 3 but several days share the third-highest volume. What makes the answer repeatable?Lab · what's graded
4 tasks · 100 ptsWHERE:recent_bars25 pts- A computed column:
big_moves25 pts ORDER BYandLIMIT:top_volume_days25 ptsINandBETWEEN:up_days_in_range25 pts