100 Practice SQL Interview Questions

SQL Interview Prep

Sign up for the latest in SQL interview resourcs from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Analyst interviews, early-career engineering roles, product/data/BI interviews, SQL skills assessment prep.

100+ SQL Interview Questions and Answers

Preparing for an SQL interview can be intimidating, but having a solid grasp of common questions and answers will boost your confidence. Below is a comprehensive list of over 100 SQL interview questions, organized by difficulty and topic. This resource is perfect for developers, analysts, engineers, product managers, and anyone prepping for technical interviews.

🔹 Basic SQL

1. What is SQL?

SQL (Structured Query Language) is the standard language used to manage relational databases. It allows users to retrieve, insert, update, and delete data, as well as manage database structure and permissions.

2. What are the different types of SQL statements?

  • DDL (Data Definition Language): CREATE, ALTER, DROP

  • DML (Data Manipulation Language): SELECT, INSERT, UPDATE, DELETE

  • DCL (Data Control Language): GRANT, REVOKE

  • TCL (Transaction Control Language): COMMIT, ROLLBACK, SAVEPOINT

3. What is a primary key?

A primary key uniquely identifies each record in a table. It must be unique and cannot contain NULL values.

4. What is a foreign key?

A foreign key is a column (or set of columns) that creates a link between two tables by referencing the primary key of another table.

5. What is the difference between WHERE and HAVING?

  • WHERE filters rows before aggregation.

  • HAVING filters after aggregation.

6. What does NULL mean in SQL?

NULL represents a missing or undefined value. It is not equivalent to zero or an empty string.

7. What is a unique key?

A unique key ensures all values in a column or group of columns are distinct. Unlike the primary key, it allows a single NULL.

8. What are constraints in SQL?

Constraints enforce rules on data, such as:

  • NOT NULL

  • UNIQUE

  • PRIMARY KEY

  • FOREIGN KEY

  • CHECK

  • DEFAULT

9. What is normalization?

Normalization is the process of organizing data to reduce redundancy and improve data integrity. Common forms include:

  • 1NF (First Normal Form)

  • 2NF (Second Normal Form)

  • 3NF (Third Normal Form)

10. What is denormalization?

Denormalization introduces redundancy for improved read performance. It’s often used in OLAP/data warehousing scenarios.

11. What is a composite key?

A composite key is made up of two or more columns used to uniquely identify rows in a table.

12. What is the difference between DELETE, TRUNCATE, and DROP?

  • DELETE: Removes rows based on condition; can be rolled back.

  • TRUNCATE: Removes all rows; cannot be rolled back.

  • DROP: Deletes the entire table structure and data.

13. What is a view?

A view is a virtual table based on a SELECT statement. It does not store data but shows results of a query.

14. How do you create a table in SQL?

CREATE TABLE employees (

  id INT PRIMARY KEY,

  name VARCHAR(100),

  department VARCHAR(50)

);

15. How do you update data in SQL?

UPDATE employees SET name = 'Alice' WHERE id = 1;

16. What is a GROUP BY clause?

GROUP BY aggregates rows with the same values into summary rows:

SELECT department, COUNT(*) FROM employees GROUP BY department;

17. What is the difference between COUNT(*) and COUNT(column)?

  • COUNT(*): Counts all rows.

  • COUNT(column): Counts non-null values in a column.

18. What are UNION and UNION ALL?

  • UNION: Combines and removes duplicates.

  • UNION ALL: Combines all rows, including duplicates.

19. What is the purpose of DISTINCT?

DISTINCT returns unique values for specified columns.

20. How do you filter rows using LIKE?

SELECT * FROM employees WHERE name LIKE 'A%';

21. What is a subquery?

A query nested inside another query, often in WHERE, FROM, or SELECT.

22. What is a correlated subquery?

A subquery that references columns from the outer query.

23. How do you rename a column in SQL?

ALTER TABLE employees RENAME COLUMN old_name TO new_name;

24. How do you rename a table in SQL?

ALTER TABLE old_table_name RENAME TO new_table_name;

🔹 Intermediate SQL

25. What are window functions?

Functions that perform calculations across a set of table rows related to the current row:

  • ROW_NUMBER()

  • RANK()

  • DENSE_RANK()

  • LEAD() / LAG()

26. What is ROW_NUMBER()?

Returns a unique number for each row within a partition.

27. What is the difference between RANK() and DENSE_RANK()?

RANK() skips numbers for ties, DENSE_RANK() does not.

28. What is a CTE (Common Table Expression)?

Temporary named result set used in a WITH clause.

29. What are aggregate functions in SQL?

  • SUM()

  • AVG()

  • COUNT()

  • MIN()

  • MAX()

30. What’s the difference between LEFT JOIN and RIGHT JOIN?

  • LEFT JOIN: All from left table, matching from right.

  • RIGHT JOIN: All from right table, matching from left.

31. What is COALESCE() used for?

Returns the first non-null value in a list of inputs.

32. What is the use of CASE in SQL?

Acts as an IF-THEN-ELSE for conditional logic.

33. How do you handle duplicates in a result set?

