EVIKA.ACADEMY›SQL Tutorial
SQL Tutorial›Interview Questions

SQL Interview Questions

Chapter 40 of 40 · Final Chapter

These are the questions most commonly asked in data analyst SQL interviews — from basics to advanced patterns. Click any question to reveal the answer, the query, and the output. All examples use the EVIKA products / customers / orders dataset from this tutorial series.

BasicIntermediateAdvanced— click any question to expand the answer
Basics — SELECT, WHERE, ORDER BY, Aggregation
Q1BasicWrite a query to find all products priced above ₹1,000, sorted by price descending.
SELECT product_name, category, price
FROM   products
WHERE  price > 1000
ORDER  BY price DESC;
product_namecategoryprice
Ergonomic ChairFurniture8999
USB-C HubElectronics1499
Desk LampFurniture1199
Q2BasicHow many orders has each customer placed? Show customer_id and order count, sorted by count descending.
SELECT customer_id,
       COUNT(*) AS order_count
FROM   orders
GROUP  BY customer_id
ORDER  BY order_count DESC;
customer_idorder_count
C013
C021
C031
C041
C051
Q3BasicFind the total revenue, average order value, and number of orders for the entire orders table.
SELECT
  COUNT(*)                       AS total_orders,
  SUM(total_amount)              AS total_revenue,
  ROUND(AVG(total_amount), 2)    AS avg_order_value,
  MIN(total_amount)              AS smallest_order,
  MAX(total_amount)              AS largest_order
FROM orders;
total_orderstotal_revenueavg_order_valuesmallest_orderlargest_order
7150792154.142998999
Q4BasicList all unique cities where customers are based.
SELECT DISTINCT city
FROM   customers
ORDER  BY city;
city
Bengaluru
Delhi
Mumbai
Noida
Pune
Q5BasicFind all products whose name contains the word 'USB' or starts with 'Desk'.
SELECT product_name, price
FROM   products
WHERE  product_name LIKE '%USB%'
   OR  product_name LIKE 'Desk%';
product_nameprice
USB-C Hub1499
Desk Lamp1199
JOINs
Q6BasicShow each order with the customer's name and the product name.
SELECT o.order_id, o.order_date,
       c.customer_name, p.product_name,
       o.total_amount
FROM   orders    AS o
JOIN   customers AS c ON o.customer_id = c.customer_id
JOIN   products  AS p ON o.product_id  = p.product_id
ORDER  BY o.order_date;
order_idorder_datecustomer_nameproduct_nametotal_amount
10012026-10-01Amit VermaWireless Mouse899
10022026-10-02Priya SharmaUSB-C Hub1499
10032026-10-03Amit VermaNotebook A5495
Q7IntermediateFind customers who have never placed an order.

Two approaches — LEFT JOIN anti-join or NOT EXISTS (preferred when NULLs may be present):

-- Method 1: LEFT JOIN + IS NULL
SELECT c.customer_id, c.customer_name
FROM   customers AS c
LEFT   JOIN orders AS o ON c.customer_id = o.customer_id
WHERE  o.order_id IS NULL;

-- Method 2: NOT EXISTS (NULL-safe)
SELECT customer_id, customer_name
FROM   customers AS c
WHERE  NOT EXISTS (
  SELECT 1 FROM orders o
  WHERE  o.customer_id = c.customer_id
);
customer_idcustomer_name
C06Kavita Rao
Q8IntermediateWhich products have never been ordered?
SELECT p.product_id, p.product_name, p.category
FROM   products AS p
LEFT   JOIN orders AS o ON p.product_id = o.product_id
WHERE  o.order_id IS NULL;

In our dataset every product has at least one order, so this returns 0 rows — but the pattern is what interviewers test.

Q9IntermediateShow total revenue by city, including cities with zero orders.
SELECT c.city,
       COUNT(o.order_id)        AS orders,
       COALESCE(SUM(o.total_amount), 0) AS revenue
FROM   customers AS c
LEFT   JOIN orders AS o ON c.customer_id = o.customer_id
GROUP  BY c.city
ORDER  BY revenue DESC;
cityordersrevenue
Mumbai18999
Noida44282
Delhi11499
Bengaluru1299
Pune00
Aggregation, GROUP BY, HAVING
Q10IntermediateFind categories where the average product price is above ₹500.
SELECT category,
       ROUND(AVG(price), 2) AS avg_price,
       COUNT(*)             AS product_count
