SQL essentials: 50 queries and concepts
Learn SQL that holds up in production: joins, grouping, NULL semantics, indexes, transactions, window functions and CTEs.
Practice now
Study without an account
Scheduled with the default Askesis timings. Progress is saved in this browser.
All 50 cards
- 1Select active users’ names and emailssql
SELECT name, email FROM users WHERE active = true; - 2
WHEREvsHAVINGWHEREfilters rows before grouping;HAVINGfilters groups after aggregation - 3Count orders per customersql
SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id; - 4Customers with more than 5 orderssql
SELECT customer_id FROM orders GROUP BY customer_id HAVING COUNT(*) > 5; - 5Default direction of
ORDER BYAscending (ASC) - 6Paginate with
LIMITandOFFSETsqlSELECT * FROM posts ORDER BY id LIMIT 20 OFFSET 40;Large offsets get slow; keyset pagination (WHERE id > last_id) scales better. - 7
COUNT(*)vsCOUNT(column)COUNT(*)counts rows;COUNT(column)counts non-NULL values in that column - 8What is
NULL = NULL?NULL (unknown), not true. Test withIS NULL/IS NOT NULL - 9Replace NULL with a defaultsql
SELECT COALESCE(nickname, name) FROM users;COALESCEreturns its first non-NULL argument. - 10
INNER JOINOnly rows that have a match in both tables - 11
LEFT JOINEvery row from the left table, with NULLs where the right table has no match - 12
FULL OUTER JOINEvery row from both tables, with NULLs wherever one side has no match - 13
CROSS JOINEvery combination of rows from both tables (the Cartesian product) - 14Self join examplesql
SELECT e.name, m.name AS manager FROM employees e LEFT JOIN employees m ON m.id = e.manager_id; - 15Find customers with no orderssql
SELECT c.* FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL;NOT EXISTSworks too. - 16Pitfall of
NOT IN (subquery)If the subquery returns any NULL,NOT INmatches no rows; preferNOT EXISTS - 17
DISTINCTRemoves duplicate rows from the result - 18
UNIONvsUNION ALLUNIONremoves duplicates;UNION ALLkeeps every row and is faster - 19Wildcards in
LIKE%matches any sequence of characters;_matches exactly onesqlWHERE email LIKE '%@example.com' - 20Conditional values with
CASEsqlSELECT name, CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END AS grade FROM results; - 21The five standard aggregate functions
COUNT,SUM,AVG,MIN,MAX - 22Primary keyA column (or set of columns) that uniquely identifies each row; unique and not NULL
- 23Foreign keyA column that references a key in another table, enforcing referential integrity
- 24
ON DELETE CASCADEDeleting a parent row also deletes the rows that reference it - 25Does a
UNIQUEcolumn allow several NULLs?In PostgreSQL and most databases, yes: NULLs aren’t equal to each otherSQL Server allows only one NULL in a unique index. - 26What does an index trade off?Faster reads and lookups for slower writes and extra storage
- 27Column order in a composite index on (a, b)It helps queries filtering on
a, oraandb, but notbalone (leftmost prefix rule) - 28
EXPLAINvsEXPLAIN ANALYZEEXPLAINshows the planned execution;EXPLAIN ANALYZEruns the query and shows real timings - 29NormalizationStructuring tables to reduce redundancy and update anomalies (1NF, 2NF, 3NF, …)
- 30First normal form (1NF)Every column holds atomic values; no repeating groups
- 31Run statements as one transactionsql
BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT; - 32ACIDAtomicity, Consistency, Isolation, Durability
- 33The four standard isolation levelsRead uncommitted, Read committed, Repeatable read, Serializable
- 34Dirty readReading another transaction’s changes before it commits
- 35Number rows per group with a window functionsql
SELECT *, ROW_NUMBER() OVER ( PARTITION BY user_id ORDER BY created_at ) AS n FROM reviews; - 36
RANKvsDENSE_RANKRANKleaves gaps after ties (1, 1, 3);DENSE_RANKdoesn’t (1, 1, 2) - 37Running totalsql
SELECT day, SUM(amount) OVER (ORDER BY day) AS running_total FROM sales; - 38
LAGandLEADWindow functions that read a value from the previous or next row - 39Common table expression (CTE)sql
WITH recent AS ( SELECT * FROM orders WHERE created_at > now() - interval '7 days' ) SELECT COUNT(*) FROM recent; - 40What is
WITH RECURSIVEfor?Querying hierarchies and graphs, like a category tree or an org chart - 41Upsert in PostgreSQLsql
INSERT INTO tags (name) VALUES ('sql') ON CONFLICT (name) DO NOTHING;UseDO UPDATE SET …to update the existing row instead. - 42
DELETEvsTRUNCATEDELETEremoves chosen rows one by one;TRUNCATEempties the whole table at once and is much faster - 43Add a column to a tablesql
ALTER TABLE users ADD COLUMN bio text; - 44How do you prevent SQL injection?Use parameterized queries; never concatenate user input into SQL
- 45View vs materialized viewA view runs its query each time; a materialized view stores the result until refreshed
- 46Logical order a
SELECTis evaluated inFROM→WHERE→GROUP BY→HAVING→SELECT→ORDER BY→LIMIT - 47Correlated subqueryA subquery that refers to the outer query, so it is evaluated for each outer row
- 48
CHAR(n)vsVARCHAR(n)CHARis fixed-length and padded;VARCHARstores variable-length strings up to n - 49Why can’t you use a
SELECTalias inWHERE?WHEREis evaluated beforeSELECT, so the alias doesn’t exist yet - 50Second-highest salarysql
SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 1;
Frequently asked questions
Which database does this deck use?
Standard SQL, with PostgreSQL syntax where dialects differ (like ON CONFLICT for upserts).
Is it useful for data analysis interviews?
Yes. Joins, grouping, NULL handling and window functions make up most SQL interview questions.
Why does NOT IN sometimes return nothing?
If the subquery yields a NULL, every comparison becomes unknown, so no rows match. NOT EXISTS avoids this.
More in Databases
PostgreSQL
PostgreSQL know-how: data types, B-tree and GIN indexes, EXPLAIN, isolation levels, MVCC and VACUUM, JSONB, CTEs, window functions, constraints and roles.
50 cardsMongoDB
MongoDB basics: documents and BSON, CRUD in mongosh, query operators, indexes, the aggregation pipeline, embedding vs referencing, replica sets and sharding.
50 cardsRedis
Redis basics: strings, lists, sets, sorted sets, hashes and streams, TTLs, RDB and AOF persistence, pub/sub, caching patterns, eviction and MULTI/EXEC.
50 cards