Skip to main content
PySpark.inData Engineering
Tutorials
  • Python
  • SQL
  • PySpark
  • Machine Learning
  • NLP
  • Deep Learning
  • Linear Algebra
  • Data Engineering
  • All Tutorials
Challenge Arena Compiler Interview Questions Certifications Blogs Jobs Projects CV Builder
Menu
  • All Tutorials
  • Python
  • SQL
  • PySpark
  • Data Engineering
  • Learning Paths
  • Certificate Tracks
  • PySpark Compiler
  • Challenge Arena
  • Projects
  • Production Incidents
  • Boss Battles
  • Datasets
  • Interview Questions
  • Interview Mode
  • Company Prep
  • Certifications
  • DE Roadmap
  • Jobs
  • CV Builder
  • Blogs
  • About
  • Contact

We use cookies to run the site, remember your progress, and serve ads via Google AdSense. By continuing you agree to our Privacy Policy.

Explore

homeAll TutorialscodeLearn PythonanalyticsLearn PySparkterminalOnline Compileremoji_eventsChallenge ArenaarticleBlogsquizInterview QuestionsinfoAbout Uscontact_mailContact Us

Popular Topics

#python#pyspark#sql#spark#dataengineering#bigdata
Home›Interview Questions›SQL
🗄️ Interview Prep

SQL
Interview Questions

Window functions, CTEs, subqueries, GROUP BY pitfalls, indexing strategy, and query optimization.

Window FnCTEsIndexesSubqueriesOptimization
10Questions
FreeAlways
search
Vishal Taneja's profile picture
Vishal Taneja·
3w agoInterview Question
Q.1
Fetch all orders where the total_value is greater than the average order value.? Medium

 Input Table: Orders

order_idcustomer_idtotal_value
90115000
90227000
90336000
90448000

I use a subquery to calculate the average order value using AVG(). Then I use the result in the outer query to return orders whose total value is greater than that average.

🗄 query.sql 65 lines
1-- =========================================
2-- QUESTION 10
3-- Find Orders Where Total Order Value
4-- Exceeds the Average Order Value
5-- =========================================
6
7-- =========================================
8-- 1. Remove Existing Table
9-- =========================================
10
11DROP TABLE IF EXISTS Orders;
12
13-- =========================================
14-- 2. Create Orders Table
15-- =========================================
16
17CREATE TABLE Orders (
18 order_id INT,
19 customer_id INT,
20 total_value DECIMAL(10, 2)
21);
22
23-- =========================================
24-- 3. Insert Orders
25-- =========================================
26
27INSERT INTO Orders (
28 order_id,
29 customer_id,
30 total_value
31)
32VALUES
33 (901, 1, 5000),
34 (902, 2, 7000),
35 (903, 3, 6000),
36 (904, 4, 8000);
37
38-- =========================================
39-- 4. Select All Orders
40-- =========================================
41
42SELECT *
43FROM Orders;
44
45-- =========================================
46-- 5. Calculate Average Order Value
47-- =========================================
48
49SELECT
50 AVG(total_value) AS average_order_value
51FROM Orders;
52
53-- =========================================
54-- 6. Find Orders Above Average
55-- =========================================
56
57SELECT
58 order_id,
59 customer_id,
60 total_value
61FROM Orders
62WHERE total_value > (
63 SELECT AVG(total_value)
64 FROM Orders
65);
▶ Run to see output
✦ AI Explanation

Vishal Taneja's profile picture
Vishal Taneja·
3w agoInterview Question
Q.2
Find the most frequently sold product in each category.? Medium

Products

product_idcategoryproduct_name
601AApple
602ABanana
603BMilk
604BBread

Sales

sale_idproduct_idquantity
160110
26025
36018
460312
56044

Then we can calculate total quantity sold:

Apple  → 10 + 8 = 18
Banana → 5
Milk   → 12
Bread  → 4

Therefore:

Category A → Apple
Category B → Milk

SQL concept

The solution normally involves:

Products
   ↓
JOIN Sales
   ↓
GROUP BY category + product
   ↓
SUM(quantity) / COUNT(*)
   ↓
Rank products within each category
   ↓
Take rank = 1

