Pick a topic — languages & databases — 100+ questions and answers in the center column.
SQL
Relational query language — joins, indexes, transactions, modeling.
102 questions
Question 1
Structured Query Language for defining, querying, and manipulating relational data. ANSI/ISO standards exist; vendors add dialect extensions (MySQL, PostgreSQL, SQL Server).
Example code
SELECT 'hello' AS greetingQuestion 2
DDL shapes schema (CREATE, ALTER, DROP). DML changes or reads rows (SELECT, INSERT, UPDATE, DELETE). DCL controls permissions (GRANT, REVOKE).
Example code
CREATE TABLE t (id INT PRIMARY KEY);Question 3
Uniquely identifies a row; enforces NOT NULL + uniqueness. Surrogate keys (auto-increment/UUID) vs natural keys (email) is a modeling choice.
Example code
ALTER TABLE t ADD COLUMN x INTQuestion 4
Column(s) referencing another table’s primary/unique key—enforces referential integrity; ON DELETE/UPDATE actions define cascade behavior.
Example code
DROP TABLE IF EXISTS tQuestion 5
Allows one NULL in many SQL DBs per column; ensures no duplicate non-null values—multiple NULLs possible depending on dialect.
Example code
REFERENCES parent(id) ON DELETE CASCADEQuestion 6
Unknown—not equal to anything including NULL; use IS NULL / IS NOT NULL. Aggregates often ignore NULLs; three-valued logic in WHERE.
Example code
UNIQUE (email)Question 7
Returns rows where join predicate matches in both tables—most common join; omitting join condition can accidentally cross join.
Example code
WHERE col IS NULLQuestion 8
Keeps all left rows; right side columns NULL when no match—use to find missing relationships.
Example code
SELECT * FROM a INNER JOIN b ON a.id = b.aidQuestion 9
RIGHT mirrors LEFT with table sides swapped. FULL keeps both sides with NULL fill-outs—supported in PostgreSQL; MySQL lacks native FULL (workarounds exist).
Example code
SELECT * FROM a LEFT JOIN b ON a.id = b.aidQuestion 10
Cartesian product—every left row paired with every right row; useful with filters or small dimension tables.
Example code
SELECT * FROM a FULL OUTER JOIN b ON a.id = b.aidQuestion 11
WHERE filters rows before grouping. HAVING filters groups after GROUP BY—cannot reference non-aggregated columns not in GROUP BY (standard SQL).
Example code
SELECT * FROM a CROSS JOIN bQuestion 12
Selected non-aggregated columns must appear in GROUP BY (or be functionally dependent in some engines). MySQL historically was permissive.
Example code
SELECT d FROM t GROUP BY d HAVING COUNT(*) > 1Question 13
COUNT, SUM, AVG, MIN, MAX—COUNT(*) counts rows; COUNT(col) ignores NULLs in col.
Example code
SELECT d, COUNT(*) FROM t GROUP BY dQuestion 14
Query nested in another—correlated if it references outer columns (often slower, row-by-row). Uncorrelated can be optimized as joins.
Example code
SELECT AVG(price) FROM ordersQuestion 15
EXISTS stops at first match—often efficient for correlated checks. IN with subquery fine for small sets; beware NULLs inside IN lists.
Example code
SELECT * FROM t WHERE id IN (SELECT aid FROM x)Question 16
UNION deduplicates (sort/hash cost). UNION ALL concatenates—prefer when duplicates impossible or acceptable.
Example code
SELECT * FROM t WHERE EXISTS (SELECT 1 FROM x WHERE x.tid = t.id)Question 17
Single row, multi-row VALUES, INSERT…SELECT—mind triggers and identity columns returning generated keys.
Example code
SELECT a FROM u UNION SELECT a FROM vQuestion 18
Always scope with WHERE; forgetting it updates entire table. Joined updates vary by dialect.
Example code
SELECT a FROM u UNION ALL SELECT a FROM vQuestion 19
DELETE is row-by-row, can fire triggers, logged heavily. TRUNCATE fast reset (table-level locks, reset identities)—permissions and FK rules differ by engine.
Example code
INSERT INTO t (a,b) VALUES (1,'x')Question 20
Atomicity, Consistency, Isolation, Durability—transaction guarantees; engines implement with logging, locking, MVCC.
Example code
UPDATE t SET a = 2 WHERE id = 1Question 21
Read uncommitted / committed / repeatable read / serializable—balance dirty reads vs phantom reads vs performance.
Example code
DELETE FROM t WHERE id = 1Question 22
Two transactions wait on each other’s locks—DBMS picks a victim to roll back; apps should retry idempotently.
Example code
TRUNCATE TABLE tQuestion 23
Speed lookups and joins; cost is slower writes and storage—wrong or redundant indexes hurt.
Example code
BEGIN;
UPDATE t SET x=1;
COMMITQuestion 24
Default balanced tree for range and equality—leaf pages store row pointers or clustered data.
Example code
SET TRANSACTION ISOLATION LEVEL SERIALIZABLEQuestion 25
Index contains all columns needed for query—avoids table lookups (index-only scan).
Example code
-- deadlock: pick victim, app retriesQuestion 26
Leftmost prefix rule—put selective, equality-filtered columns first; order matters for range scans.
Example code
CREATE INDEX idx_t_a ON t(a)Question 27
1NF: atomic values. 2NF: no partial dependency on composite keys. 3NF: no transitive dependency on non-key attributes.
Example code
CREATE INDEX idx_t_ab ON t(a,b)Question 28
Read-heavy reporting, caching aggregates, controlled duplication—trade space and update complexity for speed.
Example code
SELECT a,b FROM t WHERE a = 1 -- covering if index matchesQuestion 29
Stored named query—simplifies access and can enforce column-level abstraction; not always materialized.
Example code
CREATE INDEX idx_t_abc ON t(a,b,c)Question 30
Persisted query results—refresh on schedule or trigger; great for analytics; naming differs (PostgreSQL matview, SQL Server indexed view).
Example code
CREATE VIEW v AS SELECT id,a FROM tQuestion 31
WITH clause names a subquery—improves readability; recursive CTEs traverse hierarchies (standard SQL).
Example code
WITH cte AS (SELECT * FROM t) SELECT * FROM cteQuestion 32
OVER (PARTITION BY … ORDER BY …)—compute running totals, ranks without collapsing rows like GROUP BY.
Example code
SELECT id, SUM(x) OVER (PARTITION BY g ORDER BY id) AS r FROM tQuestion 33
ROW_NUMBER unique sequential. RANK ties skip numbers. DENSE_RANK ties without gaps.
Example code
SELECT ROW_NUMBER() OVER (ORDER BY x) FROM tQuestion 34
COALESCE returns first non-NULL. NULLIF(a,b) returns NULL when equal—handy for divide-by-zero guards.
Example code
SELECT COALESCE(a,0), NULLIF(b,0) FROM tQuestion 35
Conditional scalar logic in SQL—searched CASE vs simple CASE; use in SELECT, ORDER BY, aggregates.
Example code
SELECT CASE WHEN x>0 THEN 1 ELSE 0 END FROM tQuestion 36
Parameterized queries separate SQL structure from data—primary defense against injection alongside validation.
Example code
PREPARE s AS SELECT * FROM t WHERE id = $1Question 37
Bind parameters, least-privilege DB users, ORM/query builders with binding, never concatenate untrusted input into SQL text.
Example code
-- use bound params, never concat user inputQuestion 38
Logical container for tables, views, indexes, and security objects—meaning of 'schema' vs 'database' differs (PostgreSQL schema inside a database; MySQL often treats them similarly).
Example code
CREATE SCHEMA IF NOT EXISTS appQuestion 39
Row-level boolean predicate enforced on insert/update—portable integrity beyond types.
Example code
-- CHECK constraint
SELECT 1Question 40
Column defaults reduce application branching; can use functions (e.g., now()) per dialect.
Example code
-- DEFAULT values
SELECT 1Question 41
Monotonic number generators—SERIAL in PostgreSQL, AUTO_INCREMENT in MySQL; gaps after rollback are normal.
Example code
-- Sequences
SELECT 1Question 42
Random/globally unique keys—avoid hot index pages with UUIDv7 or hash prefixes in some designs.
Example code
-- UUID keys
SELECT 1Question 43
Index with WHERE predicate—smaller, targeted (PostgreSQL); other engines use filtered equivalents or workarounds.
Example code
-- Partial index
SELECT 1Question 44
Index on function or expression—speeds queries matching that expression exactly.
Example code
-- Expression index
SELECT 1Question 45
O(1) equality in some engines—no range scans; use case-specific.
Example code
-- Hash index
SELECT 1Question 46
Table row order follows index—one per table typically (SQL Server clustered, InnoDB PK).
Example code
-- Clustered index
SELECT 1Question 47
Separate structure pointing to rows—most secondary indexes.
Example code
-- Nonclustered index
SELECT 1Question 48
Low cardinality columns alone may not help—combine with selective predicates.
Example code
-- Index selectivity
SELECT 1Question 49
SQL Server INCLUDE columns add payload without sort key overhead in nonclustered indexes.
Example code
-- Covering include columns
SELECT 1Question 50
Cost-based optimizer chooses joins and indexes—statistics quality matters; ANALYZE/UPDATE STATISTICS.
Example code
-- Query planner
SELECT 1Question 51
Column distribution stats help estimate cardinality—stale stats cause bad plans.
Example code
-- Histograms and stats
SELECT 1Question 52
Row-by-row probe—good for small inputs with index.
Example code
-- Nested loop join
SELECT 1Question 53
Build hash table on one side—good for equi-joins of larger sets without helpful indexes.
Example code
-- Hash join
SELECT 1Question 54
Both sides sorted—efficient for large pre-sorted or index-ordered inputs.
Example code
-- Merge join
SELECT 1Question 55
NOT EXISTS often clearer and optimizable vs NOT IN with NULL pitfalls.
Example code
-- Anti-join pattern
SELECT 1Question 56
EXISTS / IN subqueries that only test presence—planner may rewrite to semi-join operators.
Example code
-- Semi-join
SELECT 1Question 57
Rotate rows to columns and back—syntax varies; CASE aggregates are portable fallback.
Example code
-- PIVOT / UNPIVOT
SELECT 1Question 58
Upsert pattern in one statement—powerful but dialect-specific behavior and concurrency caveats.
Example code
-- MERGE statement
SELECT 1Question 59
Return inserted/updated/deleted rows in same statement—PostgreSQL, modern MySQL.
Example code
-- RETURNING clause
SELECT 1Question 60
ON CONFLICT DO UPDATE (PostgreSQL), ON DUPLICATE KEY UPDATE (MySQL)—learn conflict targets.
Example code
-- UPSERT dialects
SELECT 1Question 61
System-versioned history—SQL Server temporal; other DBs use triggers or audit tables.
Example code
-- Temporal tables
SELECT 1Question 62
deleted_at flag instead of physical DELETE—complicates unique constraints; partial unique indexes help.
Example code
-- Soft delete
SELECT 1Question 63
Version column checked on UPDATE—detect concurrent writes without long DB locks.
Example code
-- Optimistic locking
SELECT 1Question 64
SELECT … FOR UPDATE—holds row locks until transaction end; risk deadlocks.
Example code
-- Pessimistic locking
SELECT 1Question 65
Async followers for scale-out reads—replication lag means stale reads; routing logic required.
Example code
-- Read replicas
SELECT 1Question 66
Horizontal partition by key—application routing, cross-shard queries expensive.
Example code
-- Sharding
SELECT 1Question 67
Table split by range/list/hash—pruning improves scans; manage partition maintenance.
Example code
-- Partitioning
SELECT 1Question 68
Analytics engines store by column—great compression and aggregates; OLTP row stores differ.
Example code
-- Columnar storage
SELECT 1Question 69
Fact surrounded by dimensions—classic warehouse modeling for BI.
Example code
-- Star schema
SELECT 1Question 70
Normalized dimensions—saves space, more joins than star.
Example code
-- Snowflake schema
SELECT 1Question 71
Type 1 overwrite, Type 2 history rows, Type 3 limited attributes—warehouse modeling pattern.
Example code
-- Slowly changing dimensions
SELECT 1Question 72
Transform before load vs load raw then transform in warehouse—modern warehouses favor ELT with SQL transforms.
Example code
-- ETL vs ELT
SELECT 1Question 73
Transactional many small writes vs analytical large scans—different tuning and engines.
Example code
-- OLTP vs OLAP
SELECT 1Question 74
Read cost estimates and actuals—find sequential scans, bad nested loops, missing indexes.
Example code
-- EXPLAIN plans
SELECT 1Question 75
OPTIMIZER hints force plans—last resort when stats can’t be fixed; hurts portability.
Example code
-- Hinting
SELECT 1Question 76
Reuse DB connections—set pool size vs DB max_connections and app instances.
Example code
-- Connection pooling
SELECT 1Question 77
App role without DDL, minimal table grants—limits blast radius of bugs.
Example code
-- Least privilege
SELECT 1Question 78
Policy filters rows per user—PostgreSQL RLS; SQL Server RLS; app must still parameterize.
Example code
-- Row-level security
SELECT 1Question 79
TDE / volume encryption—protects disks; TLS protects data in flight.
Example code
-- Encryption at rest
SELECT 1Question 80
Full, incremental, differential, PITR with WAL/binlog—test restores, not just backups.
Example code
-- Backup types
SELECT 1Question 81
Replay logs to a timestamp—requires continuous archiving and base backup.
Example code
-- Point-in-time recovery
SELECT 1Question 82
Distributed transaction prepare/commit across databases—complex, avoid when possible.
Example code
-- Two-phase commit
SELECT 1Question 83
Distributed systems pick consistency vs availability under partition—SQL clusters still face network splits.
Example code
-- CAP in practice
SELECT 1Question 84
JSON/JSONB columns with query operators—convenient but easy to skip indexing; validate shape in app.
Example code
-- JSON in SQL
SELECT 1Question 85
CONTAINS, to_tsvector, MATCH—better than LIKE '%x%' for large text; specialized engines exist.
Example code
-- Full-text search
SELECT 1Question 86
Geometry/geography with indexes—PostGIS, MySQL spatial; know SRID and precision.
Example code
-- Spatial types
SELECT 1Question 87
ROWS BETWEEN, RANGE BETWEEN—control sliding aggregates; off-by-one bugs common.
Example code
-- Window framing
SELECT 1Question 88
Correlate subquery per left row (PostgreSQL, SQL Server)—powerful for top-N per group.
Example code
-- LATERAL join
SELECT 1Question 89
Hierarchies and graphs in SQL—mind cycle detection and depth limits.
Example code
-- Recursive CTE depth
SELECT 1Question 90
Window functions standardized later—verify dialect support for modern features.
Example code
-- SQL:1999 vs :2003
SELECT 1Question 91
Portable metadata views—tables, columns, constraints discovery across engines.
Example code
-- Information schema
SELECT 1Question 92
Test on target DBs; avoid silent type coercion differences and LIMIT/OFFSET quirks on old versions.
Example code
-- Dialect portability
SELECT 1Question 93
Computed persisted or virtual columns—keep logic in DB vs app; indexing rules vary.
Example code
-- GENERATED columns
SELECT 1Question 94
BEFORE/AFTER row or statement—hidden side effects complicate debugging; prefer explicit app logic when possible.
Example code
-- Triggers
SELECT 1Question 95
Server-side routines—reduce round trips but tie logic to one engine’s language and deployment.
Example code
-- Stored procedures
SELECT 1Question 96
Server-side iterators hold locks and memory—avoid large cursor loops in OLTP; batch or set-based SQL instead.
Example code
-- Cursor pitfalls
SELECT 1Question 97
COPY / LOAD DATA / BULK INSERT—disable indexes or use minimal logging modes per engine for speed with care.
Example code
-- Bulk load
SELECT 1Question 98
Execute and measure actual timings—reveals misestimates vs plain EXPLAIN plans.
Example code
-- EXPLAIN ANALYZE
SELECT 1Question 99
Scheduled ANALYZE/UPDATE STATISTICS—keeps planner accurate after bulk changes.
Example code
-- Table statistics job
SELECT 1Question 100
Surrogate (opaque id) stable under renames; natural keys readable but brittle when business rules change.
Example code
-- Surrogate vs natural keys
SELECT 1Question 101
Composite foreign keys match composite parent keys—order and null rules must align.
Example code
-- Multi-column FK
SELECT 1Question 102
Some engines disallow subqueries in CHECK—use triggers or constraints in newer versions.
Example code
-- CHECK with subqueries
SELECT 1