AAmit’s LibraryLEARN · PRACTISE · REFLECT

Computers · Programming Atlas

SQL Foundations

Queries, schema, joins, grouping, NULL, transactions, fixed CLI parameters and exercises. Portable concepts are distinguished from tested SQLite behavior.

Audience: Beginners who can save plain text and run an installed command-line runtime.

Practice: 4 to 6 hours, at your own pace.

Runtime and boundaries: SQL is a language family with implementation differences. This pack executes only the installed SQLite CLI 3.54.0 on macOS 27.0.1 arm64. SELECT, WHERE, explicit joins, grouping and NULL reasoning transfer broadly, but no other engine was tested. Dot commands, PRAGMA, typeof and SQLite affinity are labeled dialect details. Open each complete .sql file with sqlite3 -batch -init /dev/null -safe :memory: followed by input redirection from its quoted filename. Each invocation gets a new disposable in-memory database; never substitute an existing database path.

Lessons

Start with a named dialect

SQL is a language family with implementation differences. This pack executes only the installed SQLite CLI 3.54.0 on macOS 27.0.1 arm64. SELECT, WHERE, explicit joins, grouping and NULL reasoning transfer broadly, but no other engine was tested. Dot commands, PRAGMA, typeof and SQLite affinity are labeled dialect details. Open each complete .sql file with sqlite3 -batch -init /dev/null -safe :memory: followed by input redirection from its quoted filename. Each invocation gets a new disposable in-memory database; never substitute an existing database path.

Read a query as a question

Name the required columns, source tables, row conditions and desired order. SELECT does not promise an order without ORDER BY. Use a stable tie breaker when equal sort keys matter. Write explicit JOIN ... ON rather than a comma join, and qualify ambiguous column names with aliases. Start with tiny records whose result you can predict by hand. A query that returns no rows is different from a query that failed; keep stderr and exit status in the test record.

Give stored rows a contract

A primary key identifies a row, UNIQUE expresses a uniqueness rule and NOT NULL prevents absence. CHECK expresses a row condition. In SQLite ordinary type declarations give affinity rather than a universal rigid type contract. Example 02 combines an integer-affinity column with a SQLite typeof check. A nullable CHECK alone does not reject NULL; use NOT NULL when required. Foreign-key declarations need enforcement enabled per SQLite connection, outside an active transaction.

Treat missing values deliberately

NULL is not zero or empty text. Use IS NULL or IS NOT NULL for presence tests. Many comparisons with NULL produce unknown and are not retained by WHERE. COUNT(*) includes all rows, while COUNT(expression) ignores NULL results. SUM of no non-NULL inputs returns NULL. Choose COALESCE only when the replacement has a stated meaning. NOT EXISTS is useful for missing relationships; NOT IN behaves differently if its candidate set includes NULL.

Join first, then count the right thing

INNER JOIN retains matching pairs; LEFT JOIN also retains unmatched rows from the left. One-to-many matches can multiply rows and inflate totals if you join several child tables at once. Count the child primary key for zero-on-no-match summaries. A right-table predicate in WHERE may remove the unmatched rows you wanted to keep; placing a matching condition in ON has different semantics. Test an unmatched parent and multiple matches before trusting an aggregate.

Group and name intermediate results

WHERE filters before aggregation; HAVING filters groups. List non-aggregate output columns in GROUP BY rather than depending on SQLite bare-column behavior. An ordinary WITH clause can name a summary for the current statement. CASE makes a result choice visible. These tools make a query understandable, but readability does not prove performance. Index selection, query plans, recursive CTEs and window functions remain later topics.

Transactions need explicit outcomes

BEGIN groups changes until COMMIT or ROLLBACK. This pack rehearses updates and reversals only in memory. Keep a specific WHERE predicate and inspect affected state. An SQL error does not always abort the entire transaction; handle failure deliberately in application code. SQLite permits only one simultaneous writer, and transaction behavior and isolation differ between engines. Nested BEGIN is not a nesting mechanism; savepoints are a later topic.

Separate values from SQL structure

Bind external values through the application driver instead of concatenating them into SQL text. Parameters represent literal values, not identifiers or keywords; choose identifiers from an allowlist in a real application. Example 07 uses only fixed authored CLI literals. SQLite .parameter set evaluates its value as an expression before fallback handling, so it is not a safe string-input API. The quote-shaped toy shows bound-query behavior, not an application security certification. Test constraints, NULL, missing rows and rollback as well as happy paths.

Reference cards

Query: SELECT columns FROM table

Name the output and its source.

Filter: WHERE condition

