QA Interview Hub · Knowledge base · Quizzes · Українська

All topics

SQL interview questions and answers for QA

59 SQL questions that come up in QA interviews, with short answers. Open the topic in the knowledge base for a deeper explanation.

What is a relational database and what is SQL?

A relational database stores data in tables linked to each other, and SQL is a declarative language for working with them: I describe what data I want, and the database decides how to find it. The basic syntax is the same across DBMSs such as PostgreSQL, MySQL and SQL Server.

Read the topic

What are a primary key and a foreign key?

A primary key uniquely identifies a row: it is unique and never empty. A foreign key references the primary key of another table and guarantees integrity: for example, you can't create an account for a user who doesn't exist. For me as QA it is also a hint of what to test: whether the system handles such errors correctly.

Read the topic

What is normalization and why is it needed?

Normalization splits data across tables so each fact is stored once. This removes anomalies: an email changed in one row stays old in the others. 1NF: atomic values, no lists in one cell. 2NF: every non-key column depends on the whole key. 3NF: non-key columns do not depend on each other. Example: I move the customer name from orders to customers and keep only customer_id in orders. Deliberate denormalization is fine for reports, but it is a trade-off.

Read the topic

What kinds of relationships exist between tables and how are they stored?

One-to-many: a foreign key in the "child" table (orders.user_id). One-to-one: a foreign key with UNIQUE (or a shared primary key). Many-to-many: a join table with foreign keys to both sides and usually a composite primary key (enrollments(student_id, course_id)). A comma-separated list of ids in one column is not a relationship: it breaks 1NF and gives no integrity check.

Read the topic

How does SQL three-valued logic (TRUE, FALSE, UNKNOWN) work?

A comparison with NULL gives UNKNOWN, and WHERE keeps only TRUE. NOT UNKNOWN is also UNKNOWN. AND: FALSE wins (NULL AND FALSE = FALSE), otherwise UNKNOWN. OR: TRUE wins (NULL OR TRUE = TRUE). So x <> 1 does not return NULL rows and x = NULL returns nothing: write IS NULL or IS NOT DISTINCT FROM.

Read the topic

Which type to use for money, dates and times in PostgreSQL?

Money: numeric(p, s) or integers in the smallest unit (cents), not float. Moment of an event: timestamptz (stores the instant, shows it in the session zone). timestamp without a zone is a "wall clock": the same value means different instants in different zones. Date without time: date. Integer division: 7 / 2 = 3, a fraction needs numeric (7 / 2.0).

Read the topic

DDL, DML, DQL, DCL, TCL: which command belongs to which group?

DDL (structure): CREATE, ALTER, DROP. DML (rows): INSERT, UPDATE, DELETE. DQL (reading): SELECT. DCL (privileges): GRANT, REVOKE. TCL (transactions): BEGIN, COMMIT, ROLLBACK. The borders are conventional: SELECT is sometimes counted as DML, and TRUNCATE as DDL or DML. In an interview I name the group and what it changes.

Read the topic

In what order is a query actually executed?

A query isn't executed in the order it is written: first FROM and JOIN, then WHERE, GROUP BY, HAVING, and only then SELECT, ORDER BY and LIMIT. That is why an alias from SELECT can't be used in WHERE, but can in ORDER BY, and why aggregates are filtered with HAVING and not with WHERE.

Read the topic

How is a SELECT query structured?

A query starts with SELECT and a list of columns, then FROM with a table, and then, as needed, WHERE for a filter, GROUP BY and HAVING for grouping, ORDER BY for sorting and LIMIT for restriction. For quick exploration I write SELECT star, but in automated tests I list the columns explicitly, so the test doesn't depend on changes to the table's structure.

Read the topic

How to compare with NULL in WHERE?

Only with IS NULL and IS NOT NULL: x = NULL and x <> NULL are always UNKNOWN, so rows are dropped. To compare two values that may be NULL, write a IS DISTINCT FROM b (NULL counts as a value) or a IS NOT DISTINCT FROM b. COALESCE(x, 0) substitutes a default but can hide the difference between "missing" and "zero".

Read the topic

Which patterns does LIKE support and how does ILIKE differ?