🗄 query.sql 148 lines
1-- =========================================
2-- QUESTION 8
3-- Find the Most Frequently Sold Product
4-- in Each Category
5-- =========================================
6
7-- =========================================
8-- 1. Remove old tables if they exist
9-- =========================================
10
11DROP TABLE IF EXISTS ProductSales;
12DROP TABLE IF EXISTS Products;
13
14-- =========================================
15-- 2. Create Products Table
16-- =========================================
17
18CREATE TABLE Products (
19 product_id INT,
20 category VARCHAR(50),
21 product_name VARCHAR(100)
22);
23
24-- =========================================
25-- 3. Insert Products
26-- =========================================
27
28INSERT INTO Products (
29 product_id,
30 category,
31 product_name
32)
33VALUES
34 (601, 'A', 'Apple'),
35 (602, 'A', 'Banana'),
36 (603, 'A', 'Mango'),
37 (604, 'B', 'Milk'),
38 (605, 'B', 'Bread'),
39 (606, 'B', 'Butter');
40
41-- =========================================
42-- 4. Create ProductSales Table
43-- =========================================
44
45CREATE TABLE ProductSales (
46 sale_id INT,
47 product_id INT
48);
49
50-- =========================================
51-- 5. Insert Sales
52-- =========================================
53
54INSERT INTO ProductSales (
55 sale_id,
56 product_id
57)
58VALUES
59 (1, 601),
60 (2, 601),
61 (3, 601),
62 (4, 602),
63 (5, 602),
64 (6, 603),
65 (7, 604),
66 (8, 604),
67 (9, 604),
68 (10, 604),
69 (11, 605),
70 (12, 605),
71 (13, 606);
72
73-- =========================================
74-- 6. Check Products
75-- =========================================
76
77SELECT *
78FROM Products;
79
80-- =========================================
81-- 7. Check Product Sales
82-- =========================================
83
84SELECT *
85FROM ProductSales;
86
87-- =========================================
88-- 8. Count How Many Times Each Product
89-- Was Sold
90-- =========================================
91
92SELECT
93 p.category,
94 p.product_id,
95 p.product_name,
96 COUNT(ps.sale_id) AS times_sold
97FROM Products p
98JOIN ProductSales ps
99 ON p.product_id = ps.product_id
100GROUP BY
101 p.category,
102 p.product_id,
103 p.product_name
104ORDER BY
105 p.category,
106 times_sold DESC;
107
108-- =========================================
109-- 9. Find Most Frequently Sold Product
110-- in Each Category
111-- =========================================
112
113WITH product_sales AS (
114 SELECT
115 p.category,
116 p.product_id,
117 p.product_name,
118 COUNT(ps.sale_id) AS times_sold
119 FROM Products p
120 JOIN ProductSales ps
121 ON p.product_id = ps.product_id
122 GROUP BY
123 p.category,
124 p.product_id,
125 p.product_name
126),
127
128ranked_products AS (
129 SELECT
130 category,
131 product_id,
132 product_name,
133 times_sold,
134 ROW_NUMBER() OVER (
135 PARTITION BY category
136 ORDER BY times_sold DESC
137 ) AS rn
138 FROM product_sales
139)
140
141SELECT
142 category,
143 product_id,
144 product_name,
145 times_sold
146FROM ranked_products
147WHERE rn = 1
148ORDER BY category;
▶ Run to see output
✦ AI Explanation

pyspark's profile picture
pyspark·
3w agoInterview Question
Q.3
Find customers who have never placed an order.? Medium

The key concept here is a LEFT JOIN with IS NULL.

1. Customers Table

customer_idcustomer_name
1John
2Alice
3Bob

2. Orders Table

order_idcustomer_id
1011
1022

I use a LEFT JOIN between Customers and Orders on customer_id. The LEFT JOIN keeps all customers, including those without orders. Then I filter where the Orders customer_id is NULL to identify customers who have never placed an order.

🗄 query.sql 29 lines
1CREATE TABLE Customers (
2 customer_id INT,
3 customer_name VARCHAR(100)
4);
5INSERT INTO Customers (customer_id, customer_name)
6VALUES
7 (1, 'John'),
8 (2, 'Alice'),
9
10 (3, 'Bob');
11CREATE TABLE Orders (
12 order_id INT,
13 customer_id INT
14
15);
16INSERT INTO Orders (order_id, customer_id)
17VALUES
18 (101, 1),
19
20 (102, 2);
21
22SELECT
23 c.customer_id,
24 c.customer_name
25FROM Customers c
26LEFT JOIN Orders o
27 ON c.customer_id = o.customer_id
28
29WHERE o.customer_id IS NULL;
▶ Run to see output
✦ AI Explanation