FROM   products
GROUP  BY category
HAVING AVG(price) > 500
ORDER  BY avg_price DESC;
categoryavg_priceproduct_count
Furniture50992
Electronics8993
Q11IntermediateFind the second highest order total.

Classic interview question — two reliable approaches:

-- Method 1: subquery
SELECT MAX(total_amount) AS second_highest
FROM   orders
WHERE  total_amount < (SELECT MAX(total_amount) FROM orders);

-- Method 2: DENSE_RANK (handles ties correctly)
WITH ranked AS (
  SELECT total_amount,
         DENSE_RANK() OVER (ORDER BY total_amount DESC) AS rnk
  FROM   orders
)
SELECT total_amount AS second_highest
FROM   ranked
WHERE  rnk = 2
LIMIT  1;
second_highest
2398
Q12IntermediateFind customers who have spent more than the average customer spend.
WITH customer_totals AS (
  SELECT customer_id,
         SUM(total_amount) AS total_spent
  FROM   orders
  GROUP  BY customer_id
)
SELECT customer_id, total_spent
FROM   customer_totals
WHERE  total_spent > (SELECT AVG(total_spent) FROM customer_totals)
ORDER  BY total_spent DESC;
customer_idtotal_spent
C038999
C042398
C011884
Window Functions
Q13AdvancedRank products by price within each category. Show the top-ranked product per category.
WITH ranked AS (
  SELECT product_name, category, price,
         RANK() OVER (
           PARTITION BY category
           ORDER BY price DESC
         ) AS price_rank
  FROM products
)
SELECT product_name, category, price
FROM   ranked
WHERE  price_rank = 1
ORDER  BY price DESC;
product_namecategoryprice
Ergonomic ChairFurniture8999
USB-C HubElectronics1499
Notebook A5Stationery99
Q14IntermediateCalculate a running total of revenue ordered by order date.
SELECT order_id, order_date, total_amount,
       SUM(total_amount) OVER (
         ORDER BY order_date
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS running_total
FROM   orders
ORDER  BY order_date;
order_idorder_datetotal_amountrunning_total
10012026-10-01899899
10022026-10-0214992398
10032026-10-034952893
10042026-10-04899911892
Q15AdvancedFor each order, show the previous order amount for the same customer (LAG).
SELECT order_id, customer_id, order_date, total_amount,
       LAG(total_amount) OVER (
         PARTITION BY customer_id
         ORDER BY order_date
       ) AS prev_order_amount,
       total_amount - LAG(total_amount) OVER (
         PARTITION BY customer_id
         ORDER BY order_date
       ) AS change_from_prev
FROM   orders
ORDER  BY customer_id, order_date;
order_idcustomer_idtotal_amountprev_order_amountchange_from_prev
1001C01899NULLNULL
1003C01495899-404
1007C01490495-5
1002C021499NULLNULL
Q16IntermediateWhat is the difference between RANK, DENSE_RANK, and ROW_NUMBER?

Use prices 899, 899, 299 (two items tied at 899):

SELECT product_name, price,
       ROW_NUMBER()  OVER (ORDER BY price DESC) AS row_num,
       RANK()        OVER (ORDER BY price DESC) AS rnk,
       DENSE_RANK()  OVER (ORDER BY price DESC) AS dense_rnk
FROM   products
WHERE  category = 'Electronics'
ORDER  BY price DESC;
product_namepricerow_numrnkdense_rnk
USB-C Hub1499111
Wireless Mouse899222
HDMI Cable299333

ROW_NUMBER: always unique (1,2,3). RANK: ties share rank, next rank skips (1,1,3). DENSE_RANK: ties share rank, no gap (1,1,2).

NULL Handling, CASE, Subqueries
Q17BasicReplace NULL discount values with 0 and show each customer's effective discount.
SELECT customer_name,
       COALESCE(discount_pct, 0) AS effective_discount
FROM   customers
ORDER  BY effective_discount DESC;
customer_nameeffective_discount
Sneha Gupta15
Amit Verma10
Rohan Mehta5
Priya Sharma0
Arjun Singh0
Q18BasicClassify each order as Small (< ₹500), Medium (₹500–₹1,999), or Large (≥ ₹2,000).
SELECT order_id, total_amount,
       CASE
         WHEN total_amount <  500  THEN 'Small'
         WHEN total_amount <  2000 THEN 'Medium'
         ELSE                           'Large'
       END AS order_size
FROM   orders
ORDER  BY total_amount;
order_idtotal_amountorder_size
1006299Small
1007490Small
1003495Small
1001899Medium
10021499Medium
10052398Large
10048999Large
Q19AdvancedFind products priced above the average price of their own category.
-- Correlated subquery approach
SELECT product_name, category, price
FROM   products AS p1
WHERE  price > (
  SELECT AVG(price)
  FROM   products AS p2
  WHERE  p2.category = p1.category
)
ORDER  BY category, price DESC;

-- Window function approach (more efficient)
WITH cat_avg AS (
  SELECT product_name, category, price,
         AVG(price) OVER (PARTITION BY category) AS avg_cat_price
  FROM   products
)
SELECT product_name, category, price, ROUND(avg_cat_price,2) AS cat_avg
FROM   cat_avg
WHERE  price > avg_cat_price;
product_namecategorypricecat_avg
USB-C HubElectronics1499899
Ergonomic ChairFurniture89995099
Notebook A5Stationery9974
Q20IntermediateWhat does NOT IN return when the subquery contains a NULL? How do you fix it?

NOT IN returns zero rows when the subquery contains any NULL. This is because x NOT IN (1, 2, NULL) evaluates to UNKNOWN (not TRUE) for every x — the comparison with NULL is always unknown.

-- ❌ Broken: if any email is NULL, returns 0 rows
SELECT customer_name FROM customers
WHERE  customer_id NOT IN (SELECT customer_id FROM orders);

-- ✅ Fix 1: filter NULLs in subquery
WHERE  customer_id NOT IN (
  SELECT customer_id FROM orders WHERE customer_id IS NOT NULL
);

-- ✅ Fix 2: use NOT EXISTS (always NULL-safe)
WHERE  NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
Advanced — CTEs, Performance, Schema Design
Q21AdvancedUsing a CTE, find the customer who has spent the most and the one who has spent the least.
WITH spend AS (
  SELECT customer_id,
         SUM(total_amount) AS total_spent
  FROM   orders
  GROUP  BY customer_id
)
SELECT 'Top spender'    AS label, customer_id, total_spent
FROM   spend WHERE total_spent = (SELECT MAX(total_spent) FROM spend)
UNION ALL
SELECT 'Lowest spender', customer_id, total_spent
FROM   spend WHERE total_spent = (SELECT MIN(total_spent) FROM spend);
labelcustomer_idtotal_spent
Top spenderC038999
Lowest spenderC05299
Q22IntermediateWrite a query to find duplicate rows — customers who share the same email address.
SELECT email, COUNT(*) AS occurrences
FROM   customers
WHERE  email IS NOT NULL
GROUP  BY email
HAVING COUNT(*) > 1;

Returns 0 rows in our clean dataset — but this exact pattern finds duplicates in real messy data.

Q23BasicExplain the difference between WHERE and HAVING. When must you use HAVING?

WHERE filters individual rows before grouping. HAVING filters groups after aggregation. You must use HAVING when the filter references an aggregate function (COUNT, SUM, AVG, etc.) because WHERE runs before the aggregate is calculated.

-- WHERE filters rows first, then GROUP BY aggregates
SELECT category, COUNT(*) AS cnt
FROM   products
WHERE  price > 100          -- filter rows before grouping
GROUP  BY category
HAVING COUNT(*) > 1;        -- filter groups after aggregating
categorycnt
Electronics2
Furniture2
Q24AdvancedWhat index would you create to speed up: SELECT order_id, total_amount FROM orders WHERE customer_id = 'C01' ORDER BY order_date DESC?

A composite covering index on (customer_id, order_date DESC, order_id, total_amount). Reasoning:

CREATE INDEX idx_orders_cust_date_cover
  ON orders (customer_id, order_date DESC, order_id, total_amount);

-- customer_id  → equality filter (most selective — goes first)
-- order_date   → ORDER BY column (included so sort is free)
-- order_id, total_amount → covering (all SELECT columns in index)
-- EXPLAIN Extra will show: "Using index" — zero table lookups
Q25BasicWhat is the difference between TRUNCATE, DELETE, and DROP?
DELETETRUNCATEDROP
Removes rows✅ Yes (with WHERE)✅ All rows✅ All rows + structure
Removes structure❌ No❌ No✅ Yes
Rollback possible✅ Yes (in transaction)❌ No (MySQL)❌ No
Resets AUTO_INCREMENT❌ No✅ Yes✅ Yes
Triggers fire✅ Yes❌ No❌ No
Speed on large tableSlow (row by row)Fast (deallocate pages)Fast
🎉
You have completed the SQL Tutorial!
40 chapters from SELECT to window functions, stored procedures, indexes, and performance. Ready to put it into practice with real projects?