% is any number of characters (zero included), _ exactly one character. LIKE is case-sensitive, ILIKE (PostgreSQL) is not. To find a literal % or _, escape them: LIKE '50\%'. A pattern starting with % ('%abc') usually cannot use a regular index. NULL LIKE ... gives UNKNOWN.

Read the topic

Why are LIMIT and OFFSET unreliable without ORDER BY?

Without ORDER BY the database promises no row order: the same query may return different rows after an update or with another plan. So "the first 10" and OFFSET pages become arbitrary, and rows can repeat or go missing. The order must be deterministic: ORDER BY ... plus a unique column to break ties (ORDER BY created_at DESC, id DESC). With a large OFFSET the database still walks the skipped rows, so deep pagination uses keyset.

Read the topic

How do IN, BETWEEN and DISTINCT handle bounds and NULL?

BETWEEN a AND b includes both bounds; for a timestamp and "until the end of the day" use >= start and < next day. x IN (1, NULL) finds 1, but NULL never matches (NOT IN with a NULL in the list returns nothing). DISTINCT and GROUP BY treat all NULLs as equal and keep one. A NULL row passes a comparison only via IS NULL or IS NOT DISTINCT FROM.

Read the topic

How does WHERE differ from HAVING?

WHERE selects individual rows before grouping, so aggregate functions cannot be used in it. HAVING filters groups after GROUP BY and works with aggregates. The execution order is: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY. Example: SELECT user_id, COUNT(*) FROM orders WHERE status = 'paid' GROUP BY user_id HAVING COUNT(*) > 3; — first I take only the paid orders, then keep users with more than three. A filter that does not depend on an aggregate goes into WHERE: it is faster, because fewer rows have to be grouped and aggregated.

Read the topic

How do COUNT(*), COUNT(col) and COUNT(DISTINCT col) differ?

COUNT star counts all rows, COUNT of a column only those where the value is not NULL, and COUNT DISTINCT the number of unique non-empty values. The difference between the first two immediately shows how many records have an empty field, and I often use this to check data completeness after a migration.

Read the topic

How does GROUP BY work?

GROUP BY splits rows into groups with equal values and computes an aggregate for each group. The rule is simple: every column in SELECT must be either in GROUP BY or inside an aggregate function. I often group by status to see the distribution of data and notice anomalies, for example an unexpectedly large number of failed.

Read the topic

What must be in GROUP BY when SELECT has non-aggregate columns?

Every SELECT column must be in GROUP BY or inside an aggregate (COUNT, SUM, MAX…). Otherwise for a group of several rows it is unclear which value to show, and PostgreSQL returns an error (MySQL with ONLY_FULL_GROUP_BY too). Exception: columns functionally dependent on the group key (the primary key in GROUP BY). You can group by an expression too: GROUP BY date_trunc('day', created_at).

Read the topic

What do aggregates return on an empty set and on NULL?

An aggregate without GROUP BY always yields one row. On an empty set COUNT(*) is 0, while SUM, AVG, MIN, MAX are NULL. Aggregates skip NULL values (except COUNT(*)): the average of 5, NULL, 3 is 4, not 2.67. So a sum is wrapped in COALESCE(SUM(x), 0), and COUNT(col) and COUNT(*) differ when col has NULL.

Read the topic

How to count several conditions in one pass (FILTER, CASE)?

Conditional aggregation: COUNT(*) FILTER (WHERE status = 'failed') AS failed (PostgreSQL) or SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END). Without ELSE, CASE gives NULL, and when nothing matches SUM returns NULL, not 0. One GROUP BY then yields several counters (completed, failed, total) without separate queries.

Read the topic

Why did the row count grow after a JOIN and the sum doubled?

In a one-to-many join the row on the "one" side is duplicated for each pair, and aggregates over its columns get doubled. So when I count sums across several levels, user, accounts, transactions, I first aggregate the child table in a subquery and then join. And as QA I use this trap as a hint: if a report shows doubled sums, the first thing I check is the JOIN.

Read the topic

What are RIGHT, FULL OUTER and CROSS JOIN?

RIGHT JOIN is the mirror of LEFT, and it is usually replaced with LEFT by swapping the tables. FULL OUTER JOIN returns everything from both sides, and it is ideal for reconciling two data sets, for example our transactions with a provider's statement. CROSS JOIN gives all combinations of rows, so you have to be careful with it.

Read the topic

How does a condition in ON differ from one in WHERE with LEFT JOIN?