pyspark's profile picture
pyspark·
3w agoInterview Question
Q.4
Find the second-highest salary from the Employees table without using LIMIT or TOP. Medium

Example Employees Table

Suppose we have:

emp_idemp_namesalary
101Alice95000
102Bob87000
103Charlie91000
104David75000
105Eve99000

I use a subquery to find the maximum salary, filter out that salary using the WHERE clause, and then use MAX() on the remaining salaries to get the second-highest salary.

🗄 query.sql 21 lines
1CREATE TABLE Employees (
2 emp_id INT,
3 emp_name VARCHAR(100),
4 salary DECIMAL(10, 2)
5);
6INSERT INTO Employees (emp_id, emp_name, salary)
7VALUES
8 (101, 'Alice', 95000),
9 (102, 'Bob', 87000),
10 (103, 'Charlie', 91000),
11 (104, 'David', 75000),
12
13 (105, 'Eve', 99000);
14
15SELECT MAX(salary) AS second_highest_salary
16FROM Employees
17WHERE salary < (
18 SELECT MAX(salary)
19 FROM Employees
20
21);
▶ Run to see output
✦ AI Explanation

pyspark's profile picture
pyspark·
3w agoInterview Question
Q.5
Calculate the average sales amount for each region. Medium

 Input Table: Sales

sales_idregionsales_amount
501North50000
502South70000
503North80000
504West90000

I group the sales records by region using GROUP BY, and then use the AVG() aggregate function to calculate the average sales amount for each region.

🗄 query.sql 19 lines
1CREATE TABLE Sales (
2 sales_id INT,
3 region VARCHAR(50),
4 sales_amount DECIMAL(10, 2)
5);
6INSERT INTO Sales (sales_id, region, sales_amount)
7VALUES
8 (501, 'North', 50000),
9 (502, 'South', 70000),
10 (503, 'North', 80000),
11
12 (504, 'West', 90000);
13
14SELECT
15 region,
16 AVG(sales_amount) AS avg_sales
17FROM Sales
18
19GROUP BY region;
▶ Run to see output
✦ AI Explanation

pyspark's profile picture
pyspark·
3w agoInterview Question
Q.6
Write a SQL query to fetch all orders that were placed on weekends (Saturday or Sunday).? Medium

Input table: Orders

order_idcustomer_idorder_date
40112024-02-17
40222024-02-18
40332024-02-19
40412024-02-24

Let's identify the days:

order_idorder_dateDayWeekend?
4012024-02-17Saturday✅
4022024-02-18Sunday✅
4032024-02-19Monday❌
4042024-02-24Saturday✅

I use the DAYOFWEEK() function to determine the weekday for each order date, and then filter for Sunday and Saturday using IN (1, 7).

🗄 query.sql 19 lines
1CREATE TABLE Orders (
2 order_id INT,
3 customer_id INT,
4 order_date DATE
5);
6INSERT INTO Orders (order_id, customer_id, order_date)
7VALUES
8 (401, 1, '2024-02-17'),
9 (402, 2, '2024-02-18'),
10 (403, 3, '2024-02-19'),
11
12 (404, 1, '2024-02-24');
13
14SELECT
15 order_id,
16 customer_id,
17 order_date
18FROM Orders
19WHERE DAYOFWEEK(order_date) IN (1, 7);
▶ Run to see output
✦ AI Explanation

pyspark's profile picture
pyspark·
3w agoInterview Question
Q.7
Write a query to retrieve the first and last purchase date for each customer.? Medium

​Input Table: Transactions

transaction_idcustomer_idpurchase_date
30112024-01-10
30222024-01-12
30312024-02-15
30422024-02-20
30512024-03-05

🗄 query.sql 22 lines
1CREATE TABLE Transactions (
2 transaction_id INT,
3 customer_id INT,
4 purchase_date DATE
5);
6INSERT INTO Transactions
7 (transaction_id, customer_id, purchase_date)
8VALUES
9 (301, 1, '2024-01-10'),
10 (302, 2, '2024-01-12'),
11 (303, 1, '2024-02-15'),
12 (304, 2, '2024-02-20'),
13
14 (305, 1, '2024-03-05');
15
16SELECT
17 customer_id,
18 MIN(purchase_date) AS first_purchase,
19 MAX(purchase_date) AS last_purchase
20FROM Transactions
21
22GROUP BY customer_id;
▶ Run to see output
✦ AI Explanation

