SQL
Querying and shaping relational data.
SQL remains the common language of data, from product databases to analytics warehouses. Product engineers use it to build features and to answer product questions without waiting for an analyst. Joins, aggregations and window functions cover most needs.
Why it matters for a product engineer
SQL is the common language of data, from the product database to the analytics warehouse. A product engineer uses it to build features and to answer product questions without waiting for an analyst: how many teams used the new export, where a funnel drops, which accounts are about to churn. Joins, aggregations and window functions cover most needs.
How to do it
- Start from the question in plain words, then write the query that answers it.
- Check the numbers on a small case you can count by hand before you trust the total.
- Learn joins well. Most wrong answers come from a join that silently duplicates or drops rows.
- Use window functions for running totals, rankings and “the first event per user”.
- Read the query plan for anything that runs often, and check that it uses an index.
- Keep useful queries in the repository, with a sentence on what they answer.
Common mistakes
- Functions on an indexed column in the
WHEREclause, which stop the index from being used. LIKE '%term%'for search. A leading wildcard cannot use a normal index.- Counting rows after a join that multiplied them.
- Analysis queries on the production database at peak time.
Example
Markus Winand’s three-minute SQL quiz had been taken more than 28,000 times by 2014, and 60% of people failed it. The first question shows an index on a date column and a query that filters on the year, using a function on that column. Only about two thirds saw that the function stops the index from being used. MySQL users scored 55%, close to guessing. PostgreSQL users scored 83%.
Finding the rows of 2012 with an index on date_column
| A function on the column | A range on the column | |
|---|---|---|
| The condition | TO_CHAR( date_column, 'YYYY' ) = '2012' | date_column >= '2012-01-01' AND date_column < '2013-01-01' |
| Uses the index | No | Yes |
| Also works for | Whole years only | Any range: a week, a month |
Both queries return the same rows. Only the second lets the database use the index, and it needs no new index.
ReportedMarkus Winand, Use the index, Luke, 20 Feb 2014
Sources: Use the index, Luke (Markus Winand) ↗ · Results of the SQL performance quiz: 60% fail (Markus Winand) ↗
Resources
1- bookGo deeper
Use the index, Luke ↗
Markus Winand · free online bookSQL indexing explained for developers, across the major databases. It prevents most slow queries.
Tools
1- ToolOpen source