ON decides which rows of the right table join a left one; without a partner the left row still stays with NULLs on the right. WHERE filters the already joined result: a condition on the right table (o.status = 'PAID') drops NULL rows and effectively turns LEFT JOIN into INNER. To keep all left rows, put the right-table condition in ON. For INNER JOIN there is no difference.

Read the topic

Do NULLs match in a JOIN and what is a self join?

No: ON a.k = b.k for NULL = NULL is UNKNOWN, so rows with a NULL key do not join (INNER) or stay without a partner (LEFT). For NULLs to match, write IS NOT DISTINCT FROM. A self join joins a table to itself through different aliases: employees e LEFT JOIN employees m ON m.id = e.manager_id. LEFT is needed so that those with no manager (NULL) are not lost.

Read the topic

How does IN differ from EXISTS?

IN compares a value to a list from a subquery, while EXISTS only checks whether there is at least one row and can stop at the first. In the positive form modern databases often execute them the same way, so the main difference is in negation: NOT EXISTS is safe, and NOT IN breaks if the subquery contains NULL.

Read the topic

How does a correlated subquery differ from an uncorrelated one?

An uncorrelated subquery does not reference the outer query: it can run alone and gives one value or a set (WHERE amount > (SELECT AVG(amount) FROM orders)). A correlated one uses columns of the outer row (WHERE user_id = o.user_id) and logically runs per row: "an order above the average of the same user". The planner may rewrite it as a JOIN, but read it as "for each".

Read the topic

What are the rules of UNION, INTERSECT and EXCEPT?

The same number of columns and compatible types by position; names come from the first query. UNION, INTERSECT, EXCEPT remove duplicates (NULLs count as equal), the ALL variants keep them. UNION ALL is faster because it does not deduplicate. EXCEPT is asymmetric: A EXCEPT B is not B EXCEPT A. ORDER BY goes once, at the end of the whole query.

Read the topic

What does a scalar subquery return with 0 or more than one row?

A scalar subquery (after =, <, in SELECT) must give at most one row and one column. Zero rows give NULL (and a comparison with NULL is UNKNOWN, so the row is dropped). More than one row is an error "more than one row returned by a subquery used as an expression". For a set of values use IN, = ANY or EXISTS, for one value add an aggregate (MAX) or LIMIT 1 with ORDER BY.

Read the topic

When to use a CTE and is it always materialized?

A CTE (WITH name AS (...)) gives a query part a name and readability: complex steps go in order, and one CTE can be used several times; WITH RECURSIVE walks hierarchies. In PostgreSQL 12+ a non-recursive CTE without side effects that is referenced once is inlined into the query like a subquery; with several references it is computed once (materialized). The hints MATERIALIZED and NOT MATERIALIZED control this. A CTE is not a temporary table: it lives only within the query.

Read the topic

How do you find rows with no match in another table: NOT IN, NOT EXISTS or LEFT JOIN ... IS NULL?

All three ways look for an "anti-match" but behave differently with NULL. NOT EXISTS (SELECT 1 FROM b WHERE b.a_id = a.id) is safe: a NULL in b does not spoil the result. LEFT JOIN b ON b.a_id = a.id WHERE b.a_id IS NULL is also correct and readable; the condition on the right table stays in ON, and only IS NULL is left in WHERE. NOT IN (SELECT a_id FROM b) is risky: if the subquery returns even one NULL, x NOT IN (…, NULL) gives FALSE or UNKNOWN but never TRUE, and the query returns zero rows. For NOT IN you either exclude NULLs in the subquery (WHERE a_id IS NOT NULL) or use NOT EXISTS. A test case for QA: add a row with NULL to the lookup and check that the result does not disappear.

Read the topic

What is a recursive CTE and what parts does it consist of?

A recursive CTE (WITH RECURSIVE) walks a hierarchy or a chain: categories, a manager's subordinates, a graph of links. It has two parts joined with UNION ALL: an anchor query (the starting rows, for example the root manager) and a recursive step that refers to the CTE itself and adds the next level, for example the subordinates of the rows just found. It repeats until the step returns an empty result. Without a stop condition a loop in the data (A reports to B and B reports to A) makes an endless query, so a depth counter and a WHERE depth < N limit are added, or the path is checked. QA uses it to find a whole substructure or to detect circular references in test data.