pyspark's profile picture
pyspark·
3w agoInterview Question
Q.8
Find customers who have placed more than 5 orders in the last 30 days.? Medium

Input Table: Orders

order_idcustomer_idorder_date
20112024-02-15
20222024-02-10
20312024-02-18
20432024-02-20
20512024-02-25
20622024-02-27
20712024-03-02

🗄 query.sql 22 lines
1CREATE TABLE Orders (
2 order_id INT,
3 customer_id INT,
4 order_date DATE
5);
6INSERT INTO Orders (order_id, customer_id, order_date)
7VALUES
8 (201, 1, '2024-02-15'),
9 (202, 2, '2024-02-10'),
10 (203, 1, '2024-02-18'),
11 (204, 3, '2024-02-20'),
12 (205, 1, '2024-02-25'),
13 (206, 2, '2024-02-27'),
14
15 (207, 1, '2024-03-02');
16
17SELECT customer_id,
18 COUNT(order_id) AS order_count
19FROM Orders
20WHERE order_date >= CURRENT_DATE - INTERVAL 30 DAY
21GROUP BY customer_id
22HAVING COUNT(order_id) > 5;
▶ Run to see output
✦ AI Explanation

pyspark's profile picture
pyspark·
3w agoInterview Question
Q.9
Write a query to fetch the top 3 employees with the highest salaries from an Employees table.?(Asked in Accenture) Easy

Fetch the Top 3 Employees with the Highest Salaries

Input Table: Employees

emp_idemp_namesalary
101Alice95000
102Bob87000
103Charlie91000
104David75000
105Eve99000

🗄 query.sql 16 lines
1CREATE TABLE Employees (
2 emp_id INT,
3 emp_name VARCHAR(100),
4 salary DECIMAL(10, 2)
5);
6INSERT INTO Employees (emp_id, emp_name, salary)
7VALUES
8 (101, 'Alice', 95000),
9 (102, 'Bob', 87000),
10 (103, 'Charlie', 91000),
11 (104, 'David', 75000),
12
13 (105, 'Eve', 99000);
14SELECT emp_id, emp_name, salary
15
16FROM Employees;
▶ Run to see output
✦ AI Explanation

Vishal Taneja's profile picture
Vishal Taneja·
Sep 14, 2026Interview Question
Q.10
A SQL query that normally takes 2 minutes is now taking 20 minutes. What will you do? Medium

1. Check the execution plan

First, I would check the query's execution plan.

The execution plan tells us how the database is actually executing the query.

For example:

Query
  ↓
Execution Plan
  ↓
Table Scan?
Index Scan?
Join?
Sort?
Aggregation?

I want to find the expensive operation.


2. Compare old vs new execution plan

This is very important.

The query used to take:

2 minutes ✅

Now:

20 minutes ❌

So I would compare:

Previous execution plan
          VS
Current execution plan

Maybe previously:

Index Scan
    ↓
100K rows

Now:

Full Table Scan
    ↓
100 Million rows

That immediately gives us a direction.


3. Check whether data volume increased

Maybe the query itself didn't change.

The data may simply have grown.

For example:

Last month:
10 million rows
     ↓
2 minutes

Now:

100 million rows
     ↓
20 minutes

So I would check:

  • Table size
  • Number of rows
  • Recent data growth
  • Historical data volume

4. Look for full table scans

Suppose the query is:

SELECT *
FROM transactions
WHERE customer_id = 1001;

If the database scans the entire table:

100 million rows
       ↓
Scan everything
       ↓
Find customer 1001

that's potentially expensive.

An appropriate index or partitioning strategy might allow the database to access only the required data.


5. Check joins and join cardinality

This is another common reason for slow queries.

Suppose:

transactions
      JOIN
customers

You should check:

  • Join keys
  • Number of rows on each side
  • Whether the join unexpectedly produces many rows
  • Whether the join condition is correct
  • Whether a many-to-many join was accidentally created

For example:

Table A = 1 million rows
Table B = 1 million rows

