Writing SQL Queries
Read and write data with SELECT, JOIN, GROUP BY, subqueries and window functions.
Beginner · about 12 hours · difficulty 2/5
Learn first: The Relational Model
SQL is the language for talking to relational databases, and it is one of the most durable skills in software. Even if you use an ORM daily, you need to read and write SQL to debug and optimize.
Build up in this order
- CRUD:
SELECT ... FROM ... WHERE,INSERT,UPDATE,DELETE. Always double-check theWHEREclause on updates and deletes. - Sorting and limiting:
ORDER BY,LIMIT,OFFSET. - Joins:
INNER JOIN(only matches),LEFT JOIN(keep all rows from the left even without a match). These answer most real questions. - Aggregation:
COUNT,SUM,AVG,GROUP BYandHAVING(filter after grouping). - Subqueries and CTEs:
WITH recent AS (...) SELECT ...makes complex queries readable. - Window functions:
ROW_NUMBER(),RANK(), running totals withSUM() OVER (...). - Upserts:
INSERT ... ON CONFLICT DO UPDATEin PostgreSQL.
Safety
Never build SQL by concatenating user input. Use parameterized queries (WHERE email = $1) so the driver sends data separately from the query text. This prevents SQL injection.
Pitfalls
NULLis not equal to anything, includingNULL. UseIS NULL.SELECT *in application code hides which columns you depend on and fetches more than needed.
You are ready to move on when you can answer "top 5 customers by revenue last month, including customers with zero orders" in a single query.
Key concepts
- SELECT, INSERT, UPDATE, DELETE
- INNER and LEFT JOIN
- GROUP BY and HAVING
- Subqueries and CTEs
- Window functions
- Upserts
- Parameterized queries: Your main defense against SQL injection.
- NULL semantics
Mini project
Load a sample dataset (for example the PostgreSQL Pagila or a Kaggle CSV) and write 15 progressively harder queries, ending with window functions and CTEs.
Check yourself
Why does a LEFT JOIN followed by a WHERE condition on the right table sometimes behave like an INNER JOIN?
Free resources
- SQLBolt interactive lessons (SQLBolt)
- PostgreSQL: Queries (PostgreSQL)
- Select Star SQL (selectstarsql.com)