Read the topic

How do DELETE, TRUNCATE and DROP differ?

DELETE removes rows, optionally by a WHERE condition, triggers fire, and the operation can be rolled back in a transaction. TRUNCATE quickly removes all rows of a table without WHERE and does not log each deletion separately. It resets the auto-increment in MySQL and SQL Server, and in PostgreSQL only with RESTART IDENTITY; whether it can be rolled back depends on the DBMS (it can in PostgreSQL and SQL Server, not in MySQL). DROP TABLE removes the table completely: both data and structure. So for selective cleanup of test data I use DELETE ... WHERE, for resetting a whole table TRUNCATE, and I leave DROP for migrations. Without WHERE, DELETE wipes the whole table, so I always check the condition.

Read the topic

What is ACID?

ACID is four guarantees of transactions. Atomicity: all or nothing. Consistency: the database moves between valid states without violating constraints. Isolation: parallel transactions don't see each other's intermediate states. Durability: what was committed with COMMIT won't disappear even on a failure. Using a transfer as the example: money can't be debited without being credited, and with a sufficient isolation level or row locking two parallel transfers can't both spend the same balance.

Read the topic

What does INSERT ... ON CONFLICT do and how does DO NOTHING differ from DO UPDATE?

ON CONFLICT says what to do when a new row violates a unique index or a PRIMARY KEY, instead of a duplicate key error. DO NOTHING silently skips the row: the command finishes without an error and without an insert (INSERT 0 0). DO UPDATE SET ... updates the existing row, and the values from the new attempt are available through EXCLUDED. The conflict column or constraint must be named explicitly for DO UPDATE: ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name. In tests this makes data setup repeatable: a rerun neither fails nor creates duplicates. This is PostgreSQL syntax; MySQL has INSERT ... ON DUPLICATE KEY UPDATE.

Read the topic

Which isolation levels does PostgreSQL have and what does each allow?

READ COMMITTED (the default): each query sees data committed before it started, so non-repeatable reads and phantoms are possible. REPEATABLE READ: the whole transaction works with one snapshot, so there are no non-repeatable reads or phantoms, but a concurrent update of the same row ends in error 40001 and the transaction must be retried; write skew remains. SERIALIZABLE: the outcome is as if transactions ran one after another; PostgreSQL may abort one of them with error 40001, so the application must be able to retry. There is no dirty read at any level, because READ UNCOMMITTED behaves as READ COMMITTED. The level is set like this: BEGIN ISOLATION LEVEL REPEATABLE READ.

Read the topic

What is a deadlock, how does PostgreSQL handle it and how is it avoided?

A deadlock is a circle of waits: transaction A holds row 1 and waits for row 2, while B holds row 2 and waits for row 1. PostgreSQL detects this after deadlock_timeout (1 s by default) and aborts one transaction with error 40P01 “deadlock detected”; the other finishes. It is avoided with the same locking order (for example rows always by ascending id), short transactions and a retry after 40P01. To lock a row explicitly before changing it, use SELECT ... FOR UPDATE: another transaction that wants to change this row waits. In tests a deadlock shows up as a rare failure under parallel load.

Read the topic

How do you run an UPDATE or DELETE safely on a shared test environment?

First I write the same query as a SELECT with the same WHERE and look at how many rows and which ones would be affected. Then I open BEGIN, run the change and look at the row-count message (UPDATE 3): if there are more rows than expected, I ROLLBACK. Only when the number matches do I COMMIT. Before the change I copy the affected rows or record their ids so I can restore them. I tie the condition to my own test data (a marker, an email prefix) and not to the whole table. In clients with autocommit (psql, DBeaver) an explicit BEGIN is a must, otherwise the change is committed at once. An UPDATE or DELETE without WHERE touches the whole table.

Read the topic

Which constraints exist in SQL and how is each one tested?

NOT NULL: the column rejects NULL. UNIQUE: values do not repeat, but several NULLs are allowed. PRIMARY KEY: UNIQUE + NOT NULL, one per table. FOREIGN KEY: the reference must lead to an existing row of the parent table. CHECK: an arbitrary condition on the value (for example price > 0) that lets NULL pass. DEFAULT supplies a value when the column is not given. A test for each: try to insert a violation (NULL, a duplicate, a non-existing id, a negative price) and expect the specific database error (23502, 23505, 23503, 23514), and also check that a valid row passes and no duplicate appears. Boundary values for CHECK are taken on both sides of the limit (0 and 1).