An incorrect join can produce a huge intermediate result.

1M × 1M
    ↓
Very large result
    ↓
Query becomes slow

6. Check indexes or partition pruning

For traditional relational databases, check whether the expected indexes are being used.

For large data-lake systems such as Spark/Databricks, think about partition pruning and file/data skipping rather than traditional database indexes.

For example:

Transactions
├── 2026-09-10
├── 2026-09-11
├── 2026-09-12
├── 2026-09-13
└── 2026-09-14

If the query asks:

WHERE transaction_date = '2026-09-14'

we ideally want:

Read only Sept 14
       ↓
Avoid historical data

This is partition pruning.


7. Check functions on indexed columns

Consider:

WHERE YEAR(transaction_date) = 2026

Depending on the database and indexing strategy, applying a function to the column can prevent efficient use of an index.

Often, a range predicate is better:

WHERE transaction_date >= '2026-01-01'
  AND transaction_date < '2027-01-01'

The exact behavior depends on the database optimizer, but this is a useful thing to investigate.


8. Check unnecessary columns

Suppose someone uses:

SELECT *
FROM transactions;

when they only need:

SELECT transaction_id, customer_id, amount
FROM transactions;

Selecting unnecessary columns can increase:

I/O
 ↓
Memory
 ↓
Network transfer
 ↓
Processing time

So I would select only the required columns.


9. Check statistics

Database optimizers use statistics to choose execution plans.

For example:

Old statistics
      ↓
Good execution plan
      ↓
2 minutes

But if statistics become stale:

Stale statistics
      ↓
Bad cardinality estimate
      ↓
Bad execution plan
      ↓
20 minutes

So I would check whether statistics need to be refreshed.


10. Check recent deployments

Because the query suddenly became slow, I would ask:

“Was there any recent code or database change?”

Check:

  • SQL changes
  • New joins
  • New filters
  • Removed filters
  • Schema changes
  • Index changes
  • Partition changes
  • Configuration changes

For example:

Before deployment
      ↓
2 minutes ✅

Deployment
      ↓
Query changed
      ↓
20 minutes ❌

This can quickly identify the root cause.


11. For Spark / Databricks

Since you're preparing for Data Engineer interviews, this is especially important.

For Spark, I would additionally check:

Spark UI
   ↓
Stages
   ↓
Tasks
   ↓
Shuffle
   ↓
Partition sizes

Look for:

Large shuffle

Data
 ↓
Shuffle
 ↓
Huge amount of data
 ↓
Slow

Data skew

Partition 1 → 500 MB
Partition 2 → 400 MB
Partition 3 → 450 MB
Partition 4 → 40 GB ❌

One task takes much longer than the others.

Too many small files

Millions of tiny files
        ↓
Large file-listing/metadata overhead
        ↓
Slow job

Missing partition pruning

Query needs 1 day
      ↓
Scans 5 years ❌

I wouldn't immediately rewrite the query. First, I would investigate systematically. I would check the current execution plan and compare it with the previous plan to identify what changed. Then I would check data volume, full table scans, joins and join cardinality, indexes or partition pruning, functions applied to filter columns, unnecessary columns, and database statistics. I would also check whether a recent deployment or schema change affected the query. If this is a Spark/Databricks workload, I would additionally check Spark UI for expensive stages, shuffle, data skew, partition sizes and small-file issues. Once I identify the bottleneck, I would apply the appropriate optimization and validate the improvement.

PySpark.inData Engineering

A learning and career platform for Data Engineering — structured tutorials, a browser-based PySpark compiler, coding challenges, interview preparation and certifications.

Learn

  • Python
  • SQL
  • PySpark
  • Machine Learning
  • NLP
  • Deep Learning
  • Linear Algebra
  • Data Engineering
  • All Tutorials

Practise

  • PySpark Compiler
  • Challenge Arena
  • Challenges by Topic
  • Dataset Library
  • Interview Questions

Career

  • Certifications
  • CV Builder
  • Jobs

Resources

  • Blogs
  • Projects
  • Certificate Tracks

Company

  • About
  • Contact
  • Terms
  • Privacy Policy

Stay ahead in Data Engineering

Weekly tutorials, PySpark tips, SQL challenges and interview questions.

© 2026 PySpark.in. All rights reserved.

TermsPrivacyCookies