Databases Junior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What is a relational database?
Correct answer: A database of tables linked through keys
PostgreSQL, MySQL, SQL Server, Oracle and SQLite are relational databases. You query them with SQL, and relationships between tables are expressed with primary and foreign keys.
2. What is a primary key?
Correct answer: A column set that uniquely identifies each row
A table has at most one primary key. The database automatically creates a unique index for it, so lookups by primary key are fast.
3. What is a foreign key?
Correct answer: A column that references a key of another table
For example,
orders.user_idreferencesusers.id. The database rejects an order for a non-existent user.ON DELETE CASCADEorON DELETE SET NULLdefine what happens when the referenced row is deleted.4. How do you model a many-to-many relationship, such as students and courses?
Correct answer: With a junction table, e.g.
enrollments(student_id, course_id), holding a foreign key to each sideThe junction table can also hold data about the relationship itself, like the enrollment date or a grade. A comma-separated list can't be indexed, joined or constrained properly.
5. What does the
NOT NULLconstraint do?Correct answer: Forbids storing NULL in the column
Use
UNIQUEto forbid duplicates andDEFAULTto set a default value. Marking required columnsNOT NULLcatches bugs early.6. What is the difference between
UNIQUEandPRIMARY KEY?Correct answer: One primary key per table, and it can't be NULL
By default PostgreSQL treats NULLs as distinct, so a
UNIQUEcolumn can contain several NULLs.UNIQUE NULLS NOT DISTINCTchanges that.7. What does a
CHECKconstraint do?CREATE TABLE products ( id bigint PRIMARY KEY, price numeric NOT NULL CHECK (price >= 0) );Correct answer: Rejects rows where the condition is false
Constraints in the database protect data from every client: your API, scripts, admin tools. Validation only in application code can be bypassed.
8. How do you get an auto-incrementing ID column in modern PostgreSQL?
Correct answer:
id bigint GENERATED ALWAYS AS IDENTITYIdentity columns are the SQL-standard way.
serialstill works but is older.AUTO_INCREMENTis MySQL syntax.9. What is a common reason to use UUIDs instead of incrementing integers as IDs?
Correct answer: They can be generated anywhere without coordination
UUIDs are 16 bytes vs 8 for
bigint. Random UUIDs (v4) also spread inserts across the index; time-ordered UUIDs (v7) avoid that.10. Which column type is best for storing money amounts?
Correct answer:
numericor an integer number of centsFloating-point types can't represent values like 0.1 exactly, so sums drift.
numericis exact; storing cents inbigintis also common.11. Which query returns the names of users older than 30, sorted by name?
Correct answer:
SELECT name FROM users WHERE age > 30 ORDER BY name;Clauses have a fixed order:
SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT.12. In what logical order does the database evaluate the parts of a query?
Correct answer: FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT
That's why a column alias defined in
SELECTcan't be used inWHERE, but can be used inORDER BY.13. What does
SELECT DISTINCT city FROM usersreturn?Correct answer: Each city once, without duplicates
To count unique values use
COUNT(DISTINCT city). PostgreSQL also hasDISTINCT ON (...)to keep the first row per group.14. What does
WHERE email = NULLreturn?Correct answer: No rows: use
IS NULLinsteadNULL means 'unknown', so
NULL = NULLis also unknown. UseIS NULL/IS NOT NULL, orIS DISTINCT FROMfor NULL-safe comparison.15. What is the difference between
COUNT(*)andCOUNT(phone)?Correct answer:
COUNT(phone)skips rows wherephoneis NULLAggregate functions ignore NULLs, except
COUNT(*).AVG(score)also averages only non-NULL values.16. What does
WHERE name LIKE 'An%'match?Correct answer: Names that start with
An%matches any sequence of characters and_matches exactly one. In PostgreSQLLIKEis case-sensitive;ILIKEis not.17. How do you get the 10 newest orders?
Correct answer:
SELECT * FROM orders ORDER BY created_at DESC LIMIT 10;Without
ORDER BYthe order of rows is not guaranteed, soLIMITalone returns any 10 rows.TOPis SQL Server syntax.18. What does
WHERE price BETWEEN 10 AND 20include?Correct answer: Prices from 10 to 20, including both 10 and 20
BETWEENis inclusive on both ends. With timestamps this can be surprising, so ranges like>= start AND < endare often safer.19. What does
WHERE status IN ('new', 'paid')mean?Correct answer:
statusequalsneworpaidIt's a short form of
status = 'new' OR status = 'paid'.INalso accepts a subquery:WHERE user_id IN (SELECT id FROM ...).20. Why is
SELECT *often avoided in application code?Correct answer: It fetches extra columns and breaks on schema changes
Listing columns makes queries explicit and cheaper to transfer, especially when tables have large text or JSON columns.
21. What does an
INNER JOINreturn?Correct answer: Only rows that have a match in both tables
JOINwithout a keyword meansINNER JOIN. Users without orders, and orders without users, are not in the result.22. What does a
LEFT JOINreturn?SELECT u.name, o.id FROM users u LEFT JOIN orders o ON o.user_id = u.id;Correct answer: Every user, with NULLs where there are no orders
A
LEFT JOINkeeps all rows from the left table.RIGHT JOINdoes the same for the right table, andFULL JOINkeeps unmatched rows from both.23. How do you find users who have no orders?
Correct answer:
LEFT JOIN orders o ON o.user_id = u.id WHERE o.id IS NULLThis is an 'anti-join'.
NOT EXISTSexpresses it directly and the planner handles both forms well.24. What does a
CROSS JOINof a table with 10 rows and a table with 5 rows return?Correct answer: 50 rows: every combination
It's the Cartesian product. Forgetting the
ONcondition in older comma-style joins (FROM a, b) accidentally produces the same explosion of rows.25. A user has 3 orders and 2 addresses. You join
users,ordersandaddressesonuser_id. How many rows do you get for that user?Correct answer: 6
Joining two independent one-to-many relations multiplies rows (3 × 2). Sums and counts over such a join are inflated; aggregate each relation separately.
26. Why are table aliases like
uandoused in joins?Correct answer: To shorten queries and tell apart same-named columns
When two tables have a column with the same name, an unqualified reference is ambiguous and the query fails.
27. What does this query return?
SELECT city, COUNT(*) FROM users GROUP BY city;Correct answer: One row per city with its user count
GROUP BYcollapses rows with the same value into one, and aggregate functions are computed for each group.28. What is the difference between
WHEREandHAVING?Correct answer:
WHEREfilters rows;HAVINGfilters groupsExample:
GROUP BY city HAVING COUNT(*) > 100. You can't use an aggregate inWHEREbecause aggregates don't exist yet at that stage.29. Why does
SELECT city, name, COUNT(*) FROM users GROUP BY cityfail?Correct answer:
nameis neither grouped nor aggregatedEach output row is a group. Every selected column must be in
GROUP BYor wrapped in an aggregate likeMAX(name)orstring_agg(name, ', ').30. Which aggregate functions are standard in SQL?
Correct answer:
COUNT,SUM,AVG,MIN,MAXLENGTH,UPPERandTRIMare scalar functions: they work on each value, not on a group. PostgreSQL adds many more aggregates likestring_aggandarray_agg.31. What is the difference between
UNIONandUNION ALL?Correct answer:
UNIONremoves duplicates;UNION ALLkeeps themBoth stack the results of two queries with matching columns. Use
UNION ALLwhen duplicates are impossible or wanted: it's faster.32. What happens with
UPDATE users SET active = false;without aWHERE?Correct answer: Every row in the table is updated
The same goes for
DELETE FROM users;. Run risky changes inside a transaction, check the affected row count, and only then commit.33. Which statement adds a row?
Correct answer:
INSERT INTO users (name) VALUES ('Ann');List the columns explicitly so the statement keeps working if columns are added. PostgreSQL's
RETURNING idreturns generated values in the same query.34. What is the difference between
DELETE FROM logsandTRUNCATE logs?Correct answer:
TRUNCATEempties the table at once, without scanning rowsDELETEcan have aWHEREand removes rows one by one.DROP TABLEremoves the table structure too.35. What is the difference between DDL and DML?
Correct answer: DDL defines structure; DML works with data
In PostgreSQL even DDL runs inside transactions, so a failed migration can be rolled back as a whole.
36. What is a 'soft delete'?
Correct answer: Marking a row as deleted instead of removing it
It allows restoring data and keeps history, but every query must filter out deleted rows, and unique constraints need care (for example, a partial unique index).
37. What is the main goal of database normalization?
Correct answer: Storing each fact once to avoid inconsistencies
If a customer's address is copied into every order, changing it means updating many rows, and missing one leaves the data inconsistent.
38. Which table violates first normal form (1NF)?
Correct answer:
users(id, name, phones)withphones='111, 222'1NF requires atomic values. A list in one cell can't be indexed, validated or joined properly; move it to a separate table.
39. What is denormalization?
Correct answer: Deliberately duplicating data to make reads faster
It's a trade-off for read-heavy workloads. The duplicate must be updated reliably, for example in the same transaction or by a trigger.
40. Which type should you usually use for timestamps in PostgreSQL?
Correct answer:
timestamptz(with time zone)timestamptzstores an absolute moment (in UTC) and converts to the session time zone on output. Plaintimestamphas no zone, so its meaning is ambiguous.41. What is the difference between
varchar(255)andtextin PostgreSQL?Correct answer: Same speed;
varchar(n)only adds a length limitIn PostgreSQL both are stored the same way. Use a
CHECKconstraint orvarchar(n)when a limit is a real business rule.42. What is a view?
Correct answer: A saved query you can select from like a table
Views hide complex joins and limit which columns users see. A materialized view, in contrast, stores the result and must be refreshed.
43. What is an index for?
Correct answer: To find rows quickly without a full table scan
Indexes speed up
WHERE,JOINandORDER BY, but take space and slow down writes, because every insert and update must also update the index.44. Why not add an index on every column?
Correct answer: Each index slows down writes and takes up space
Add indexes for real query patterns and remove unused ones. PostgreSQL's statistics views show how often each index is used.
45. What is a transaction?
Correct answer: Statements applied completely or not at all
Start with
BEGIN, finish withCOMMIT, or undo everything withROLLBACK. A transfer between accounts must never apply only one of its two updates.46. What does ACID stand for?
Correct answer: Atomicity, Consistency, Isolation, Durability
Atomicity: all or nothing. Consistency: constraints hold. Isolation: concurrent transactions don't interfere. Durability: committed data survives crashes.
47. What does 'durability' guarantee?
Correct answer: Committed changes survive a crash or power loss
PostgreSQL writes changes to the write-ahead log (WAL) and flushes it to disk before confirming the commit. After a crash it replays the log.
48. What is SQL injection?
const sql = "SELECT * FROM users WHERE name = '" + name + "'";Correct answer: User input that changes the meaning of a query
Never build SQL from strings. Use parameters (
WHERE name = $1), which drivers send separately from the query text.49. Why should an application connect to the database with a user that has limited privileges?
Correct answer: A breach then can't drop tables or read unneeded data
Grant only the needed rights (
GRANT SELECT, INSERT ON ...). Run migrations with a separate, more powerful role.50. What is a database migration?
Correct answer: A versioned script that changes the schema
Migrations live in git next to the code. Tools like Prisma Migrate, Flyway or Knex track which ones have been applied.
51. What is an ORM?
Correct answer: A library that maps tables to objects in code
Prisma, TypeORM, Sequelize and Drizzle are popular in Node.js. They speed up common work, but you still need to understand the SQL they generate.
52. Why should you regularly test restoring from backups, not just make them?
Correct answer: Only a real restore proves that a backup works
Many teams discover broken or incomplete backups only during an incident. Practise restores and measure the time against your recovery goals.
53. What is the main idea of a document database like MongoDB?
Correct answer: Flexible JSON-like documents, often with nested data
An order with its items can be one document, read in a single operation. The trade-off: duplicated data and weaker support for cross-document queries.
54. What is Redis most often used for in web applications?
Correct answer: An in-memory store for caching, sessions and queues
Redis keeps data in memory, so reads and writes are very fast. It supports strings, hashes, lists, sets, sorted sets and streams.
55. When is a relational database usually the better default?
Correct answer: For structured, related data needing transactions
Most applications fit a relational model well. PostgreSQL also handles JSON documents, full-text search and more, so it covers many 'NoSQL' needs too.
56. What does 'schemaless' mean for a document database?
Correct answer: The app handles the document shapes
The schema still exists, just in your code ('schema on read'). MongoDB can also validate documents with JSON Schema rules.
57. What does
EXPIRE session:42 3600do in Redis?Correct answer: Deletes the key automatically after 3600 seconds
TTLs make Redis a natural fit for caches and sessions: old data cleans itself up.
SET key value EX 3600sets the value and TTL in one command.58. What is a subquery?
SELECT name FROM products WHERE price > (SELECT AVG(price) FROM products);Correct answer: A query inside another query
Subqueries can return one value (as here), a list for
IN, or a whole table inFROM. CTEs (WITH) are often a more readable way to write them.59. What does
COALESCE(nickname, name)return?Correct answer:
nicknameif it's not NULL, otherwisenameCOALESCEreturns the first non-NULL argument. It's handy for defaults, e.g.COALESCE(SUM(amount), 0)when there are no rows.60. What does
CASEdo in a query?SELECT name, CASE WHEN age < 18 THEN 'minor' ELSE 'adult' END AS group_name FROM users;Correct answer: Returns a value by conditions, like if/else
It's often used inside aggregates too:
COUNT(*) FILTER (WHERE ...)orSUM(CASE WHEN ... THEN 1 ELSE 0 END)to count by category.61. What does
INSERT ... RETURNING iddo in PostgreSQL?Correct answer: Inserts the row and returns the generated
idin the same queryIt saves a round trip and avoids race conditions of 'insert, then select the max id'.
RETURNINGalso works withUPDATEandDELETE.62. What does
OFFSET 20 LIMIT 10do?Correct answer: Skips 20 rows and returns the next 10
It's the simplest pagination. For deep pages it gets slow, because the database still reads and discards the skipped rows.
63. What is a database 'schema' in the sense of PostgreSQL's
CREATE SCHEMA?Correct answer: A namespace grouping tables and views
By default objects live in the
publicschema. Schemas help separate modules or extensions, and they can have their own permissions.64. Why should you avoid storing large files (images, videos) directly in database rows?
Correct answer: They bloat the database, backups and replication
Store the file in object storage and keep metadata (key, size, owner) in the database. Small binary data is fine in a
byteacolumn.65. What does SQLite fit best?
Correct answer: Embedded, local storage in a single file
SQLite is a library, not a server, and the whole database is one file. It allows one writer at a time, which is fine for many apps but not for heavy concurrent writes.
66. What is the result of
SELECT 10 + NULL?Correct answer:
NULLAlmost any operation with NULL gives NULL, because the result is unknown. Use
COALESCE(value, 0)when NULL should count as zero.67. What is a composite primary key?
CREATE TABLE enrollments ( student_id bigint REFERENCES students (id), course_id bigint REFERENCES courses (id), PRIMARY KEY (student_id, course_id) );Correct answer: A primary key made of several columns
Composite keys are typical for junction tables. Each column alone may repeat; only the combination must be unique.
68. What does
ON DELETE CASCADEon a foreign key do?Correct answer: Deleting a row also deletes the rows referencing it
For example, deleting a user deletes their sessions. The default (
NO ACTION) blocks the delete while references exist;SET NULLclears the reference.69. What does
created_at timestamptz NOT NULL DEFAULT now()do?Correct answer: Fills in the current time if no value is provided
Defaults apply only on insert. Tracking
updated_aton every change needs application code or a trigger.70. How do you add a column to an existing table?
Correct answer:
ALTER TABLE users ADD COLUMN phone text;In PostgreSQL adding a nullable column (or one with a constant default) is instant even on big tables. Changes like this belong in a migration.
71. How do you get the 5 cities with the most users?
Correct answer:
SELECT city, COUNT(*) AS n FROM users GROUP BY city ORDER BY n DESC LIMIT 5;Group, count, sort by the count and limit.
ORDER BYcan use the aliasnbecause it runs afterSELECT.72. Table
employees(id, name, manager_id)stores each employee's manager. How do you list employees with their manager's name?Correct answer: Join the table with itself on
manager_idThis is a self-join; aliases make the two roles clear.
LEFT JOINkeeps the top manager, who has no manager.73. Does PostgreSQL automatically create an index on a foreign key column like
orders.user_id?Correct answer: No, you usually add that index yourself
Without an index, joins by
user_idand deletes of users (which check for referencing orders) have to scan the wholeorderstable.74. What does
EXISTScheck?SELECT name FROM users u WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);Correct answer: Whether the subquery returns at least one row
The database can stop at the first matching row.
NOT EXISTSgives the opposite: users without orders.75. Where do NULLs appear with
ORDER BY last_login ASCin PostgreSQL?Correct answer: At the end: NULL sorts as the largest value
With
DESCthey come first. You can set it explicitly withNULLS FIRSTorNULLS LAST. Other databases, like MySQL, sort NULLs differently.