SQL queries are the heart of working with any database. They help you fetch, update, insert, or delete data using simple commands. If you are looking for a job that involves data handling, writing SQL queries is something you’ll be tested on. Interviewers often ask practical questions to check how well you understand query logic, joins, filtering, grouping, and subqueries. That’s why this blog brings you the most commonly asked SQL query interview questions, from beginner-level queries to tricky ones. Each answer is written in a way that is easy to understand and useful for interviews.
Fun Fact – According to the 2024 Stack Overflow Developer Survey, 54.1% of professional developers reported using SQL. This shows how important SQL is for working with and managing data in real jobs.
Note – This list of top 100 SQL query interview questions is divided into different categories. It will help you go through the questions faster and find what you need easily.
Note – For better understanding and practical context, we’ll be using the following sample tables throughout the queries.
1. Employees Table
EMP_ID | NAME | DEPARTMENT | SALARY | HIRE_DATE | MANAGER_ID |
101 | Alice | HR | 50000 | 2021-01-15 | NULL |
102 | Bob | IT | 60000 | 2020-03-10 | 101 |
103 | Carol | IT | 65000 | 2019-07-20 | 101 |
104 | David | Sales | 55000 | 2022-05-01 | 101 |
105 | Eve | Sales | 54000 | 2021-11-25 | 101 |
106 | Frank | IT | 62000 | 2023-02-14 | 102 |
2. Orders Table
ORDER_ID | CUSTOMER_ID | ORDER_DATE | AMOUNT | REGION |
201 | C001 | 2024-01-10 | 250 | North |
202 | C002 | 2024-01-15 | 400 | East |
203 | C001 | 2024-02-01 | 300 | North |
204 | C003 | 2024-03-05 | 150 | South |
205 | C004 | 2024-03-10 | 600 | East |
206 | C002 | 2024-03-15 | 200 | East |
3. Customers Table
CUSTOMER_ID | NAME | CITY | SIGNUP_DATE |
C001 | John | Delhi | 2023-12-10 |
C002 | Priya | Mumbai | 2023-11-20 |
C003 | Ahmed | Bengaluru | 2023-10-05 |
C004 | Sneha | Kolkata | 2024-01-18 |
C005 | Ramesh | Hyderabad | 2024-02-11 |
Basic SQL Queries for Interview
This is a list of basic interview questions on SQL queries, along with their answers.
- What does the SELECT statement do in SQL?
The SELECT statement is used to fetch data from one or more tables in a database. You can choose specific columns or use * to select all columns.
- How do you retrieve unique records from a table?
Use the DISTINCT keyword. For example, SELECT DISTINCT city FROM customers; returns only unique cities from the customers table.
- What is the difference between WHERE and HAVING clauses?
WHERE filters rows before aggregation; HAVING filters results after aggregation. WHERE works on raw data; HAVING works on grouped results.
- How do you sort records in SQL?
Use ORDER BY. You can sort in ascending (ASC) or descending (DESC) order. Example: SELECT * FROM products ORDER BY price DESC;.
- What is the use of the LIMIT clause?
LIMIT restricts the number of rows returned by a query. Example: SELECT * FROM orders LIMIT 10; returns the first 10 records.
- What is a primary key in SQL?
A primary key uniquely identifies each row in a table. It must be unique and cannot be null. Each table can have only one primary key.
Note – Basic SQL query-based interview questions often include simple commands, filtering, sorting, joins, and basic aggregations.
SQL Queries Interview Questions for Freshers
Here are some frequently asked interview questions on SQL queries and their answers.
- What is SQL?
SQL (Structured Query Language) is a standard programming language used to manage and work with relational databases. It allows you to create, read, update, and delete data stored in tables.
- What is an SQL query?
An SQL query is a command written in SQL to perform an action on a database—like retrieving data, updating records, or deleting rows. For example, SELECT * FROM users; is a query to fetch all user records.
- What are the different types of SQL statements?
SQL statements fall into categories like:
- DML (Data Manipulation Language): SELECT, INSERT, UPDATE, DELETE
- DDL (Data Definition Language): CREATE, ALTER, DROP
- DCL (Data Control Language): GRANT, REVOKE
- TCL (Transaction Control Language): COMMIT, ROLLBACK, SAVEPOINT
- How do you insert data into a table?
Use the INSERT INTO statement. Example:
INSERT INTO employees (id, name, salary) VALUES (1, ‘John’, 50000);
- What is the difference between DELETE and TRUNCATE?
DELETE removes specific rows based on a condition and can be rolled back. TRUNCATE removes all rows quickly but can’t be rolled back in most systems.
- How do you update a record in SQL?
Use the UPDATE statement with a WHERE clause. Example:
UPDATE employees SET salary = 60000 WHERE id = 1;
- What is the purpose of the GROUP BY clause?
GROUP BY groups rows that have the same values in specified columns. It’s often used with aggregate functions like SUM, AVG, and COUNT.
Note – SQL query-related interview questions for freshers include basic syntax, simple queries, filtering, sorting, and joins.
SQL Interview Queries for Experienced
Let’s go through some important SQL query interview questions for experienced professionals and their answers.
- How do you optimize a slow-running query?
“I usually start by checking indexes on columns used in joins or filters. I also look at the execution plan to identify full table scans or bottlenecks. Rewriting subqueries, reducing joins, and limiting returned columns often helps.”
- What is a correlated subquery?
A correlated subquery depends on the outer query. It runs once for each row processed by the outer query.
Example:
SELECT name FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees WHERE department = e.department);
- How do indexes impact query performance?
Indexes speed up searches by letting the database locate data faster, especially on large tables. However, they can slow down insert/update operations since indexes need to be updated too.
- What are window functions and where are they used?
Window functions perform calculations across a set of rows related to the current row. They are used in ranking, running totals, or comparisons without collapsing rows. Example: ROW_NUMBER(), RANK(), SUM() OVER.
- How do you debug a failing SQL query in production?
“I break down the query and run parts of it to isolate the issue. I also check for missing joins, invalid column names, or bad data. Reviewing logs and query plans helps too.”
Note – SQL query-related interview questions for experienced candidates often include complex joins, subqueries, indexing, and real-world scenarios.
SQL Queries Interview Questions for 2 Years Experienced
Here are some SQL queries asked in interview questions for candidates with 2 years of experience.
- How would you find duplicate records in a table?
- How can you find the second highest salary from a table?
- How do you get the top 3 employees by department based on salary?
SQL Queries Interview Questions for 3 Years Experienced
SQL queries asked in interview for professionals with three years of experience.
- How would you write a query to check for gaps in sequential IDs?
- What is the difference between INNER JOIN and LEFT JOIN?
- When would you use a FULL OUTER JOIN?
SQL Query Interview Questions for 5 Years Experienced
These are some common SQL interview queries for 5 years experienced candidates.
- How do you join more than two tables?
- What is normalization in SQL?
- What is the difference between OLTP and OLAP?
SQL Query Interview Questions for 7 Years Experienced
Here are some frequently asked queries in SQL in interviews for professionals with 7 years of experience.
- What is a foreign key constraint?
- Write a query to reverse a string using SQL.
- Write a query to pivot table data without using PIVOT.
Advanced SQL Queries for Interview
Let’s go through some advanced SQL query interview questions and answers.
- How do you split comma-separated values into rows in SQL?
Use a string-splitting function.
In PostgreSQL:
SELECT unnest(string_to_array(‘A,B,C’, ‘,’)) AS item;
In SQL Server:
SELECT value FROM STRING_SPLIT(‘A,B,C’, ‘,’);
- Using the employees table, write a SQL query to transpose department names into columns with total salary.
Use CASE statements with aggregation:
SELECT
SUM(CASE WHEN department = ‘HR’ THEN salary ELSE 0 END) AS HR_Salary,
SUM(CASE WHEN department = ‘IT’ THEN salary ELSE 0 END) AS IT_Salary,
SUM(CASE WHEN department = ‘Sales’ THEN salary ELSE 0 END) AS Sales_Salary
FROM employees;
- Using the employees table, find employees earning more than the average salary across the company.
SELECT emp_id, name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
- Using the orders table, write a query to count the number of orders placed by each customer.
SELECT customer_id, COUNT(*) AS total_orders
FROM orders
GROUP BY customer_id;
Note – Each SQL question and answer here is designed to test advanced-level concepts in interviews.
SQL Queries Scenario-Based Interview Questions
These are some scenario-based SQL queries interview questions with answers.
- Using the orders table, write a query to calculate the running total of order amounts by customer.
SELECT customer_id, order_date, amount,
SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running_total
FROM orders;
- From the orders table, find customers who placed more than one order.
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 1;
- Using the customers table, find and remove duplicate customer records (assume duplicates based on name and city).
To identify:
SELECT name, city, COUNT(*)
FROM customers
GROUP BY name, city
HAVING COUNT(*) > 1;
Note – Scenario-based SQL queries questions for interview often test your problem-solving skills and real-world understanding.
Tricky SQL Queries for Interview
This is a list of tricky SQL queries interview questions and their answers.
- Using the orders table, find customers who didn’t place an order in the last 30 days.
SELECT customer_id
FROM customers
WHERE customer_id NOT IN (
SELECT customer_id
FROM orders
WHERE order_date >= CURRENT_DATE – INTERVAL ’30 days’
);
- Calculate the percentage of total order amount contributed by each region.
SELECT region,
SUM(amount) AS total,
ROUND(SUM(amount) * 100.0 / SUM(SUM(amount)) OVER(), 2) AS percentage
FROM orders
GROUP BY region;
- Using an invoices table, write a query to find gaps in invoice numbers.
Assume invoice numbers are sequential integers:
SELECT invoice_number + 1 AS missing_invoice
FROM invoices i
WHERE NOT EXISTS (
SELECT 1 FROM invoices WHERE invoice_number = i.invoice_number + 1
);
Note – Tricky SQL-based interview questions are often asked in technical rounds to assess logical thinking and query skills.
Complex SQL Queries Interview Questions
Let’s go through some complex SQL interview questions and answers.
- Using the orders table, calculate the cumulative percentage of sales per region.
SELECT region, amount,
SUM(amount) OVER (PARTITION BY region ORDER BY order_date) * 100.0 / SUM(amount) OVER() AS cumulative_pct
FROM orders;
- Using the employees table with manager_id, flatten the reporting hierarchy using a recursive CTE.
It is one of the toughest SQL interview questions.
WITH RECURSIVE hierarchy AS (
SELECT emp_id, name, manager_id, 1 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.emp_id, e.name, e.manager_id, h.level + 1
FROM employees e
JOIN hierarchy h ON e.manager_id = h.emp_id
)
SELECT * FROM hierarchy;
- Write a query to generate a calendar table for the year 2025.
WITH RECURSIVE calendar AS (
SELECT DATE ‘2025-01-01’ AS day
UNION ALL
SELECT day + INTERVAL ‘1 day’
FROM calendar
WHERE day < ‘2025-12-31’
)
SELECT * FROM calendar;
Note – Complex SQL queries questions for interview often focus on nested queries, advanced joins, and performance logic.
Role-Based SQL Queries Questions for Interview
SQL Queries for Software Testers
Here are some commonly asked interview questions for SQL queries for testers.
- How do you write a query to check data consistency between two related tables?
You can compare values between the two tables using EXCEPT, NOT EXISTS, or JOIN.
SELECT id, status FROM source_table
EXCEPT
SELECT id, status FROM target_table;
- How can you verify the record count between a source and a target table during testing?
Use subqueries or separate count statements:
SELECT
(SELECT COUNT(*) FROM source_table) AS source_count,
(SELECT COUNT(*) FROM target_table) AS target_count;
- How can you use SQL joins to validate data mappings between two tables?
Join the source and target tables using the primary key and compare fields:
SELECT s.id, s.name, t.name
FROM source_table s
JOIN target_table t ON s.id = t.id
WHERE s.name != t.name;
Note – SQL queries for testing interview often include data validation, joins, and checks on database integrity.
SQL Questions for Data Engineer
Here are some important SQL query interview questions and answers for data engineer.
- How do you write an ETL audit query to compare row counts between staging and final tables?
SELECT
(SELECT COUNT(*) FROM staging_table) AS staging_count,
(SELECT COUNT(*) FROM final_table) AS final_count;
- How can you validate referential integrity using SQL in a data pipeline?
SELECT * FROM child_table
WHERE parent_id NOT IN (SELECT id FROM parent_table);
- How can you identify slowly changing dimension (SCD) changes using SQL?
Compare current and historical data. For example:
SELECT * FROM history_table h
JOIN current_table c ON h.id = c.id
WHERE h.address != c.address AND h.end_date IS NULL;
Also Read - Top 40+ ETL Testing Interview Questions and Answers
SQL Query Interview Questions for Data Analyst
Let’s go through the most asked SQL queries in interviews for data analysts.
- Write a query to calculate the median value of a numeric column.
In PostgreSQL:
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY column_name) AS median
FROM table_name;
- How do you write a SQL query to identify user churn over time?
Find users with only one recorded activity:
SELECT user_id
FROM activity
GROUP BY user_id
HAVING COUNT(*) = 1;
- Write a query to calculate monthly user retention using order or login data.
Use a self-join on user and month:
SELECT a.user_id, a.login_month, b.login_month AS retained_month
FROM logins a
JOIN logins b ON a.user_id = b.user_id
WHERE a.login_month = ‘2024-01’ AND b.login_month = ‘2024-02’;
ETL Testing SQL Queries Interview Questions
Here are some common ETL testing interview questions on SQL queries.
- How do you write a SQL query to compare row-level data between staging and target tables?
SELECT * FROM staging s
FULL OUTER JOIN final f ON s.id = f.id
WHERE s.value != f.value OR s.value IS NULL OR f.value IS NULL;
- How do you test transformation logic using SQL when values are modified or derived?
Apply the logic manually and compare:
SELECT id, source_value, source_value * 1.1 AS expected, transformed_value
FROM target_table
WHERE ROUND(source_value * 1.1, 2) != transformed_value;
- How do you write a query to validate if any data was truncated during ETL load?
SELECT * FROM target
WHERE LENGTH(description) < LENGTH(source_description);
- Write a query to check for NULLs in key fields after transformation is complete.
SELECT * FROM final_table
WHERE key_column IS NULL OR date_field IS NULL;
Concept-Based SQL Queries Questions for Interview
JOIN SQL Queries for Interview
These are some common interview questions on join in SQL.
- What is the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN?
- INNER JOIN returns only matching records between two tables.
- LEFT JOIN returns all rows from the left table and matching rows from the right table.
- RIGHT JOIN returns all rows from the right table and matching rows from the left.
- FULL JOIN returns all rows from both tables, with NULLs where there is no match.
- How do you join three tables and filter based on one of them?
You can join them using proper keys and apply the filter in the WHERE clause:
SELECT o.order_id, c.name, p.product_name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
JOIN products p ON o.product_id = p.product_id
WHERE p.category = ‘Electronics’;
- What’s the impact of join order on query performance?
In most modern databases, the optimizer decides join order automatically. But large joins without indexes can still slow down performance. Filtering early and joining smaller result sets can improve execution time.
Note – Interview questions on SQL join queries often check your understanding of data relationships across multiple tables.
DB Queries for Interview
Here are some common DB queries interview questions and answers.
- How do you get the list of all tables in a database?
In PostgreSQL or MySQL:
SELECT table_name FROM information_schema.tables WHERE table_schema = ‘public’;
- How do you fetch the column names and types for a specific table?
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = ‘your_table_name’;
- How do you list indexes created on a table?
In PostgreSQL:
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = ‘your_table_name’;
In MySQL:
SHOW INDEXES FROM your_table_name;
DBMS Queries Interview Questions
- What is a transaction in SQL?
A transaction is a sequence of operations performed as a single unit of work. It must either complete fully or not at all. Transactions help maintain data integrity.
- What are the properties of a transaction (ACID)?
- Atomicity: All operations succeed or none do.
- Consistency: Data remains valid after the transaction.
- Isolation: Transactions don’t interfere with each other.
- Durability: Once committed, the changes persist.
- How do you implement concurrency control in SQL?
Concurrency is managed through isolation levels like READ COMMITTED or SERIALIZABLE. Locks and row-level control prevent conflicts when multiple users access the same data.
- What are views and how are they used?
A view is a virtual table created from a query. It simplifies complex joins or hides columns:
CREATE VIEW active_customers AS
SELECT * FROM customers WHERE status = ‘active’;
You can then query it like a regular table.
SQL Theory Questions
You might also come across theoretical SQL questions like these.
- What are constraints in SQL and name a few types?
Constraints limit the data allowed in a column. Common types include:
- PRIMARY KEY – Uniquely identifies a row
- FOREIGN KEY – Links to another table
- NOT NULL – Disallows NULL values
- UNIQUE – Prevents duplicate values
- CHECK – Validates based on conditions
- What is a stored procedure and when would you use it?
A stored procedure is a saved block of SQL code that performs a task. It’s used for repetitive operations like inserting or validating records. It improves performance and consistency.
- What is a trigger in SQL?
A trigger is a predefined action that runs automatically in response to events like INSERT, UPDATE, or DELETE. It’s used for logging, enforcing business rules, or syncing audit tables.
- What are aggregate functions in SQL?
Aggregate functions perform calculations on multiple rows and return a single result. Examples include:
- SUM()
- AVG()
- MAX()
- MIN()
- COUNT()
Note – These top SQL queries interview questions include theoretical concepts often asked by recruiters.
SQL Practical Interview Questions
Here are some commonly asked SQL practical questions for interview.
SQL Programming Interview Questions
Here are some frequently asked SQL query examples with answers.
- How do you write a stored procedure to update multiple tables?
Use separate UPDATE statements inside a procedure:
CREATE PROCEDURE update_data()
BEGIN
UPDATE orders SET status = ‘Shipped’ WHERE order_id = 101;
UPDATE inventory SET stock = stock – 1 WHERE product_id = 55;
END;
- How do you use IF…ELSE in SQL scripts?
IF total > 1000 THEN
UPDATE status SET level = ‘Premium’;
ELSE
UPDATE status SET level = ‘Standard’;
END IF;
- What are temporary tables and when should you use them?
Temporary tables store data during a session. Use them for intermediate calculations or transformations in complex scripts.
- How do you declare and use variables in SQL?
DECLARE total_sales INT;
SET total_sales = (SELECT SUM(amount) FROM orders);
SQL Coding Interview Questions
Let’s look at some practical SQL coding questions and their solution.
- Write a query to convert rows to a comma-separated string.
SELECT STRING_AGG(name, ‘, ‘) FROM employees;
- Using employees, rank employees by salary within each department.
SELECT name, department, salary,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rank
FROM employees;
- Using orders, calculate running average of order amount by customer.
SELECT customer_id, order_date,
AVG(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running_avg
FROM orders;
- Using employees, get top 2 highest paid employees per department.
SELECT * FROM (
SELECT *, RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk
FROM employees
) t WHERE rnk <= 2;
SQL Questions for Practice
These SQL query questions and answers for practice will help you improve your skills and build confidence.
- Using the orders table, write a query to find the number of days between order_date and today.
SELECT order_id, customer_id,
CURRENT_DATE – order_date AS days_since_order
FROM orders;
- Write a query to count NULL values in each column of a table.
Since SQL doesn’t support column-wise dynamic aggregation easily, use individual counts:
SELECT
COUNT(*) – COUNT(col1) AS col1_nulls,
COUNT(*) – COUNT(col2) AS col2_nulls
FROM your_table;
- Write a query to find customers who have placed orders in all regions.
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(DISTINCT region) = (SELECT COUNT(DISTINCT region) FROM orders);
- Using the employees table, fetch the top 5 highest paid employees.
SELECT emp_id, name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;
- Using the orders table, get the total number of orders per customer.
SELECT customer_id, COUNT(*) AS total_orders
FROM orders
GROUP BY customer_id;
Note – SQL questions and answers for practice often include basic queries, joins, filtering, sorting, and aggregations.
Company-Specific SQL Query Interview Questions
This is a list of top SQL queries asked in interviews at various IT companies in India.
Oracle SQL Query Questions
These are some queries asked in SQL in oracle interview.
- How do you use the ROWNUM pseudocolumn in Oracle SQL?
- What is the difference between RANK() and DENSE_RANK() in Oracle SQL?
- How do you write a hierarchical query using CONNECT BY?
- How do you use MERGE statements for UPSERT operations in Oracle SQL?
Note – Interview questions on Oracle SQL queries often include PL/SQL blocks, functions, joins, and performance tuning.
Also Read - Top 30+ PL/SQL Interview Questions and Answers
SQL Queries for Amazon Interview
Here are some common SQL queries asked in interview questions at Amazon.
- Write a query to get the most viewed product in each category.
- Write a query to find users who bought the same item more than once.
- How do you write a query to find products with increasing daily sales for 3 days in a row?
- Write a query to calculate conversion rate per user session.
TCS Interview Questions on SQL Queries
At TCS, you might come across SQL query-based interview questions.
- How do you write a query to remove duplicate rows using ROW_NUMBER()?
- How do you find employees who never received a bonus?
- How do you write a query to fetch alternate rows from a table?
- Write a query to get the highest and lowest salary in each department.
- Write a query to count how many employees joined each month.
Teradata SQL Queries Interview Questions
These are some SQL queries asked in interview questions at Teradata.
- What is QUALIFY in Teradata SQL and how is it used?
- Write a query using RANK in Teradata to get top 3 salaries per department.
- How do you use CASE in SELECT clause in Teradata?
- How do you handle large datasets efficiently using Teradata SQL?
Wrapping Up
And this wraps up the 100 most commonly asked SQL query interview questions and answers. Practice these regularly, understand the logic, and you’ll feel more confident during interviews.
Looking for SQL jobs? Check out Hirist — an online job portal built for tech professionals. You can easily find the top SQL jobs in India, all in one place.
FAQs
What are some important queries in SQL for interview?
Some imp SQL query for interviews include –
- Find second highest salary using subquery
- Count orders per customer
- Use JOIN to combine two tables
- Get top N records per group
Where can I find SQL server practice questions?
You can find SQL Server practice questions on LeetCode, InterviewBit, and SQLZoo. Many blogs and GitHub repositories also share real interview sets.
How to explain SQL query in interview?
Break it down step-by-step – mention what the query does, which tables it uses, how joins or filters work, and what the final output looks like.
What are some commonly asked SQL command interview questions?
Common SQL command interview questions include –
- What does SELECT do?
- Difference between DELETE and TRUNCATE
- How does UPDATE work with a JOIN?
- What is a WHERE clause?
How to write SQL query easily?
Understand the schema, then write from SELECT to FROM, apply joins or conditions, and use aliases for clarity.
What are some frequently asked performance tuning in SQL server interview questions?
Topics include indexing, query plans, avoiding full table scans, and using EXISTS vs IN. These are common SQL queries questions for interview rounds.
Give me a list of MySQL query interview questions.
Sample SQL query questions include –
- Use of LIMIT and OFFSET
- String functions like CONCAT()
- Filtering with BETWEEN and LIKE
How to practice SQL queries for interview?
Practice SQL query-based interview questions using sample databases like Sakila or Employees on platforms such as SQLFiddle, Mode Analytics, or your local SQL editor.
What are some tips to prepare for SQL query interview questions?
Focus on real-life use cases, revise JOINs, use online platforms, and solve daily scenarios with different query types.
What is the average salary for SQL-skilled professionals in India?
According to AmbitionBox, as of 2025, SQL Developer salaries in India typically range from ₹2.0 Lakhs to ₹9.0 Lakhs per year. Specialized roles and positions in top companies may offer higher compensation.