Keep rows whose condition is true.

Order: ORDER BY key, id

Specify deterministic ordering.

Schema: PRIMARY KEY / UNIQUE

Identity and uniqueness rules.

Schema: NOT NULL / CHECK

Presence and row-condition constraints.

SQLite: typeof(value)

SQLite storage-class inspection, not portable SQL.

Missing: IS NULL / IS NOT NULL

Test absence explicitly.

Missing: COALESCE(value, fallback)

Choose a meaningful fallback.

Join: JOIN ... ON / LEFT JOIN

Matching pairs / retain unmatched left rows.

Aggregate: COUNT(*) / COUNT(column)

Rows / non-NULL column values.

Aggregate: GROUP BY / HAVING

Form and filter group summaries.

Query: WITH name AS (...)

Name a statement-scoped query step.

Query: CASE WHEN ... THEN ... ELSE ... END

Compute a conditional result.

Query: EXISTS / NOT EXISTS

Test whether matching rows exist.

Transaction: BEGIN / COMMIT / ROLLBACK

Group, keep or reverse a toy change.

Parameters: :minimum / driver binding API

Bind values; CLI .parameter is a separate expression parser.

Examples and practice

Code below is reading material, not an execution console. Download the edition for the complete example files and companion modules.

SQL 01 Filter and order

WHERE chooses rows; ORDER BY defines the displayed order, including a tie breaker. These clauses transfer broadly, but this complete file uses SQLite CLI dot commands. Every file starts with its own data.

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE sessions (id INTEGER PRIMARY KEY, topic TEXT, minutes INTEGER);
INSERT INTO sessions VALUES (1,'HTML',20),(2,'SQL',30),(3,'SQL',10);
SELECT topic, minutes FROM sessions
WHERE minutes >= 20 ORDER BY minutes DESC, id;

Expected:

SQL|30
HTML|20
SQL 02 Define a contract

Keys identify rows, UNIQUE rejects duplicate names and NOT NULL rejects absence. SQLite affinity alone is not a rigid type contract: typeof in this CHECK is SQLite-specific. This is not portable schema DDL.

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE topics (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL UNIQUE,
  minutes INTEGER NOT NULL CHECK (typeof(minutes) = 'integer' AND minutes >= 0)
);
INSERT INTO topics VALUES (1,'SQL',25),(2,'Shell',0);
SELECT id, name, minutes FROM topics ORDER BY id;

Expected:

1|SQL|25
2|Shell|0
SQL 03 Reason about NULL

NULL represents a missing value. Equality with NULL does not become true; use IS NULL. COUNT(*) counts rows, COUNT(column) counts non-NULL values. COALESCE here uses -1 only as a display marker, not a stored replacement.

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE notes (id INTEGER PRIMARY KEY, minutes INTEGER);
INSERT INTO notes VALUES (1,10),(2,NULL),(3,0);
SELECT COUNT(*), COUNT(minutes), SUM(minutes) FROM notes;
SELECT id, COALESCE(minutes, -1) FROM notes ORDER BY id;
SELECT COUNT(*) FROM notes WHERE minutes = NULL;
SELECT COUNT(*) FROM notes WHERE minutes IS NULL;

Expected:

3|2|10
1|10
2|-1
3|0
0
1
SQL 04 Keep unmatched topics

LEFT JOIN keeps each topic even without a session. Count the non-null child key rather than COUNT(*) to show zero for an unmatched row. A right-side filter in WHERE can remove unmatched rows. PRAGMA foreign_keys is SQLite-specific and set before writes.