Use DISTINCT, or GROUP BY, or ROW_NUMBER() and filter.

34. How can you retrieve even and odd rows from a table?

Use MOD(id, 2) = 0 for even, = 1 for odd.

35. What is an index in SQL?

Improves performance by reducing the number of rows scanned.

36. What’s the difference between clustered and non-clustered indexes?

  • Clustered: Alters row order physically.

  • Non-clustered: Stores pointers to data.

37. What is a self-join?

A join where a table is joined to itself.

38. How do you prevent SQL injection?

Use parameterized queries, prepared statements, and avoid dynamic SQL.

39. What’s the difference between EXISTS and IN?

  • EXISTS: Checks for result existence.

  • IN: Checks membership in a list of values.

40. What is a transaction?

A sequence of operations performed atomically. Uses BEGIN, COMMIT, ROLLBACK.

41. What are ACID properties?

  • Atomicity

  • Consistency

  • Isolation

  • Durability

42. What is the difference between NOW() and CURRENT_TIMESTAMP?

Functionally similar – both return the current date and time.

43. How do you get the second highest salary in SQL?

SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);

44. How do you fetch only the first 10 rows from a table?

SELECT * FROM employees LIMIT 10;

In SQL Server:

SELECT TOP 10 * FROM employees;

45. How do you find duplicate values in a table?

SELECT column_name, COUNT(*)

FROM table_name

GROUP BY column_name

HAVING COUNT(*) > 1;

46. How do you get the number of rows in a table?

SELECT COUNT(*) FROM table_name;

47. How do you get the structure of a table?

In PostgreSQL/MySQL:

DESCRIBE table_name;

In SQL Server:

EXEC sp_help 'table_name';

48. What is a temporary table?

A table that exists temporarily during a session or transaction. It is prefixed with # in SQL Server or created via CREATE TEMP TABLE.

49. What is a materialized view?

A precomputed view stored on disk for performance. Unlike regular views, materialized views store actual data.

🔹 Advanced SQL

50. What are stored procedures?

Stored procedures are reusable SQL code blocks that perform actions such as inserts, updates, or complex logic, and can accept parameters.

51. What are triggers?

Triggers are automated procedures that run in response to database events like INSERT, UPDATE, or DELETE.

52. What is the difference between a function and a stored procedure?

  • Functions return a value and can be used in SELECT statements.

  • Procedures may not return a value and are executed standalone.

53. How does the optimizer choose query plans?

The database query planner evaluates possible strategies and picks the most efficient one based on indexes, statistics, and constraints.

54. What are WITH ROLLUP and WITH CUBE?

They are extensions to GROUP BY that allow subtotals and grand totals in aggregation queries.

55. What is pivoting in SQL?

Turning rows into columns for aggregation. For example, monthly sales in columns instead of rows.

56. What is unpivoting?

Turning columns into rows, often used for flattening data structures.

57. How do you handle recursive queries?

Use recursive Common Table Expressions:

WITH RECURSIVE cte_name AS (

  SELECT ...

  UNION ALL

  SELECT ...

  FROM cte_name

  WHERE condition

)

SELECT * FROM cte_name;

58. What is the MERGE statement?

MERGE allows you to INSERT, UPDATE, or DELETE in a single query based on conditions.

59. How do you monitor query performance?

Use EXPLAIN, database-specific profiling tools (e.g. pg_stat_statements, MySQL EXPLAIN), and logs.

60. What is query optimization?

Improving query speed and efficiency by rewriting queries, creating indexes, and reducing operations like joins or subqueries.

61. What’s the difference between logical and physical query plans?

  • Logical Plan: Abstract description of operations.

  • Physical Plan: Actual implementation steps (e.g. nested loop join vs hash join).

62. What is a deadlock?

A situation where two transactions wait indefinitely for each other to release locks. Resolved via detection or timeouts.

63. What are isolation levels?

Transaction isolation levels control concurrency:

  • Read Uncommitted

  • Read Committed

  • Repeatable Read

  • Serializable

🔹 Practical Scenario Questions

64. How would you find users who haven’t logged in in the past 30 days?

SELECT * FROM users WHERE last_login < CURRENT_DATE - INTERVAL '30 days';

65. How do you identify the top 3 selling products by month?

Use window functions:

SELECT *

FROM (

  SELECT product_id, month, sales,

         RANK() OVER (PARTITION BY month ORDER BY sales DESC) AS rk

  FROM sales_table

) t

WHERE rk <= 3;

66. How do you calculate a running total?

SELECT user_id, amount,

       SUM(amount) OVER (PARTITION BY user_id ORDER BY date) AS running_total

FROM transactions;

67. How do you get the percentage of total sales per region?

SELECT region, SUM(sales) AS total_sales,

       SUM(sales) * 100.0 / SUM(SUM(sales)) OVER () AS percent_total

FROM sales

GROUP BY region;

68. How do you deduplicate rows while keeping the most recent entry?

SELECT *

FROM (

  SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY updated_at DESC) AS rn

  FROM users

) sub

WHERE rn = 1;

69. How would you compare two tables to find missing records?