Read the topic

What do ON DELETE CASCADE, SET NULL, RESTRICT and NO ACTION do?

This is the foreign key behaviour when a parent row is deleted. NO ACTION (the default): the deletion is rejected with error 23503 if child rows exist; the check happens at the end of the statement. RESTRICT: the same, but the check is immediate and cannot be deferred. CASCADE: child rows are deleted together with the parent. SET NULL: the reference column in child rows becomes NULL (it must allow NULL), SET DEFAULT: becomes its default value. For tests it matters what the business chose: if deleting a user must remove their orders, I check that they are gone; if not, I check for the error. CASCADE is dangerous: one DELETE may wipe a lot of data.

Read the topic

What is a composite index and when does an index not help?

A composite index covers several columns, for example (user_id, created_at), and its rows are ordered by the first column, then the second. So it is effective for conditions on the first column or on both, while a query on the second column alone gets no narrow range (since PostgreSQL 18 skip scan helps only when the first column has few distinct values). An index does not help when: the query returns most of the table (95% of rows), a function or cast is applied to the indexed column (lower(email), user_id::text; an expression index is needed), the LIKE pattern starts with % (LIKE '%abc'), the table is tiny, or statistics are stale. An index slows writes and takes space, so it is added for real queries and its use is checked with EXPLAIN.

Read the topic

What is normalization and which normal forms must you know?

Normalization is splitting data across tables so that one fact is stored in one place. 1NF: values are atomic, with no lists in a cell and no repeating columns. 2NF: 1NF and every non-key column depends on the whole key, not on part of it (important for composite keys). 3NF: 2NF and non-key columns do not depend on each other, only on the key (a customer’s city does not live in the order). Benefit: no inconsistencies and update anomalies. Cost: more JOINs. Denormalization (repeating data) deliberately breaks a form for read speed but needs the copies to be synchronised. A QA engineer asks whether data is duplicated and whether a fact changes in one place.

Read the topic

How do you read EXPLAIN output and how does EXPLAIN ANALYZE differ from EXPLAIN?

EXPLAIN shows the plan the planner chose and does not run the query. EXPLAIN ANALYZE really executes it and adds the actual time and row counts (actual time, rows, loops), so for INSERT, UPDATE and DELETE it is run inside a transaction with ROLLBACK to avoid changing data. In the plan, read the nodes from the bottom up: Seq Scan (a full pass), Index Scan, Index Only Scan, Bitmap Heap Scan, then JOINs and sorts. cost=a..b is an estimate (startup..total) in abstract units, not seconds. The main sign of a problem is an estimated row count far from the actual one (stale statistics, ANALYZE). Seq Scan is not always bad: on a small table or when most rows are selected it is cheaper.

Read the topic

What does QA check when testing a database migration?

First: the migration runs on a copy with production-like data (volume and "dirty" values), not only on an empty database: NOT NULL without a default or UNIQUE fails if empty values or duplicates already exist. Second: data is not lost or corrupted (row counts, checksums or a sample before and after). Third: there is a way back (rollback) and it is verified, and the migration can safely be repeated. Fourth: time and locking on a large table (ALTER TABLE takes a strong lock, on large tables it is done in stages). Fifth: the old application version still works with the new schema during deployment (add first, remove later). After the migration the application and critical queries are checked.

Read the topic

What are a partial and a covering index and when do they help?

A partial index is built only for rows that satisfy a condition: CREATE INDEX ON orders (created_at) WHERE status = 'pending'. It is small and fast when most rows have the status done, but the planner uses it only for queries whose condition follows from the index condition (WHERE status = 'pending'). A covering index contains all the columns of a query, so PostgreSQL takes data from the index itself (Index Only Scan) and does not read the table; extra columns are added with INCLUDE (...) (PostgreSQL 11+). An Index Only Scan relies on the visibility map (VACUUM), so on freshly changed data it may still visit the table. Both options save space or reads, but every index slows down writes.

Read the topic

What are window functions and how do they differ from GROUP BY?

A window function computes a value over a group of rows, but, unlike GROUP BY, doesn't collapse them: every row stays and gets an extra column. PARTITION BY sets the groups, and ORDER BY the order inside. That way I can, for example, show each transaction and next to it the total amount for its account in one query.

