20 SQL Questions
1. Write an SQL query to select the top 5 highest-paid employees from an Employee table
(fields: id, name, salary).
2. How do you find duplicate rows in a table based on a single column? Provide an example
query.
3. Given Orders(order_id, customer_id, order_date, total), write a query to compute
monthly sales for the last 12 months.
4. Explain how an INNER JOIN differs from LEFT JOIN and provide example queries for both.
5. Write a query to delete rows older than 30 days from a table named sessions with a
column created_at.
6. How do you add a unique constraint to an existing table? Provide the ALTER TABLE
statement.
7. Given a Products table, write a query to get the second highest price without using
LIMIT with offset (use a subquery).
8. Explain the difference between WHERE and HAVING with examples.
9. How to pivot rows into columns in SQL (for example, turning product sales by month into
columns)?
10. Write a query to find the running total of sales ordered by order_date using window
functions.
11. How do you optimize a slow query? List at least five approaches and explain briefly.
12. Write a query to find customers who have never placed an order (Customers and Orders
tables).
13. Explain transactions and isolation levels; give examples of anomalies (dirty read,
non-repeatable read, phantom read).
14. How to perform an UPSERT (insert or update) in SQL (give examples for PostgreSQL and
MySQL).
15. Given a large table, how would you remove duplicate rows while keeping one copy?
16. Explain indexes: B-tree vs hash indexes, and when to use each.
17. Write a query to get the nth row per group (for example, the top 3 orders per
customer).
18. Describe how to design a normalized schema for a blog system (posts, comments, tags)
up to 3NF.
19. How to safely perform schema migrations in production with zero-downtime strategies?
20. Given a table with JSON column (Postgres), show how to query nested JSON fields and
index them.