← Back to SQL, page 22

sql-0438 · Medium mid

How would you test code that runs SQL, so tests are fast and do not interfere with each other?

Run tests against the same database engine as production, create the schema from migrations, and isolate each test by wrapping it in a transaction that is rolled back at the end, or by using a fresh database or schema per test worker. Keep fixtures small and explicit, and test edge cases such as NULLs, ties and empty tables.

Full answer

Practices:

  • Same engine: SQLite in tests and PostgreSQL in production hides differences in typing, NULL ordering and errors. Containers make a real PostgreSQL cheap in CI.
  • Schema from migrations: tests then also verify the migrations.
  • Isolation: begin a transaction before each test and roll back afterwards; tests that need commits (for example to test concurrency) use a separate database per worker instead.
  • Fixtures: build only the rows a test needs, with factories, so each test shows its own data.
  • Edge cases: empty results, NULL values, duplicate sort keys, time zones, large values.
  • Query counts: assert the number of queries an endpoint makes to catch N+1 regressions.
  • Plans: for critical queries, a test can assert that EXPLAIN uses an index on realistic data volumes.

Every query in this bank was run twice and the outputs compared, which is a small example of checking that results are deterministic.

Key points

  • Test on the production engine
  • Build schemas from migrations
  • Roll back per test or use per-worker databases
  • Small explicit fixtures
  • Cover NULLs, ties and empty tables

Common mistakes

  • Sharing one mutable database across parallel tests
  • Mocking the database entirely for query logic

Follow-ups

  • How would you test concurrent updates?
  • How do you keep test data realistic without copying production?

Tips

  • Mention isolation explicitly