SELECT id FROM table_a

EXCEPT

SELECT id FROM table_b;

70. How do you detect gaps in a sequence?

Use LEAD() and check for differences > 1.

71. How would you write a case-insensitive search?

SELECT * FROM users WHERE LOWER(name) = 'john';

72. How do you split a string in SQL?

In PostgreSQL:

SELECT regexp_split_to_table('a,b,c', ',');

73. How do you join on multiple conditions?

SELECT * 

FROM orders o

JOIN customers c 

  ON o.customer_id = c.id AND o.region = c.region;

74. How would you detect anomalies in user behavior?

Look for outliers in login frequency, activity counts, or session durations using aggregation + standard deviation or window functions.

75. How do you calculate a 7-day moving average?

SELECT user_id, event_date, 

       AVG(metric) OVER (PARTITION BY user_id ORDER BY event_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS moving_avg

FROM metrics;

76. How do you handle time zones in SQL?

Use AT TIME ZONE in PostgreSQL or CONVERT_TZ() in MySQL. Always store data in UTC and convert on display.

77. How do you filter for weekends only?

SELECT * FROM events WHERE EXTRACT(DOW FROM event_date) IN (0, 6); -- PostgreSQL: Sunday = 0

78. How would you calculate retention over time?

Cohort analysis: group users by signup date and track their return behavior in time buckets (e.g., week 0, week 1, week 2).

79. How would you pivot a table to show monthly totals per user?

Use CASE WHEN:

SELECT user_id,

  SUM(CASE WHEN month = '2024-01' THEN amount ELSE 0 END) AS jan_total,

  SUM(CASE WHEN month = '2024-02' THEN amount ELSE 0 END) AS feb_total

FROM purchases

GROUP BY user_id;

80. How do you convert a timestamp to a date?

SELECT DATE(timestamp_column) FROM events;

81. How do you get the previous row’s value?

SELECT user_id, event_date, 

       LAG(event_date) OVER (PARTITION BY user_id ORDER BY event_date) AS prev_date

FROM logins;

82. How do you join three or more tables?

Just chain joins:

SELECT * 

FROM a 

JOIN b ON a.id = b.a_id 

JOIN c ON b.id = c.b_id;

🔹 SQL on Large Datasets / Optimization

83. How do indexes improve query performance?

They allow the DB engine to locate data faster, reducing full-table scans.

84. When should you avoid indexes?

Avoid on frequently updated columns or small tables. Indexes slow down writes.

85. How do you optimize a slow-running query?

  • Use EXPLAIN

  • Add appropriate indexes

  • Reduce joins or subqueries

  • Use selective filters early

86. What are common causes of slow queries?

  • Missing indexes

  • Large joins without filters

  • SELECT *

  • Poor cardinality in join keys

87. What tools can be used for SQL profiling?

  • PostgreSQL: pg_stat_statements

  • MySQL: EXPLAIN, SHOW PROFILE

  • SQL Server: Execution Plan Viewer

88. How do you partition a large table?

Use PARTITION BY clause based on ranges, lists, or hashes (varies by DB).

89. What is the difference between horizontal and vertical partitioning?

  • Horizontal: rows split across tables

  • Vertical: columns split into separate tables

90. How would you denormalize a database for performance?

Embed related data, use redundant fields, pre-join tables into wide tables for faster read access.

91. How do you handle large joins across billions of rows?

  • Ensure indexes on join keys

  • Filter early

  • Partition large tables

  • Use batch processing

92. What are best practices for performant SQL?

  • Avoid SELECT *

  • Use covering indexes

  • Limit rows returned

  • Monitor slow queries

  • Use appropriate data types

🔹 Role-Specific Questions (Bonus)

93. What SQL skills are most important for analysts?

Joins, filtering, grouping, subqueries, window functions, and basic data wrangling.

94. How would a product manager use SQL?

To answer product usage questions: conversion funnels, retention, feature adoption.

95. What queries would an engineer use daily?

Debugging issues, writing test queries, analyzing logs/events data, profiling performance.

96. What’s the difference between OLTP and OLAP databases?

  • OLTP: transaction-heavy (e.g., MySQL, PostgreSQL)

  • OLAP: analytical queries (e.g., Redshift, BigQuery, Snowflake)

🔹 Real-World Tasks

97. How do you detect a sudden spike in user traffic?

Compare daily active users to rolling 7-day average using window functions.

98. How do you analyze user retention?

Cohort users by signup date, count returning users in each time bucket.

99. How do you join event logs to user metadata?

Use user ID or session ID as the join key, ensure consistent data types.

100. How do you test SQL queries before using them in prod?

Run on a limited dataset, use EXPLAIN, and sanity-check outputs with known inputs.

🎯 Summary

This list of 100+ SQL interview questions and answers is designed to help you:

  • Ace technical interviews

  • Brush up on fundamentals and advanced topics

  • Practice real-world scenario queries

  • Learn how to write efficient, secure SQL

💡 Next steps:

  • Try these in a SQL editor like Galaxy

  • Bookmark the Learn SQL and Glossary pages

  • Practice daily with SQL challenges