Read the topic

How do ROW_NUMBER, RANK and DENSE_RANK differ?

All three number rows by the sort order, and the difference is in equal values. ROW_NUMBER always gives unique numbers, RANK gives equal values an equal rank with a gap after them, and DENSE_RANK has no gap. So for "the second highest salary" taking ties into account I use DENSE_RANK, and for deduplication ROW_NUMBER.

Read the topic

How do you find the top N rows in each group?

I number the rows in each group with a window function and filter the number in an outer query: WITH r AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS rn FROM employees) SELECT * FROM r WHERE rn <= 3. A filter in the same SELECT does not work, because WHERE runs before window functions. The choice of function depends on ties: ROW_NUMBER gives at most N rows per group and breaks ties arbitrarily (an extra sort key such as id makes it stable), RANK and DENSE_RANK return everyone with an equal value, so there may be more than N rows. LIMIT with ORDER BY applies to the whole result, not to each group.

Read the topic

What do LAG and LEAD do and what do they return for edge rows?

LAG(col, n, default) OVER (ORDER BY ...) takes the value from the n-th row before the current one, and LEAD from the n-th row after. By default n = 1. For the first row (in LAG) or the last one (in LEAD) there is no such neighbour, so the result is NULL unless the third argument default is given. With PARTITION BY neighbours are looked for only within the group, and the first row of each group also gets NULL from LAG. Typical tasks: the difference from the previous day (amount - LAG(amount) OVER (ORDER BY day)), time between events, finding status changes. These functions do not merge rows, their number stays the same.

Read the topic

What is a window frame and why does LAST_VALUE with ORDER BY not return the last row?

A frame is the set of rows around the current one that a window function computes from: ROWS BETWEEN 1 PRECEDING AND CURRENT ROW means the current row and one before it. If OVER has ORDER BY and no frame is given, the default RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW applies: from the start of the group to the current row together with all rows “equal” by ORDER BY. That is why LAST_VALUE(x) OVER (ORDER BY id) returns the value of the current row itself, not of the last row in the group. To get the last one, widen the frame: ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING. The same frame makes SUM(...) OVER (ORDER BY day) give an equal sum to rows with the same day.

Read the topic

How does a window function differ from GROUP BY when you need a group total next to every row?

GROUP BY collapses the rows of a group into one, so no individual rows are left in the result. A window function SUM(amount) OVER (PARTITION BY customer_id) computes the group sum but keeps every row in place and adds the sum as a separate column. That makes it possible to compute a row’s share of the group total right away (amount * 100.0 / SUM(amount) OVER (PARTITION BY customer_id)) or a running total, which GROUP BY cannot do. Window functions are allowed only in SELECT and ORDER BY; they cannot be used in WHERE or HAVING, so filtering on their result is done in an outer query or a CTE.

Read the topic

How do you store money correctly, and what bugs are there?

Money must not be stored in FLOAT, because it has a binary error: zero point one plus zero point two is not exactly zero point three, and over thousands of operations cents get lost. The right way is NUMERIC or integer minor units. As QA I test amounts with cents, the rounding rules of fees, and whether the sum of the parts matches the total.

Read the topic

What is SQL injection and how do you test for it?

SQL injection is when user input gets into a query as code, and a special string, for example with a quote and a "one equals one" condition, changes the query's logic. The defence is parameterised queries. As QA I check search fields, filters and API parameters with basic strings with quotes and comments: I expect them to be handled as plain text, with no database errors in the response.

Read the topic

How do you verify in the database the result of a UI or API action?

I take the id from the API response (or create a unique marker in the UI, such as an email with a timestamp) and find the row by it: SELECT status, amount, currency FROM payments WHERE id = $1. I check not only that the row exists but its values: amount, status, currency, owner, time fields. I look at side effects: the balances of both accounts, journal entries, the number of rows (exactly one, not two). I also check that nothing extra changed: other rows stayed the same. For asynchronous processing I poll the DB until the expected state or a timeout, instead of a fixed sleep. The queries must be parameterised and read only the needed rows.

Read the topic

How do you find orphan records and other data integrity violations?

