SQL Cheat sheet
0. Workflow (before you write SQL)
md5sum file.dband compare with the task. Precondition only, not needed in the report.cp old.db work.db. Never touch the original..tables,.schema, thenSELECT * FROM t LIMIT 5;and check the real formats (dates, zip type, NULLs).- Turn every output column into a written rule (e.g. “age = current year - birth year”, “7 stars”).
- Build the SELECT or UPDATE, check the first 5 rows by hand, check
COUNT(*). - Export, then verify the CSV/DB (row count, header, one row by hand).
- Report: tool, SQLite version, exact commands, 2-3 lines of output. Candidate number and title last.
1. Statements
-- read
SELECT col1, col2 FROM t WHERE col3 > 5 ORDER BY col1 DESC LIMIT 10;
SELECT COUNT(*), COUNT(col), COUNT(DISTINCT col) FROM t; -- COUNT(col) skips NULL
-- change values in place
UPDATE t SET col = <expr> WHERE <cond>; -- without WHERE = all rows
-- joins
SELECT ... FROM a JOIN b ON b.fk = a.pk; -- INNER: rows without match disappear
SELECT ... FROM a LEFT JOIN b ON b.fk = a.pk; -- keeps rows without match (NULL)
-- group
SELECT fk, COUNT(*), MAX(ts) FROM b GROUP BY fk HAVING COUNT(*) > 1;
-- structure
.schema -- CLI: shows CREATE statements
PRAGMA table_info(t); -- columns and types
ALTER TABLE t DROP COLUMN c; -- needs SQLite >= 3.35
VACUUM; -- rewrite file, purges old data from free pages
Order of clauses: SELECT -> FROM -> JOIN -> WHERE -> GROUP BY -> HAVING -> ORDER BY -> LIMIT.
2. String changes / operations
| Goal | SQL | Example result |
|---|---|---|
| first N chars | substr(x,1,N) | substr('Mike',1,1) -> M |
| last N chars | substr(x,-N) | substr('10.04.2001',-4) -> 2001 |
| from position (1-based) | substr(x,start) / substr(x,start,len) | substr('hello',2,3) -> ell |
| concatenate | a | b | 'u' | '0042' -> u0042 |
| position of text (0 = none) | instr(x,'@') | instr('a@b.com','@') -> 2 |
everything from @ | substr(x, instr(x,'@')) | @b.com |
| length | length(x) | 5 |
| upper / lower | upper(x), lower(x) | |
| replace | replace(x,'-','+') | a+b |
| trim spaces | trim(x) | |
| zero padding | printf('%05d', n) | 00042 |
| decimals | printf('%.2f', n) | 3.14 |
| to number / text | CAST(x AS INTEGER), CAST(x AS TEXT) | |
| first non-NULL | COALESCE(x,'never') | |
| if / else | CASE WHEN c1 THEN a WHEN c2 THEN b ELSE d END | |
| pattern | x LIKE 'A%' (% = any, _ = one char) | case-insensitive for ASCII |
Repeat a character: no repeat() in SQLite. Write the stars literally ('*********') or use replace(hex(zeroblob(n)),'00','*'). Count your stars.
Numbers / dates
| Goal | SQL |
|---|---|
| random 10-digit number (no leading 0) | CAST(1000000000 + abs(random() % 9000000000) AS TEXT) |
| random 10 digits with leading zeros | printf('%010d', abs(random() % 10000000000)) |
| current year | CAST(strftime('%Y','now') AS INTEGER) |
| Unix timestamp -> UTC text | strftime('%d.%m.%Y %H:%M', ts, 'unixepoch') |
| Unix timestamp -> ISO UTC | datetime(ts,'unixepoch') |
| text date -> Unix timestamp | strftime('%s','2022-12-03 23:00:00') |
| round | round(x,1) |
unixepoch is UTC. Add 'localtime' only if the task wants local time.
Bucketing (CASE runs top to bottom)
CASE WHEN salary IS NULL THEN NULL
WHEN salary < 50000 THEN 'low'
WHEN salary < 100000 THEN 'medium' -- exactly 50000 lands here
ELSE 'high' END -- exactly 100000 lands here
3. Examples from past tasks (one statement does everything)
3a. t_person: anonymize in place (UPDATE + rebuild + VACUUM)
Task: first name = first char + 9 *, last name = random 10 digits, birth date -> year, salary -> low/medium/high, remove username, password, is_vip.
UPDATE t_person SET
first_name = substr(first_name,1,1) || '*********',
last_name = CAST(1000000000 + abs(random() % 9000000000) AS TEXT),
date_of_birth = CAST(substr(date_of_birth,-4) AS INTEGER), -- DD.MM.YYYY; for YYYY-MM-DD use substr(...,1,4)
salary = CASE WHEN salary IS NULL THEN NULL
WHEN salary < 50000 THEN 'low'
WHEN salary < 100000 THEN 'medium'
ELSE 'high' END;
-- rebuild: drops the 3 columns AND fixes salary type (works on old SQLite, no DROP COLUMN needed)
-- adapt the column list to the real .schema!
CREATE TABLE t_person_new ("Id" INTEGER, "salutation" TEXT, "first_name" TEXT, "last_name" TEXT,
"date_of_birth" NUMERIC, "salary" TEXT, "date_of_creation" NUMERIC, PRIMARY KEY("Id"));
INSERT INTO t_person_new SELECT "Id", salutation, first_name, last_name, date_of_birth, salary, date_of_creation FROM t_person;
DROP TABLE t_person;
ALTER TABLE t_person_new RENAME TO t_person;
VACUUM;
Order matters: UPDATE first, then rebuild, then VACUUM last. Alternative to the rebuild (SQLite >= 3.35): ALTER TABLE t_person DROP COLUMN username; for each column. Weak point: random() can produce duplicates (the task does not ask for uniqueness).
3b. c3 customers -> CSV (3 tables, 2 JOINs)
Columns: gender, lastname, birthyear, zip, status. Last name = first 2 chars + 8 -, birth year only, zip = first 2 digits + 00.
SELECT c.gender,
substr(c.lastname,1,2) || '--------' AS lastname,
substr(c.birthdate,-4) AS birthyear,
substr(l.zip,1,2) || '00' AS zip,
s.status
FROM t_customer c
JOIN t_location l ON c.fk_location = l.pk_location
JOIN t_customer_status s ON c.fk_customer_status = s.pk_customer_status;
Check: SELECT COUNT(*) FROM t_customer; must equal the number of CSV rows. An INNER JOIN drops customers with NULL or orphaned foreign keys.
3c. c4 active users -> CSV (LEFT JOIN + GROUP BY)
Columns: id, email, age, cntlogins, lastlogin. Rules: id = u + 4-digit key, email = first 3 chars + 7 * + domain with @, age = plain year difference, last login in UTC dd.mm.yyyy hh:mm.
SELECT 'u' || printf('%04d', u.pk_user) AS id,
substr(u.email,1,3) || '*******' || substr(u.email, instr(u.email,'@')) AS email,
CAST(strftime('%Y','now') AS INTEGER) - CAST(substr(u.birthdate,-4) AS INTEGER) AS age,
COUNT(l.pk_login) AS cntlogins,
strftime('%d.%m.%Y %H:%M', MAX(l.timestamp), 'unixepoch') AS lastlogin
FROM t_user u
JOIN t_status s ON s.pk_status = u.fk_status
LEFT JOIN t_login l ON l.fk_user = u.pk_user
WHERE s.status = 'active'
GROUP BY u.pk_user
ORDER BY u.pk_user;
COUNT(l.pk_login)gives 0 for users without logins (COUNT(*)would give 1).- Users without logins get
NULLin lastlogin (an empty cell in the CSV).COALESCE(..., '')if the task wants something else. 'now'changes every year. State the year you used in the report.- Past mistakes on this task: 8 stars instead of 7, birthday-aware age, local time, 2-digit year.
4. Export into CSV
a) sqlite3 CLI (CLI commands NOT tested here)
.headers on
.mode csv
.output out.csv
SELECT ... ; -- your query
.output stdout
One-liner from the shell:
sqlite3 -header -csv work.db "SELECT ..." > out.csv
Check afterwards: head -3 out.csv; wc -l out.csv (rows + 1 header line).
b) Python, standard library only
import sqlite3, csv
con = sqlite3.connect("work.db")
cur = con.execute("SELECT ...")
with open("out.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow([d[0] for d in cur.description]) # header = column aliases
w.writerows(cur) # NULL -> empty cell
Header names come from AS alias, so name the columns exactly as the task requires.
5. Export into a new database
a) ATTACH + CREATE TABLE … AS (quick)
ATTACH 'anon.db' AS n;
CREATE TABLE n.customer_anon AS
SELECT c.gender, substr(c.lastname,1,2)||'--------' AS lastname, substr(c.birthdate,-4) AS birthyear
FROM t_customer c;
DETACH n;
Weakness: CREATE TABLE ... AS loses types and the primary key (the columns come out untyped). If types matter, use b).
b) ATTACH + explicit schema (clean types)
ATTACH 'anon.db' AS n;
CREATE TABLE n.person (id INTEGER PRIMARY KEY, first_name TEXT, salary TEXT);
INSERT INTO n.person SELECT Id, substr(first_name,1,1)||'*********', CASE ... END FROM t_person;
DETACH n;
c) Copy the whole DB, then anonymize the copy (safest)
cp old.db anon.db # or in SQL: VACUUM INTO 'anon.db'; (SQLite >= 3.27)
sqlite3 anon.db < anonymize.sql
VACUUM INTO writes a compact copy of the DB, which also leaves out old free pages.
Check the result
SELECT sql FROM sqlite_master; -- schema as intended?
SELECT COUNT(*) FROM t_person; -- same count as the source?
PRAGMA integrity_check; -- ok
Raw-file check for leftovers (shell):
strings anon.db | grep -i -E "password|username|<an old value>" # should print nothing
6. Pitfalls
| Pitfall | Fix |
|---|---|
"00" (double quotes) is an identifier in SQL. SQLite falls back to a string only when no such column exists. | Strings always in single quotes: '00' |
substr starts at 1, not 0 | substr(x,1,2) = first two chars |
COUNT(*) after a LEFT JOIN counts the NULL row | COUNT(right_table.pk) |
| INNER JOIN silently drops rows | Compare COUNT(*) before and after |
| Date format assumed | SELECT date FROM t LIMIT 5; first (DD.MM.YYYY vs YYYY-MM-DD) |
| Birth year is text, subtraction needs numbers | CAST(... AS INTEGER) |
strftime(..., 'unixepoch') is UTC, Python fromtimestamp() is local time | State UTC explicitly in the report |
SQLite does not enforce column types (except STRICT tables) | A TEXT value in an INTEGER column works. Rebuild the table if the type matters |
UPDATE without WHERE | Test on a copy, check changes() afterwards |
DROP COLUMN fails on SQLite < 3.35 | Use the rebuild pattern |
| Deleted data stays in the file | VACUUM last |
| No hash or regex functions in plain SQLite | Use Python (hmac, re) |
| Stars or dashes miscounted | SELECT length(first_name) FROM t LIMIT 5; (must be 10) |
7. Report template (keep it short, show evidence)
Candidate Nr.: <number>
Task: <exact title of this task>
Tools: sqlite3 shell <version> (SELECT sqlite_version();), <other tools>
Steps:
1. cp old.db work.db
2. <exact command / query>
3. <export command>
Output (excerpt): <2-3 lines or row count, e.g. 2000 rows>
Check: row count matches source (2000 = 2000), header correct, first row verified by hand
Last 60 seconds: candidate number filled in, title matches the task, file names correct, ZIP contains the CSV/DB and the PDF.