Databases (SQL, Postgres, Drizzle, MongoDB, Supabase)
SQL vs NoSQL
Section titled “SQL vs NoSQL”Q (basic): SQL vs NoSQL: when would you pick each?
Say this (30 sec): SQL (Postgres, MySQL) has a fixed schema, relations with joins, strong ACID transactions, and a powerful query language. Pick it when data is relational and consistency matters: users, orders, payments, or a social graph with likes and follows. NoSQL comes in several kinds: document (MongoDB), key-value (Redis), wide-column (Cassandra), and graph (Neo4j). It has a flexible schema and scales horizontally more easily. Pick it for varied or changing data shapes, very high write volume, or data read as one unit, like a whole document. My default is Postgres unless there’s a clear reason not to.
Common wrong answer: “NoSQL is faster” or “NoSQL has no transactions.” MongoDB has supported multi-document ACID transactions since 4.0. Speed depends on the access pattern.
Q (mid): What is the CAP theorem?
Say this: In a distributed system, during a network partition you must choose between Consistency (every read sees the latest write) and Availability (every request gets a response). You can’t fully have both. Partition tolerance isn’t optional in a real network, so the real choice is CP vs AP while a partition is happening.
Postgres fundamentals
Section titled “Postgres fundamentals”Q (basic): Explain the types of JOINs.
Say this (30 sec):
- INNER JOIN: only rows that match in both tables.
- LEFT JOIN: all rows from the left table, plus matches from the right. Unmatched right columns are NULL.
- RIGHT JOIN: the mirror of LEFT.
- FULL OUTER JOIN: all rows from both tables, with NULLs where there’s no match.
- CROSS JOIN: the Cartesian product (every combination).
- SELF JOIN: a table joined to itself, e.g. employee and manager.
Example (users with no posts, a classic):
SELECT u.* FROM users uLEFT JOIN posts p ON p.user_id = u.idWHERE p.id IS NULL;Q (basic): What is an index and how does it work?
Say this (30 sec): An index is a separate data structure that lets the DB find rows without scanning the whole table, like the index at the back of a book. Postgres’s default is a B-tree, a balanced tree with sorted keys. It supports =, <, >, BETWEEN, ORDER BY, and prefix LIKE 'abc%'. Lookups are O(log n) instead of O(n). Other types: Hash (equality only), GIN (arrays, JSONB, full-text search), GiST (geo and ranges), and BRIN (huge, naturally ordered tables like time series).
Follow-ups they ask: “Are primary keys indexed?” Yes. PRIMARY KEY and UNIQUE constraints create indexes automatically. Foreign keys are not indexed automatically in Postgres, so add those yourself.
Q (mid): When do indexes hurt or not get used?
Say this (30 sec): They slow down writes, because every INSERT, UPDATE, or DELETE has to update each index. They also use disk and memory. They may not be used when:
- the query returns a large share of the table (a sequential scan is cheaper),
- the column has low cardinality, e.g. a boolean,
- you wrap the column in a function, e.g.
WHERE LOWER(email) = ...(fix with an expression index), - you use a leading wildcard,
LIKE '%abc', - there’s a type mismatch or implicit cast,
- the query skips the leftmost column of a composite index.
Q (tricky): How does composite index column order matter?
Say this (30 sec): Index (user_id, created_at) is sorted by user_id first, then by created_at within each user. It helps WHERE user_id = ? and WHERE user_id = ? ORDER BY created_at DESC. It does not help WHERE created_at > ? alone. Rule of thumb: put equality-filtered columns first, then range or sort columns.
Example: A feed query WHERE user_id = $1 ORDER BY created_at DESC LIMIT 20 works best with an index on (user_id, created_at DESC).
Q (mid): How do you find out why a query is slow?
Say this: Run EXPLAIN ANALYZE. It runs the query and shows the real plan with timings. Look for Seq Scan on large tables where you expected an Index Scan, big gaps between estimated and actual rows (stale stats, so run ANALYZE), and expensive sorts or nested loops. Then add or adjust indexes, rewrite the query, or cut down the rows returned. Use pg_stat_statements to find the slowest queries across the app.
Common wrong answer: Saying plain EXPLAIN shows real timings. It only shows estimates. ANALYZE actually runs the query, so be careful with UPDATE or DELETE. Wrap those in a transaction and roll back.
Q (mid): Explain normalization: 1NF, 2NF, 3NF.
Say this (30 sec):
- 1NF: atomic values, no repeating groups. Don’t store
tags = "a,b,c"in one column. - 2NF: 1NF, plus every non-key column depends on the whole primary key. This matters for composite keys.
- 3NF: 2NF, plus no transitive dependencies. Non-key columns depend only on the key, not on other non-key columns. For example, don’t store
city_nameinuserswhen it depends oncity_id.
Short version: “The key, the whole key, and nothing but the key.”
Follow-ups they ask: “When do you denormalize?” For read-heavy paths, like storing a likes_count on posts. You trade write complexity for faster reads.
Q (basic): What are transactions and ACID?
Say this (30 sec): A transaction groups statements so they all succeed or all fail.
- Atomicity: all or nothing.
- Consistency: constraints hold before and after.
- Isolation: concurrent transactions don’t interfere in ways they shouldn’t.
- Durability: once committed, data survives a crash (thanks to the write-ahead log, WAL).
Example: a money transfer. Debit A and credit B in one transaction.
Example:
BEGIN;UPDATE accounts SET balance = balance - 100 WHERE id = 1;UPDATE accounts SET balance = balance + 100 WHERE id = 2;COMMIT; -- or ROLLBACK on errorQ (tricky): Isolation levels and the anomalies they prevent?
Say this (30 sec):
- Dirty read: reading uncommitted data.
- Non-repeatable read: the same row returns different values within one transaction.
- Phantom read: the same query returns a different set of rows.
| Level | Dirty | Non-repeatable | Phantom |
|---|---|---|---|
| Read Uncommitted | possible* | possible | possible |
| Read Committed (PG default) | no | possible | possible |
| Repeatable Read | no | no | possible* |
| Serializable | no | no | no |
*In Postgres, Read Uncommitted behaves like Read Committed, and Repeatable Read also prevents phantoms (it uses snapshot isolation). Serializable can fail with serialization errors, so the app must retry.
Follow-ups they ask: “How do you prevent two users booking the last seat?” Use SELECT ... FOR UPDATE (a row lock), an atomic UPDATE ... WHERE seats > 0, or a unique constraint.
Q (mid): What is the N+1 query problem?
Say this (30 sec): You fetch a list of N posts with 1 query, then loop and fetch each post’s author with N more queries. With 100 posts that’s 101 round trips. Fix it with a JOIN, a single WHERE id IN (...) query, or the ORM’s eager loading. In Drizzle, use the relational query with: { author: true } or a join. In GraphQL, use DataLoader.
Example:
// Bad: N+1for (const p of posts) p.author = await db.query.users.findFirst({ where: eq(users.id, p.authorId) });// Goodconst rows = await db.query.posts.findMany({ with: { author: true } });Q (mid): What is connection pooling and why is it needed?
Say this (30 sec): Opening a Postgres connection is expensive: TCP, TLS, auth, and Postgres starts a whole backend process for each connection. A pool keeps a set of open connections and lends them out per query. Postgres also has a limited max_connections. In serverless setups, many function instances can each open connections and exhaust the DB. That’s why we use PgBouncer, Supabase’s pooler (Supavisor), or Hyperdrive on Workers.
Follow-ups they ask: “Transaction mode vs session mode in PgBouncer?” In transaction mode, a connection goes back to the pool after each transaction, so it scales better. But session features like session-level prepared statements and SET might not work.
Q (basic): What are migrations?
Say this: Migrations are versioned, ordered scripts that change the DB schema: create tables, add columns, add indexes. They’re committed to Git so every environment reaches the same schema the same way. Rules: never edit a migration that has already been applied; make backward-compatible changes (add a nullable column first, backfill, then make it NOT NULL); and run migrations in CI/CD before or while deploying.
Q (mid): DELETE vs TRUNCATE vs DROP?
Say this: DELETE removes rows one at a time, accepts WHERE, fires triggers, and can be rolled back. TRUNCATE removes all rows quickly with no row-by-row scan. In Postgres it’s transactional and can be rolled back. DROP removes the whole table, including its structure.
Q (basic): Primary key vs foreign key vs unique?
Say this: A primary key uniquely identifies each row, is NOT NULL, and there’s one per table. A foreign key references another table’s key and enforces referential integrity, with options like ON DELETE CASCADE. A unique constraint means no duplicates, but it allows NULLs (multiple NULLs by default in Postgres).
SQL query exercises
Section titled “SQL query exercises”Q (basic): Find the second highest salary.
Example:
-- Option 1: handles duplicates of the top salarySELECT MAX(salary) FROM employeesWHERE salary < (SELECT MAX(salary) FROM employees);
-- Option 2: DISTINCT + OFFSETSELECT DISTINCT salary FROM employeesORDER BY salary DESCLIMIT 1 OFFSET 1;
-- Option 3: Nth highest with a window functionSELECT salary FROM ( SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees) t WHERE rnk = 2 LIMIT 1;Common wrong answer: ORDER BY salary DESC LIMIT 1 OFFSET 1 without DISTINCT. If two people share the top salary, it returns the top salary again.
Q (basic): GROUP BY with HAVING: departments with more than 5 employees.
Example:
SELECT department_id, COUNT(*) AS cnt, AVG(salary) AS avg_salFROM employeesWHERE active = true -- filters rows before groupingGROUP BY department_idHAVING COUNT(*) > 5 -- filters groups after aggregationORDER BY cnt DESC;Say this: The logical order is FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. That’s why you can’t use an aggregate in WHERE, and (in standard SQL) why a SELECT alias can’t be used in WHERE.
Q (mid): Top N per group: top 3 highest-paid per department.
Example:
SELECT * FROM ( SELECT e.*, ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn FROM employees e) tWHERE rn <= 3;Say this: ROW_NUMBER gives a unique 1, 2, 3. RANK handles ties with gaps (1, 1, 3). DENSE_RANK handles ties without gaps (1, 1, 2). Pick based on how ties should count.
Q (mid): Find and delete duplicate emails.
Example:
-- findSELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;
-- delete duplicates, keep the lowest idDELETE FROM users aUSING users bWHERE a.email = b.email AND a.id > b.id;Follow-ups they ask: “How do you prevent it?” Add a UNIQUE constraint on email, ideally on LOWER(email) or using the citext type.
Q (mid): Each user's latest post.
Example:
-- Postgres-specific, conciseSELECT DISTINCT ON (user_id) user_id, id, content, created_atFROM postsORDER BY user_id, created_at DESC;You can also use the ROW_NUMBER() ... WHERE rn = 1 pattern.
Q (basic): Employees earning more than their manager (self join).
Example:
SELECT e.name FROM employees eJOIN employees m ON e.manager_id = m.idWHERE e.salary > m.salary;ORMs: Drizzle
Section titled “ORMs: Drizzle”Q (basic): What is Drizzle ORM and why did you choose it over Prisma?
Say this (30 sec): Drizzle is a TypeScript ORM where you define the schema in TS and queries look like SQL: db.select().from(users).where(eq(users.id, 1)). Types are inferred straight from the schema, with no code generation step. I chose it because it’s lightweight with no heavy query engine, so it works on Cloudflare Workers and other edge runtimes. It’s “if you know SQL, you know Drizzle”, and it has a relational query API for nested data. Prisma has a great DX and a mature ecosystem, but historically it shipped a Rust query engine and a generated client. That made bundles bigger and edge deployment harder. Newer Prisma versions have reduced that gap.
Common wrong answer: “Drizzle is faster than raw SQL.” It’s a thin layer. The win is type safety with very little overhead.
Q (mid): Show a Drizzle schema and query.
Example:
import { pgTable, serial, text, integer, timestamp, index } from 'drizzle-orm/pg-core';
export const users = pgTable('users', { id: serial('id').primaryKey(), email: text('email').notNull().unique(),});
export const posts = pgTable('posts', { id: serial('id').primaryKey(), userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }), content: text('content').notNull(), createdAt: timestamp('created_at').defaultNow().notNull(),}, (t) => [index('posts_user_created_idx').on(t.userId, t.createdAt)]);
// queryconst feed = await db.select().from(posts) .innerJoin(users, eq(posts.userId, users.id)) .where(eq(posts.userId, 1)) .orderBy(desc(posts.createdAt)).limit(20);Q (mid): How do migrations work with drizzle-kit?
Say this: drizzle-kit generate compares your TS schema with the last snapshot and writes SQL migration files that you review and commit. drizzle-kit migrate applies them. drizzle-kit push syncs the schema directly with no migration files. It’s fine for prototyping, but not for production. drizzle-kit studio opens a DB browser. Config goes in drizzle.config.ts.
Q (mid): How do you run a transaction in Drizzle?
Example:
await db.transaction(async (tx) => { await tx.update(accounts).set({ balance: sql`${accounts.balance} - 100` }).where(eq(accounts.id, 1)); await tx.update(accounts).set({ balance: sql`${accounts.balance} + 100` }).where(eq(accounts.id, 2));}); // throws, so it rolls back automaticallyMongoDB
Section titled “MongoDB”Q (basic): MongoDB basics: documents, collections, _id?
Say this: MongoDB stores BSON documents (binary JSON) in collections. Documents in one collection can have different shapes. Every document has an _id, which defaults to an ObjectId: 12 bytes made of a timestamp, a random value, and a counter, so it’s roughly time-ordered. It supports indexes, replica sets for high availability, and sharding for horizontal scaling. Mongoose adds schemas and validation on top in Node.
Q (mid): Embedding vs referencing?
Say this (30 sec): Embed when the data is read together, belongs to the parent, and is bounded in size. For example, a user’s addresses, or the line items in an order. Reference (store IDs and use $lookup or populate) when the related data is large or unbounded (like the comments on a viral post), shared across documents, or updated on its own. Documents have a 16 MB limit, so unbounded arrays are a classic mistake.
Rule: design around your query patterns, not around normalization.
Q (mid): What is the aggregation pipeline?
Say this: It’s a series of stages that transform documents in order: $match (filter), $group, $project (reshape), $sort, $limit, $lookup (a left join), and $unwind (flatten arrays). Put $match early so it can use indexes and shrink the data.
Example:
db.orders.aggregate([ { $match: { status: 'paid' } }, { $group: { _id: '$userId', total: { $sum: '$amount' }, count: { $sum: 1 } } }, { $sort: { total: -1 } }, { $limit: 5 },]);Supabase
Section titled “Supabase”Q (basic): What is Supabase?
Say this: Supabase is an open-source backend platform built on real Postgres. It gives you a database, Auth (email, OAuth, magic links, issuing JWTs), Storage (files with access policies), Realtime (subscriptions to DB changes, broadcast, presence), Edge Functions, and auto-generated REST APIs through PostgREST. People often call it a “Firebase alternative”, but it’s SQL instead of NoSQL.
Q (mid): What is Row Level Security (RLS) and why does Supabase need it?
Say this (30 sec): RLS is a Postgres feature where policies decide which rows each user can SELECT, INSERT, UPDATE, or DELETE. Supabase lets the frontend query the DB directly with the public anon key, so RLS is the actual security boundary. Without it, anyone with the anon key could read every table. Policies use auth.uid(), which comes from the user’s JWT.
Example:
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;CREATE POLICY "users edit own posts" ON posts FOR UPDATE USING (auth.uid() = user_id);Common wrong answer: Exposing the service_role key on the client. It bypasses RLS and must stay on the server only.
Q (mid): How does Supabase Realtime work?
Say this: Realtime has three features. Postgres Changes listens to Postgres’s logical replication stream (built on the WAL) and pushes INSERT, UPDATE, and DELETE events to subscribed clients over WebSockets, respecting RLS. Broadcast sends low-latency messages between clients. Presence tracks who’s online. The Realtime server is written in Elixir. For high-volume apps, Broadcast scales better than Postgres Changes, because each change has to be checked against RLS for every subscriber.