SQL for Data Science

The Data Science unit on relational databases and SQL, worked on one SQLite database built from eleven NHANES 2017-2018 tables. Codd's relational model and the normalization of the survey's prescription file; reading a table with SELECT and WHERE under three-valued logic; IN, BETWEEN, LIKE, CASE, ORDER BY and LIMIT; aggregates, GROUP BY and window functions; joins and the number of rows they produce; subqueries, EXISTS and recursive common table expressions; and running SQL from Python with parameters and transactions. Each article ends with worked problems and open questions, every number checked by a script.

Much of the world's structured data lives in relational databases, and SQL is how it is retrieved. This unit teaches the relational model and the parts of SQL a data analyst uses most, from reading one table to combining several and running queries from Python. Its subject is not syntax alone. A query in SQL can be valid, run without error and return a plausible number that answers a different question from the one asked, and most such answers come from two sources: missing values, which SQL handles with a three-valued logic, and joins, which can multiply rows. The unit keeps returning to both.

Every article uses one database: eleven tables built from the public files of the National Health and Nutrition Examination Survey (NHANES) 2017 to 2018, in SQLite, the database engine built into Python. The tables hold 9,254 people with their demographics, examinations, blood pressure readings, laboratory results, smoking answers and 14,434 reported prescription medicines with their reasons for use. Values are stored as published, refusal codes and top-codes included, so that the articles can show how SQL treats each kind of missing or inexact value. The database is built by tools/experiments/data-science/sqldata.py, and every number in the unit is computed by the article's script in the same folder and checked there by assertions. SQL behavior is stated for the SQLite version that ran it (3.49.1, with notes on the 3.38.4 in the site's test environment); notes on PostgreSQL, MySQL, SQL Server and Oracle come from their current documentation, not from running them.

Articles, in order

  • Relational Databases: Codd's 1970 model and the problem of data independence it solved; relations against SQL tables, which allow duplicates and NULLs; primary, foreign and surrogate keys, including why the prescription file has no natural key; integrity constraints and the ones SQLite does not enforce by default; first, second and third normal form worked on the prescription file, with functional dependencies tested in SQL, the splits on functional dependencies proved lossless by Heath's theorem, and the whole rebuild checked against the file; and the several kinds of missing value that one NULL must stand for.
  • Simple SQL Queries: SELECT, FROM and WHERE; integer division and operator precedence, where misplaced parentheses add exactly the 1,089 men aged 60 and over; three-valued logic derived as minimum and maximum, with the identity that a condition, its negation and its NULL test split every table; text against numbers and SQLite's quotes; and a query run with two plans.
  • Special Operators and Clauses: IN and the NOT IN trap, BETWEEN and the boundary values that closed classes count twice, LIKE and GLOB across dialects, CASE, COALESCE and NULLIF with the condition under which a stand-in for NULL can be undone, DISTINCT, NULLs and ties in ORDER BY, and "the first k rows with ties" proved equal to a rank filter.
  • Aggregate Functions: scalar functions and where dialects disagree; COUNT, SUM and AVG with NULL; GROUP BY reproducing the grouped means of the pandas articles; the difference between a mean over readings and a mean over people derived as a covariance; HAVING and the logical order of a query; a median query proved correct and the one-pass standard deviation shown failing; and window functions.
  • Join Queries: joins as filtered Cartesian products; inner, outer, self, semi-, anti- and band joins; ON against WHERE, with the rule for when a WHERE condition turns a left join into an inner join; the full join emulation and the column its NULL test must use; and the row count $\sum_k m_k n_k$, which explains a mean blood pressure computed per pill instead of per person.
  • Subqueries: scalar subqueries and SQLite's first-row rule; IN and EXISTS as semi-joins; exactly when NOT IN and NOT EXISTS agree; correlated subqueries and their rewrites, which stop being equivalent when the group key can be NULL; derived tables and common table expressions; and recursion, with why UNION stops on a cycle and UNION ALL does not.
  • Queries in Python: the DB-API, cursors and fetching; placeholders, SQL injection on a copy of the database, and why escaping quotes is not enough; reading results into pandas; transactions under each of sqlite3's settings, only some of which make a failed block atomic; and SQLAlchemy.

The order is the order of a query's growth: the model, then one table, then the operators and clauses that shape a result, then summaries, then several tables, then queries within queries, then programs. Each article assumes the ones before it, and the last links to the first article of the next unit, Introduction to Data Wrangling.

Where the site goes deeper

Several articles elsewhere on the site take up subjects this unit touches. Structuring Data and Exploring Data with Groups and Pivot Tables do in pandas what these articles do in SQL, and Enriching Data treats joins as pandas merges with their checks; Data Engineering places databases among warehouses, data lakes and file formats. Knowledge Graphs treats queries as conjunctive queries over triples and proves their basic properties and shows, on one of its queries, that join order changes the work but not the answer, the problem a search engine solves when it intersects postings lists in Optimizing Boolean Queries. The means computed here are unweighted sample means; Survey Weights and the Horvitz–Thompson Estimator explains what the survey's weights add, and Confounding and Causal Diagrams why a comparison such as statin users against non-users does not measure the drug's effect.

The unit is an entry point, and several subjects it names would fit a collection of their own: relational algebra and calculus and the proofs that SQL rewrites are equivalent; functional dependencies, Boyce–Codd and higher normal forms, and decomposition algorithms; indexes, query evaluation and join algorithms; transactions, isolation levels, concurrency control and recovery; database security beyond injection; and the modern engines for analytics, distributed data, vectors, graphs and time series. The site's own warehouse, an Azure SQL database whose schema and migrations are kept in the repository, supplies a real example for several of them, and Relational Databases uses its page table to illustrate surrogate keys and domain constraints.

References