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. 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. 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. 3. What is a foreign key?

    Correct answer: A column that references a key of another table

    For example, orders.user_id references users.id. The database rejects an order for a non-existent user. ON DELETE CASCADE or ON DELETE SET NULL define what happens when the referenced row is deleted.

  4. 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 side

    The 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. 5. What does the NOT NULL constraint do?

    Correct answer: Forbids storing NULL in the column

    Use UNIQUE to forbid duplicates and DEFAULT to set a default value. Marking required columns NOT NULL catches bugs early.

  6. 6. What is the difference between UNIQUE and PRIMARY KEY?

    Correct answer: One primary key per table, and it can't be NULL

    By default PostgreSQL treats NULLs as distinct, so a UNIQUE column can contain several NULLs. UNIQUE NULLS NOT DISTINCT changes that.

  7. 7. What does a CHECK constraint 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. 8. How do you get an auto-incrementing ID column in modern PostgreSQL?

    Correct answer: id bigint GENERATED ALWAYS AS IDENTITY

    Identity columns are the SQL-standard way. serial still works but is older. AUTO_INCREMENT is MySQL syntax.

  9. 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. 10. Which column type is best for storing money amounts?

    Correct answer: numeric or an integer number of cents

    Floating-point types can't represent values like 0.1 exactly, so sums drift. numeric is exact; storing cents in bigint is also common.

  11. 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. 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 SELECT can't be used in WHERE, but can be used in ORDER BY.

  13. 13. What does SELECT DISTINCT city FROM users return?

    Correct answer: Each city once, without duplicates

    To count unique values use COUNT(DISTINCT city). PostgreSQL also has DISTINCT ON (...) to keep the first row per group.

  14. 14. What does WHERE email = NULL return?

    Correct answer: No rows: use IS NULL instead

    NULL means 'unknown', so NULL = NULL is also unknown. Use IS NULL / IS NOT NULL, or IS DISTINCT FROM for NULL-safe comparison.

  15. 15. What is the difference between COUNT(*) and COUNT(phone)?

    Correct answer: COUNT(phone) skips rows where phone is NULL

    Aggregate functions ignore NULLs, except COUNT(*). AVG(score) also averages only non-NULL values.

  16. 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 PostgreSQL LIKE is case-sensitive; ILIKE is not.

  17. 17. How do you get the 10 newest orders?

    Correct answer: SELECT * FROM orders ORDER BY created_at DESC LIMIT 10;

    Without ORDER BY the order of rows is not guaranteed, so LIMIT alone returns any 10 rows. TOP is SQL Server syntax.

  18. 18. What does WHERE price BETWEEN 10 AND 20 include?

    Correct answer: Prices from 10 to 20, including both 10 and 20

    BETWEEN is inclusive on both ends. With timestamps this can be surprising, so ranges like >= start AND < end are often safer.

  19. 19. What does WHERE status IN ('new', 'paid') mean?

    Correct answer: status equals new or paid

    It's a short form of status = 'new' OR status = 'paid'. IN also accepts a subquery: WHERE user_id IN (SELECT id FROM ...).

  20. 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. 21. What does an INNER JOIN return?

    Correct answer: Only rows that have a match in both tables

    JOIN without a keyword means INNER JOIN. Users without orders, and orders without users, are not in the result.

  22. 22. What does a LEFT JOIN return?

    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 JOIN keeps all rows from the left table. RIGHT JOIN does the same for the right table, and FULL JOIN keeps unmatched rows from both.

  23. 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 NULL

    This is an 'anti-join'. NOT EXISTS expresses it directly and the planner handles both forms well.

  24. 24. What does a CROSS JOIN of 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 ON condition in older comma-style joins (FROM a, b) accidentally produces the same explosion of rows.

  25. 25. A user has 3 orders and 2 addresses. You join users, orders and addresses on user_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. 26. Why are table aliases like u and o used 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. 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 BY collapses rows with the same value into one, and aggregate functions are computed for each group.

  28. 28. What is the difference between WHERE and HAVING?

    Correct answer: WHERE filters rows; HAVING filters groups

    Example: GROUP BY city HAVING COUNT(*) > 100. You can't use an aggregate in WHERE because aggregates don't exist yet at that stage.

  29. 29. Why does SELECT city, name, COUNT(*) FROM users GROUP BY city fail?

    Correct answer: name is neither grouped nor aggregated

    Each output row is a group. Every selected column must be in GROUP BY or wrapped in an aggregate like MAX(name) or string_agg(name, ', ').

  30. 30. Which aggregate functions are standard in SQL?

    Correct answer: COUNT, SUM, AVG, MIN, MAX

    LENGTH, UPPER and TRIM are scalar functions: they work on each value, not on a group. PostgreSQL adds many more aggregates like string_agg and array_agg.

  31. 31. What is the difference between UNION and UNION ALL?

    Correct answer: UNION removes duplicates; UNION ALL keeps them

    Both stack the results of two queries with matching columns. Use UNION ALL when duplicates are impossible or wanted: it's faster.

  32. 32. What happens with UPDATE users SET active = false; without a WHERE?

    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. 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 id returns generated values in the same query.

  34. 34. What is the difference between DELETE FROM logs and TRUNCATE logs?

    Correct answer: TRUNCATE empties the table at once, without scanning rows

    DELETE can have a WHERE and removes rows one by one. DROP TABLE removes the table structure too.

  35. 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. 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. 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. 38. Which table violates first normal form (1NF)?

    Correct answer: users(id, name, phones) with phones = '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. 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. 40. Which type should you usually use for timestamps in PostgreSQL?

    Correct answer: timestamptz (with time zone)

    timestamptz stores an absolute moment (in UTC) and converts to the session time zone on output. Plain timestamp has no zone, so its meaning is ambiguous.

  41. 41. What is the difference between varchar(255) and text in PostgreSQL?

    Correct answer: Same speed; varchar(n) only adds a length limit

    In PostgreSQL both are stored the same way. Use a CHECK constraint or varchar(n) when a limit is a real business rule.

  42. 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. 43. What is an index for?

    Correct answer: To find rows quickly without a full table scan

    Indexes speed up WHERE, JOIN and ORDER BY, but take space and slow down writes, because every insert and update must also update the index.

  44. 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. 45. What is a transaction?

    Correct answer: Statements applied completely or not at all

    Start with BEGIN, finish with COMMIT, or undo everything with ROLLBACK. A transfer between accounts must never apply only one of its two updates.

  46. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 57. What does EXPIRE session:42 3600 do 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 3600 sets the value and TTL in one command.

  58. 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 in FROM. CTEs (WITH) are often a more readable way to write them.

  59. 59. What does COALESCE(nickname, name) return?

    Correct answer: nickname if it's not NULL, otherwise name

    COALESCE returns the first non-NULL argument. It's handy for defaults, e.g. COALESCE(SUM(amount), 0) when there are no rows.

  60. 60. What does CASE do 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 ...) or SUM(CASE WHEN ... THEN 1 ELSE 0 END) to count by category.

  61. 61. What does INSERT ... RETURNING id do in PostgreSQL?

    Correct answer: Inserts the row and returns the generated id in the same query

    It saves a round trip and avoids race conditions of 'insert, then select the max id'. RETURNING also works with UPDATE and DELETE.

  62. 62. What does OFFSET 20 LIMIT 10 do?

    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. 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 public schema. Schemas help separate modules or extensions, and they can have their own permissions.

  64. 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 bytea column.

  65. 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. 66. What is the result of SELECT 10 + NULL?

    Correct answer: NULL

    Almost any operation with NULL gives NULL, because the result is unknown. Use COALESCE(value, 0) when NULL should count as zero.

  67. 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. 68. What does ON DELETE CASCADE on 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 NULL clears the reference.

  69. 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_at on every change needs application code or a trigger.

  70. 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. 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 BY can use the alias n because it runs after SELECT.

  72. 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_id

    This is a self-join; aliases make the two roles clear. LEFT JOIN keeps the top manager, who has no manager.

  73. 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_id and deletes of users (which check for referencing orders) have to scan the whole orders table.

  74. 74. What does EXISTS check?

    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 EXISTS gives the opposite: users without orders.

  75. 75. Where do NULLs appear with ORDER BY last_login ASC in PostgreSQL?

    Correct answer: At the end: NULL sorts as the largest value

    With DESC they come first. You can set it explicitly with NULLS FIRST or NULLS LAST. Other databases, like MySQL, sort NULLs differently.