0. Workflow (before you write SQL)

  1. md5sum file.db and compare with the task. Precondition only, not needed in the report.
  2. cp old.db work.db. Never touch the original.
  3. .tables, .schema, then SELECT * FROM t LIMIT 5; and check the real formats (dates, zip type, NULLs).
  4. Turn every output column into a written rule (e.g. “age = current year - birth year”, “7 stars”).
  5. Build the SELECT or UPDATE, check the first 5 rows by hand, check COUNT(*).
  6. Export, then verify the CSV/DB (row count, header, one row by hand).
  7. 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

GoalSQLExample result
first N charssubstr(x,1,N)substr('Mike',1,1) -> M
last N charssubstr(x,-N)substr('10.04.2001',-4) -> 2001
from position (1-based)substr(x,start) / substr(x,start,len)substr('hello',2,3) -> ell
concatenatea | b'u' | '0042' -> u0042
position of text (0 = none)instr(x,'@')instr('a@b.com','@') -> 2
everything from @substr(x, instr(x,'@'))@b.com
lengthlength(x)5
upper / lowerupper(x), lower(x)
replacereplace(x,'-','+')a+b
trim spacestrim(x)
zero paddingprintf('%05d', n)00042
decimalsprintf('%.2f', n)3.14
to number / textCAST(x AS INTEGER), CAST(x AS TEXT)
first non-NULLCOALESCE(x,'never')
if / elseCASE WHEN c1 THEN a WHEN c2 THEN b ELSE d END
patternx 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

GoalSQL
random 10-digit number (no leading 0)CAST(1000000000 + abs(random() % 9000000000) AS TEXT)
random 10 digits with leading zerosprintf('%010d', abs(random() % 10000000000))
current yearCAST(strftime('%Y','now') AS INTEGER)
Unix timestamp -> UTC textstrftime('%d.%m.%Y %H:%M', ts, 'unixepoch')
Unix timestamp -> ISO UTCdatetime(ts,'unixepoch')
text date -> Unix timestampstrftime('%s','2022-12-03 23:00:00')
roundround(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 NULL in 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

PitfallFix
"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 0substr(x,1,2) = first two chars
COUNT(*) after a LEFT JOIN counts the NULL rowCOUNT(right_table.pk)
INNER JOIN silently drops rowsCompare COUNT(*) before and after
Date format assumedSELECT date FROM t LIMIT 5; first (DD.MM.YYYY vs YYYY-MM-DD)
Birth year is text, subtraction needs numbersCAST(... AS INTEGER)
strftime(..., 'unixepoch') is UTC, Python fromtimestamp() is local timeState 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 WHERETest on a copy, check changes() afterwards
DROP COLUMN fails on SQLite < 3.35Use the rebuild pattern
Deleted data stays in the fileVACUUM last
No hash or regex functions in plain SQLiteUse Python (hmac, re)
Stars or dashes miscountedSELECT 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.