Testing Fundamentals
SQL Interview Questions & Answers
SQL interview questions for testers: joins, aggregation, subqueries, CTEs, window functions, Nth highest salary, duplicates and data reconciliation.
Interview Questions
Showing 15 of 50 questions
DDL defines structure (CREATE, ALTER, DROP, TRUNCATE), DML manipulates data (SELECT, INSERT, UPDATE, DELETE), DCL controls access (GRANT, REVOKE) and TCL manages transactions (COMMIT, ROLLBACK, SAVEPOINT).
WHERE filters individual rows before grouping and cannot use aggregate functions, while HAVING filters groups after GROUP BY and can use aggregates like COUNT or SUM.
INNER JOIN returns only matching rows, LEFT JOIN returns all rows from the left table with NULLs where there is no match, RIGHT JOIN does the opposite, FULL OUTER JOIN returns all rows from both, and CROSS JOIN returns every combination.
DELETE is DML that removes selected rows using WHERE and fires triggers, TRUNCATE is DDL that quickly removes all rows while keeping the table structure, and DROP removes the table itself including structure, data and indexes.
NULL means unknown, so comparisons with = or <> return unknown rather than true. Use IS NULL or IS NOT NULL to check it, and COALESCE to substitute a default value.
UNION combines results and removes duplicates, while UNION ALL keeps all rows including duplicates and is faster because it skips the de-duplication step.
Group by the customer, count rows per group and order by the count descending; join to customers to include names.
A portable approach is to find the max salary that is less than the overall max. Alternatively use DISTINCT with ORDER BY and LIMIT/OFFSET, or DENSE_RANK.
Use DENSE_RANK ordered by salary descending, optionally partitioned by department, and filter on the rank. DENSE_RANK handles ties without skipping ranks.
Group by the columns that define a duplicate and keep groups where COUNT is greater than one. To see the full rows, use a window COUNT or join back.
Number rows within each duplicate group using ROW_NUMBER and delete every row whose number is greater than one, keeping the lowest id.
A subquery is a query nested inside another. A correlated subquery references the outer query and is logically evaluated once per outer row. Joins are often more readable and efficient for combining columns, while EXISTS subqueries are ideal for existence checks.
A Common Table Expression, defined with WITH, is a named temporary result set used within one query. It makes complex queries readable, lets you reuse a result multiple times, and supports recursion for hierarchies.
ROW_NUMBER gives a unique sequential number to every row, RANK gives tied rows the same rank and then skips numbers, and DENSE_RANK gives ties the same rank without gaps.
Self join the employees table, aliasing one copy as the employee and another as the manager, joining on manager_id, then compare salaries.