SQL
Study guide: DISC-DA
SQL (Structured Query Language) is the language used to retrieve and manipulate data held in the tables of a relational database. A query is a SELECT statement that names the columns or calculations wanted, the tables to read (FROM), the rows to keep (WHERE), how to group them (GROUP BY), which groups to keep (HAVING) and the order of the result (ORDER BY), and the database decides how to carry it out.
A summary query is written in this form:
SELECT terr, COUNT(*) AS n_claims, SUM(paid) AS total_paid
FROM claim
WHERE acc_year = 2024
GROUP BY terr
HAVING COUNT(*) >= 50
ORDER BY total_paid DESC;
It is processed in a different order from the one it is written in:
- The tables in
FROMare read and joined. WHEREremoves the rows that do not satisfy its condition.GROUP BYgroups the remaining rows and the aggregates are computed.HAVINGremoves groups.- The output columns of the
SELECTlist are computed. - Duplicates are removed if
DISTINCTis asked for. ORDER BYsorts the result.
The order explains two rules below: WHERE cannot use an aggregate, and it cannot use a name given in the select list.
Selecting and filtering rows
SELECT * returns every column. Otherwise the select list names columns or computes new ones from them, each evaluated once per result row. FROM names the table, or several tables combined by a join.
A row is kept by WHERE only if the condition is true for it. Conditions combine comparisons (=, <>, <, >=) with AND, OR and NOT. Because WHERE runs before grouping, it cannot contain an aggregate function.
Grouping and aggregate functions
GROUP BY combines rows that share the same values of the grouping columns into one output row, and aggregate functions compute one value per group. COUNT(*) counts rows, COUNT(col) counts rows where col is not null, and SUM, AVG, MIN and MAX work on the non-null values. Without GROUP BY, an aggregate treats the whole table as one group.
HAVING selects groups after the aggregates are computed, so its condition normally uses one, such as territories with at least 50 claims. A condition that needs no aggregate belongs in WHERE, which is also cheaper, because the rows it removes are never grouped.
What does this query return from the claim table? A claim table holds eight claims.
claim_id terr acc_year paid K1 T1 2024 5,000 K2 T1 2024 15,000 K3 T2 2024 2,000 K4 T2 2024 NULL K5 T2 2024 4,000 K6 T3 2024 30,000 K7 T1 2023 1,000 K8 T3 2023 6,000 SELECT terr, COUNT(*) AS n, COUNT(paid) AS n_paid, AVG(paid) AS avg_paid FROM claim WHERE acc_year = 2024 GROUP BY terr HAVING COUNT(*) >= 2 ORDER BY avg_paid DESC;Answer
WHEREremoves K7 and K8, the 2023 claims.- Grouping the other six by territory gives T1 (K1, K2), T2 (K3, K4, K5) and T3 (K6).
AVGignores K4's null, so T1 averages(5{,}000 + 15{,}000)/2 = 10{,}000and T2 averages(2{,}000 + 4{,}000)/2 = 3{,}000.- T3 has one claim and fails
HAVING COUNT(*) >= 2.- The result is two rows, sorted by average: T1 with
n = 2,n_{\text{paid}} = 2and 10,000, then T2 withn = 3,n_{\text{paid}} = 2and 3,000.- Treating K4's null as zero would have given T2 an average of 2,000.
Sorting and aliases
Without ORDER BY, rows come back in an unspecified order that must not be relied on, so "the first row" of the result is not defined. Sorting is ascending unless DESC is written, and each later sort column breaks ties in the earlier ones. The direction applies to each column separately, so ORDER BY x, y DESC sorts x ascending.
AS gives an output column a name (a column alias), which can be used in ORDER BY but not in WHERE, where the expression has to be written out again, because that step runs before the select list is computed. In standard SQL and PostgreSQL the alias cannot be used in HAVING either. MySQL is an exception and permits an alias in HAVING. A table alias (FROM claim AS c) gives a table a short name, which keeps join conditions readable and is required to join a table to itself.
Nulls
A null is an unknown value, so comparing it with = or <> gives null rather than true or false, and the row fails a WHERE condition. Test for it with IS NULL or IS NOT NULL, and use COALESCE to substitute a value. Aggregates other than COUNT return null, not zero, when no rows are selected. Null values covers the rest.
How many rows does
SELECT COUNT(*) FROM policy WHERE ...count under each of these four conditions? A policy table holds five policies with deductibles of 500, 1,000, NULL, 500 and NULL, the nulls being policies whose deductible was never recorded. The conditions aredeductible <> 500,deductible = NULL,deductible IS NULLanddeductible <> 500 OR deductible IS NULL.Answer
- A comparison with a null is unknown, so a null row never satisfies
<>or=.deductible <> 500counts 1, the 1,000 policy only. The two nulls are not counted, though they are not known to be 500.deductible = NULLcounts 0, because the comparison is never true, even for the null rows.deductible IS NULLcounts 2.deductible <> 500 OR deductible IS NULLcounts 3, every policy not known to have a 500 deductible.- An analyst who wanted all policies other than the 500 deductible and wrote the first condition silently loses the policies with no recorded deductible.
Joins combine tables, a database index speeds up filtering and joining on a column, and a user-defined function packages a rule for reuse inside queries. The same operations exist for an in-memory dataframe in R or pandas, and a query's result is itself a structured table.
Putting a row condition in
HAVINGor an aggregate inWHEREA condition on an aggregate, such asSUM(paid) > 100000, cannot go inWHERE, which runs before grouping. A condition on a row value, such as an accident year, belongs inWHERE, so that the excluded rows never enter the aggregate.