An orphan is a child row without a parent: SELECT o.id FROM orders o LEFT JOIN users u ON u.id = o.user_id WHERE u.id IS NULL AND o.user_id IS NOT NULL. The IS NOT NULL condition filters out rows where the reference is simply not set. NOT EXISTS (SELECT 1 FROM users u WHERE u.id = o.user_id) finds the same, but it also returns rows with NULL in user_id, so the o.user_id IS NOT NULL condition is added there too. A trap: NOT IN (SELECT ...) returns an empty result if the subquery contains even one NULL. Other checks: duplicates via GROUP BY ... HAVING COUNT(*) > 1, balances against the sum of transactions, values outside the allowed range, statuses missing from the list, dates in the future. If a foreign key exists the database will not allow an orphan; so such queries are needed for tables without constraints, after migrations and imports.

Read the topic

How do you set up and clean up test data with SQL?

Setup: INSERT the needed rows with a recognisable marker (an email prefix, a separate test tenant) and ON CONFLICT DO NOTHING so a rerun does not fail; I get ids through RETURNING, but for a row that already existed DO NOTHING returns nothing: then the id comes from a separate SELECT, or the insert uses ON CONFLICT (email) DO UPDATE SET email = EXCLUDED.email RETURNING id. Cleanup touches only this test’s data: DELETE ... WHERE email LIKE 'qa+%' in the reverse order of creation (child tables first, then parents), otherwise a foreign key stops the deletion. An alternative: open a transaction before the test and ROLLBACK after, if the test and the application share one connection. TRUNCATE fits only your own isolated database; on a shared environment it wipes other people’s data. Data must be unique for each run and independent of test order.

Read the topic

Which date and time zone traps does a QA engineer check in SQL?

For points in time (a payment creation) timestamptz is used: it stores an absolute instant and shows it in the session time zone (the TimeZone setting). timestamp without a zone is ambiguous. The cast created_at::date gives the date in the session zone, so a payment at 23:30 UTC is already the next day in Kyiv; for reports the zone is set explicitly: created_at AT TIME ZONE 'Europe/Kyiv'. Day boundaries are checked as a half-open interval >= date AND < next date, not BETWEEN, because BETWEEN includes the upper bound. Daylight saving changes, 29 February, month end and a row exactly at midnight are tested. A condition WHERE created_at::date = ... switches off a plain index on the column.

Read the topic

Task: remove duplicates, leaving one record each.

I number the rows in each group of duplicates with ROW_NUMBER and PARTITION BY and delete everything with a number greater than one, keeping the oldest record. First I run a SELECT of those same rows, and I do everything in a transaction. And I clarify whether the duplicates have child records, otherwise foreign keys won't let the delete happen or the related data will vanish through a cascade.

Read the topic

Task: the employee with the highest salary in each department.

GROUP BY with MAX gives only the maximum salary itself, not the name, so I use the window function RANK partitioned by department and take rank one, so I see everyone if several people share the maximum. An alternative without window functions is to join the table with a subquery that computes the maximum per department.

Read the topic

How do you find the N-th highest salary?

First I clarify: the N-th value or the N-th row, whether there are repeats and what to return if there is no N-th. For unique values: SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET N-1 (without DISTINCT a repeat takes a place and 250 may come out “third”), or DENSE_RANK() OVER (ORDER BY salary DESC) with the filter = N in an outer query. For the second: SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees). An aggregate without GROUP BY returns one row with NULL when there is no such salary, while OFFSET with no row gives an empty result. In PostgreSQL a NULL salary comes first with DESC, so it is filtered out by a condition.

Read the topic

How do you find gaps and islands of consecutive values?

Gaps: generate the full series and remove the existing values. SELECT s.n FROM generate_series(1, 6) AS s(n) LEFT JOIN t ON t.id = s.n WHERE t.id IS NULL (for ids 1, 2, 4, 6 these are 3 and 5). Or compare with the next value: LEAD(id) OVER (ORDER BY id) - id > 1. Islands (runs in a row, for example days of activity): for unique values the difference day - ROW_NUMBER() OVER (ORDER BY day) is the same within a run, so it is used for grouping with MIN, MAX and COUNT. For 1, 2, 3, 5, 6 the difference is 0, 0, 0, 1, 1, that is two runs. If values may repeat, they are first reduced to unique ones with DISTINCT.

Read the topic

Practice SQL with flashcards