.bail on
.headers off
.mode list
.nullvalue NULL
PRAGMA foreign_keys = ON;
CREATE TABLE topics (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE sessions (id INTEGER PRIMARY KEY,
  topic_id INTEGER NOT NULL REFERENCES topics(id), minutes INTEGER NOT NULL);
INSERT INTO topics VALUES (1,'SQL'),(2,'Shell'),(3,'Python');
INSERT INTO sessions VALUES (1,1,20),(2,1,10),(3,2,15);
SELECT t.name, COUNT(s.id), COALESCE(SUM(s.minutes),0)
FROM topics AS t LEFT JOIN sessions AS s ON s.topic_id = t.id
GROUP BY t.id, t.name ORDER BY t.id;

Expected:

SQL|2|30
Shell|1|15
Python|0|0
SQL 05 Aggregate and filter groups

WHERE filters input rows, GROUP BY forms groups and HAVING filters group results. Every selected non-aggregate column appears in GROUP BY; avoid SQLite bare-column shortcuts when writing queries meant to transfer.

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE sessions (topic TEXT NOT NULL, minutes INTEGER NOT NULL);
INSERT INTO sessions VALUES ('SQL',20),('SQL',15),('Shell',10);
SELECT topic, COUNT(*), SUM(minutes) AS total
FROM sessions WHERE minutes > 0
GROUP BY topic HAVING SUM(minutes) >= 30 ORDER BY topic;

Expected:

SQL|2|35
SQL 06 Commit and roll back

Run only in the new in-memory database. The first change is undone; the second persists for this connection. The explicit key predicate limits the update. Do not assume every statement error rolls back a whole transaction; applications must handle errors and rollback deliberately.

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE progress (id INTEGER PRIMARY KEY, minutes INTEGER NOT NULL);
INSERT INTO progress VALUES (1,10),(2,20);
BEGIN;
UPDATE progress SET minutes = minutes + 5 WHERE id = 1;
ROLLBACK;
SELECT 'rolled back', minutes FROM progress WHERE id = 1;
BEGIN;
UPDATE progress SET minutes = minutes + 5 WHERE id = 1;
COMMIT;
SELECT 'committed', minutes FROM progress WHERE id = 1;
SELECT 'unchanged', minutes FROM progress WHERE id = 2;

Expected:

rolled back|10
committed|15
unchanged|20
SQL 07 Bind fixed toy values

The statement uses bound values, including a fixed quote-shaped string that stays data. The CLI .parameter set command itself evaluates SQL expressions; never construct it from untrusted text. In applications use the driver binding API with a fixed SQL statement. Placeholders cannot stand for table names or keywords.

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE topics (name TEXT NOT NULL, minutes INTEGER NOT NULL);
INSERT INTO topics VALUES ('SQL',30),('Shell',20);
.parameter init
.parameter set :minimum 25
SELECT name FROM topics WHERE minutes >= :minimum ORDER BY name;
.parameter set :topic "'x'' OR 1=1 --'"
SELECT COUNT(*) FROM topics WHERE name = :topic;
SELECT :topic;

Expected:

SQL
0
x' OR 1=1 --
SQL 08 Name a query step

An ordinary CTE names an intermediate query for one statement. CASE expresses a result choice. Neither is a persistent table here; a CTE is a readability tool, not a promise of a faster query.

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE sessions (topic TEXT, minutes INTEGER);
INSERT INTO sessions VALUES ('SQL',20),('SQL',15),('Shell',10);
WITH totals AS (
  SELECT topic, SUM(minutes) AS minutes FROM sessions GROUP BY topic
)
SELECT topic, minutes,
  CASE WHEN minutes >= 30 THEN 'ready' ELSE 'practice' END AS next_step
FROM totals ORDER BY topic;

Expected:

SQL|35|ready
Shell|10|practice
SQL 09 Find missing relationships

NOT EXISTS tests whether a matching row exists. This deliberately includes a NULL in the child table: a NOT IN subquery containing NULL has different three-valued logic and can surprise beginners.

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE topics (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE sessions (topic_id INTEGER);
INSERT INTO topics VALUES (1,'SQL'),(2,'Shell');
INSERT INTO sessions VALUES (1),(NULL);
SELECT name FROM topics AS t
WHERE NOT EXISTS (SELECT 1 FROM sessions AS s WHERE s.topic_id = t.id)
ORDER BY name;

Expected:

Shell
SQL Exercise A Count all topics

Count a non-null child key and group by the parent identity as well as its name. This keeps the topic with no sessions.

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE topics (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE sessions (id INTEGER PRIMARY KEY, topic_id INTEGER);
INSERT INTO topics VALUES (1,'SQL'),(2,'Shell');
INSERT INTO sessions VALUES (1,1),(2,1);
SELECT t.name, COUNT(s.id) FROM topics AS t
LEFT JOIN sessions AS s ON s.topic_id = t.id
GROUP BY t.id, t.name ORDER BY t.name;

Expected:

SQL|2
Shell|0

Practice: Return every topic and its session count, including zero. Sort names. Test a topic with no sessions.

SQL Exercise B Preserve unknown minutes

Zero is a known value; NULL is unknown. The total summarizes only the known values and must not be described as the complete total.

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE sessions (id INTEGER PRIMARY KEY, minutes INTEGER);
INSERT INTO sessions VALUES (1,0),(2,NULL),(3,15);
SELECT COUNT(*) AS rows, COUNT(minutes) AS known,
  COUNT(*) - COUNT(minutes) AS unknown,
  SUM(minutes) AS known_total FROM sessions;

Expected:

3|2|1|15

Practice: Summarize row count, known count, unknown count and known-minute total without turning unknown into zero.

SQL Exercise C Rehearse a change

The preview is a reversible transaction in an isolated in-memory toy database, not a production change plan.

.bail on
.headers off
.mode list
.nullvalue NULL
CREATE TABLE progress (id INTEGER PRIMARY KEY, minutes INTEGER CHECK(minutes >= 0));
INSERT INTO progress VALUES (1,20);
BEGIN;
UPDATE progress SET minutes = 25 WHERE id = 1;
SELECT 'preview', minutes FROM progress WHERE id = 1;
ROLLBACK;
SELECT 'restored', minutes FROM progress WHERE id = 1;

Expected:

preview|25
restored|20

Practice: Change one toy row inside a transaction, display it, roll back and prove the original value remains.

Prompt templates

These are editable planning prompts in the downloadable workbench; they do not contact an AI service here.

Build an example
Create an original {language} example for {goal}. Runtime: {runtime}. Constraints: {constraints}. State the dialect, input contract, complete files and exact expected output. Use only tiny authored inputs in an isolated local practice environment. No production data, network, secrets, installations or destructive shell commands. Distinguish proposed tests from executed evidence.
Debug a failure
Debug this {language} behavior for {goal} under {runtime}. Constraints: {constraints}. Ask for the smallest reproducer, explain the failure, and suggest a focused correction with a regression case. Use only tiny authored inputs in an isolated local practice environment. No production data, network, secrets, installations or destructive shell commands. Distinguish proposed tests from executed evidence.
Test the contract
Design tests for {goal} in {language} under {runtime}. Constraints: {constraints}. Cover empty input, boundaries, invalid values, status and side effects; provide expected outputs and an isolated test procedure. Use only tiny authored inputs in an isolated local practice environment. No production data, network, secrets, installations or destructive shell commands. Distinguish proposed tests from executed evidence.
Refactor with evidence
Refactor {goal} in {language} for clarity under {runtime}. Constraints: {constraints}. Preserve behavior, identify dialect assumptions and compare results before and after. Use only tiny authored inputs in an isolated local practice environment. No production data, network, secrets, installations or destructive shell commands. Distinguish proposed tests from executed evidence.
Document a local recipe
Document {goal} in {language} under {runtime}. Constraints: {constraints}. Explain inputs, exact invocation, outputs, failure handling, effects and limitations. Label SQLite details clearly. Use only tiny authored inputs in an isolated local practice environment. No production data, network, secrets, installations or destructive shell commands. Distinguish proposed tests from executed evidence.
Review safety and portability
Review {goal} in {language} for SQLite portability and safety under {runtime}. Constraints: {constraints}. Check quoting or binding boundaries, unintended effects and failure behavior; distinguish observed facts from assumptions. Use only tiny authored inputs in an isolated local practice environment. No production data, network, secrets, installations or destructive shell commands. Distinguish proposed tests from executed evidence.

Further reading

Download the offline edition

Complete Atlas 0.11.0 ZIP (6,079,970 bytes) · 411-page guide and catalogue PDF · Versioned source JSON

Unzip the edition and open Programming and Scripting Atlas.html, Web Foundations.html, Python Foundations.html, SQL Foundations.html, Shell Foundations.html, TypeScript Foundations.html Data Formats Foundations.html, C Foundations.html C++ Foundations.html, Ruby Foundations.html, Perl Foundations.html, Swift Foundations.html, Makefile Foundations.html, awk Foundations.html, sed Foundations.html, jq Foundations.html, XSLT 1.0 Foundations.html, Tcl Foundations.html, Expect Foundations.html or Objective-C Foundations.html locally. The original interactive workbenches retain their offline prompt-building, local presets and export controls. Read the included README before running examples yourself. The workbench does not execute pasted code or call an AI service; prompt text is for you to inspect and use separately.

Version 0.11.0 is pinned here. The other 257 registry entries remain planned; this edition does not claim complete language coverage.

Evidence and limits

Objective-C adds 12 accepted native programs, four separate compiler or warning-policy rejections, 120 root checks and 147 independent native checks. Two rejection fixtures are warnings promoted by -Werror; they are not intrinsic syntax failures. No rejected fixture was executed. Tests dated 26 October 2026 used Apple Clang 21.0.0, ARC, C17 base mode, macOS SDK 27.0 headers and system Foundation 6.9 (5027.0.69) on macOS 27.0.1 arm64. This is introductory macOS/Foundation coverage, not iOS, GNUstep, Objective-C++, UI, concurrency or cross-platform coverage. No sanitizers, leak detector, race analysis, allocation/disk-full/permission fault injection or asynchronous timing tests were run. Trusted authored fixtures and process bounds do not establish an arbitrary-code sandbox.

The pinned Atlas 0.11.0 evidence records 607 browser checks, 55 Python harness checks plus four unittest methods, 74 SQL checks, 515 shell checks across 71 runs, 99 TypeScript checks, 51 Data Formats checks, 119 C checks, 116 C++ checks, 97 Ruby checks, 97 Perl checks, 105 Swift harness checks and 97 Makefile harness checks, 145 awk checks, 145 sed checks, 161 jq checks, 157 XSLT checks, 150 Tcl checks and 161 Expect checks. These are separate measures. Tcl and Expect tests are dated 26 October 2026 on installed Tcl 8.5.9 / Expect 5.45 with Tcl 8.5.9 on macOS arm64. These old versions are recorded teaching evidence, not deployment recommendations. Tcl has 12 accepted programs and Expect has 12 accepted controllers; each has four expected evaluation failures, not static compilation passes. Tcl has nine scenarios, five expected nonzero; Expect has seven scenarios, four expected nonzero. Expect default controllers invoke 15 toy children, including two expected child failures; one scenario also expects a failed child. Controller success does not mean every child succeeds. The authoring release records 100 owned-runner regression checks and 109 independent runner checks separately. Only authored fixtures and retained native child handles are covered. Cooperative cleanup requires event-loop progress; outer-timeout child cleanup remains uncertain without complete wait receipts. The retired PID-inspection branch was not retried. No sign-ins, secrets, network or external application control are taught or tested by this pack. awk and sed are text-processing languages; their examples use fixed authored ASCII input and the C locale with installed awk 20200816 and macOS sed on one platform. jq and XSLT each have 12 accepted examples and four separately rejected programs. jq has 21 scenarios, including five contract errors and one no-result status; XSLT has 20 scenarios, including five terminating messages and one CLI parameter rejection. Expected nonzero outcomes are not successful programs. Tests dated 26 October 2026 used jq 1.7.1-apple and XSLT 1.0 with libxslt 1.1.35/libxml2 2.9.13, fixed trusted programs and tiny authored inputs in the C locale on macOS arm64. These old installed XML libraries are recorded learning environments, not recommendations for untrusted-document processing. No imports, external documents, DTDs, custom/external entities, extension functions or generated source are covered. Command flags and bounds are not a complete sandbox. Standalone XPath remains planned; supporting XPath 1.0 expressions are limited to these XSLT examples. These tests do not establish GNU-tool equivalence, Unicode behavior, arbitrary-script safety or cross-platform portability. Swift has 12 accepted programs and four expected static rejections; Makefile has 12 accepted default targets, four expected parser rejections, eight additional scenarios and one expected recipe failure. Makefile is build scripting, not a general-purpose language. The Swift and Makefile test execution dates remain 25 October 2026. awk and sed tests are dated 26 October 2026. Delivery verification does not replace or refresh test execution dates. TypeScript includes 12 accepted programs executed as JavaScript and nine intentionally invalid cases correctly rejected. Each C/C++ pack has 12 accepted programs run normally and with AddressSanitizer/UndefinedBehaviorSanitizer, plus four expected compiler rejections that are never executed. Ruby and Perl each have 12 syntax-accepted programs executed and four expected syntax rejections; rejected cases are not successful programs. Syntax checks may execute compile-time code and are not arbitrary-code sandboxes. Sanitizer results cover executed paths only; leak detection and allocation-failure injection were not tested and memory safety is not proved.

Tested environments are Chrome 155, CPython 3.9.6, SQLite CLI 3.54.0, macOS sh/Bash 3.2.57/Zsh 5.9, TypeScript 6.0.3, Node 24.18.0 Apple Clang 21.0.0, Ruby 2.6.10p210 and Perl 5.34.1, Apple Swift 6.4 in Swift 6 mode and GNU Make 3.81 on one arm64 macOS host. C uses a C17 subset; C++ uses a C++20 subset with libc++ 220106. Python 3.9.6 is unsupported upstream. Ruby 2.6 is end-of-life upstream; the recorded installed interpreter is not a recommended modern runtime. Data Formats uses installed Tomli 1.0.3 through a private fallback; the Python tomllib branch was not run. No new-installation recommendation, complete language/format conformance, schema certification, hardened untrusted XML parsing or general-purpose execution sandbox is established. Other platforms, browsers and screen readers remain unverified. The 145 official references belong to the saved Atlas review, not fresh website-time verification.