๐ง SQL Interview Question (ModerateโTricky & Top Performer Analysis)
๐
sales(region, salesperson_id, revenue)
โ Ques :
๐ Find the top 2 highest revenue-generating salespersons in each region.
๐งฉ How Interviewers Expect You to Think
โข Data is grouped by region ๐
โข Need ranking within each group
โข Handle ties carefully (RANK / DENSE_RANK)
โข Filter top N per group
๐ก SQL Solution
SELECT region, salesperson_id, revenue
FROM (
SELECT
region,
salesperson_id,
revenue,
DENSE_RANK() OVER (PARTITION BY region ORDER BY revenue DESC) AS rnk
FROM sales
) t
WHERE rnk <= 2;
๐ฅ Why This Question Is Powerful
โข Tests window functions (RANK / DENSE_RANK) ๐ง
โข Very common in business reporting & leaderboards ๐
โข Checks understanding of partitioning + ordering logic
โค๏ธ React if you want more such real interview-level SQL questions ๐
๐
sales(region, salesperson_id, revenue)
โ Ques :
๐ Find the top 2 highest revenue-generating salespersons in each region.
๐งฉ How Interviewers Expect You to Think
โข Data is grouped by region ๐
โข Need ranking within each group
โข Handle ties carefully (RANK / DENSE_RANK)
โข Filter top N per group
๐ก SQL Solution
SELECT region, salesperson_id, revenue
FROM (
SELECT
region,
salesperson_id,
revenue,
DENSE_RANK() OVER (PARTITION BY region ORDER BY revenue DESC) AS rnk
FROM sales
) t
WHERE rnk <= 2;
๐ฅ Why This Question Is Powerful
โข Tests window functions (RANK / DENSE_RANK) ๐ง
โข Very common in business reporting & leaderboards ๐
โข Checks understanding of partitioning + ordering logic
โค๏ธ React if you want more such real interview-level SQL questions ๐
โค5๐2
๐ง๐ผ๐ฝ ๐๐ฒ๐ฟ๐๐ถ๐ณ๐ถ๐ฐ๐ฎ๐๐ถ๐ผ๐ป๐ ๐ง๐ผ ๐๐ฒ๐ ๐๐ถ๐ด๐ต ๐ฃ๐ฎ๐๐ถ๐ป๐ด ๐๐ผ๐ฏ ๐๐ป ๐ฎ๐ฌ๐ฎ๐ฒ๐
๐ 2000+ Students Placed
๐ค 500+ Hiring Partners
๐ผ Avg. Rs. 7.4 LPA
๐ 41 LPA Highest Package
Fullstack :- https://pdlink.in/4hO7rWY
Data Analytics :- https://pdlink.in/4fdWxJB
๐ Start learning today, build job-ready skills, and get placed in leading tech companies.
๐ 2000+ Students Placed
๐ค 500+ Hiring Partners
๐ผ Avg. Rs. 7.4 LPA
๐ 41 LPA Highest Package
Fullstack :- https://pdlink.in/4hO7rWY
Data Analytics :- https://pdlink.in/4fdWxJB
๐ Start learning today, build job-ready skills, and get placed in leading tech companies.
๐ง SQL Interview Question (ModerateโTricky & Duplicate Detection + Latest Record)
๐
employees(emp_id, email, updated_at)
โ Ques :
๐ Find duplicate emails, but return only the latest record for each duplicate email.
๐งฉ How Interviewers Expect You to Think
โข Identify duplicates using COUNT() ๐
โข Use window functions for ranking
โข Partition by email
โข Order by latest timestamp
โข Filter only duplicates + latest row
๐ก SQL Solution
SELECT emp_id, email, updated_at
FROM (
SELECT
emp_id,
email,
updated_at,
COUNT(*) OVER (PARTITION BY email) AS cnt,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY updated_at DESC
) AS rn
FROM employees
) t
WHERE cnt > 1
AND rn = 1;
๐ฅ Why This Question Is Powerful
โข Tests window functions (COUNT OVER, ROW_NUMBER) ๐ง
โข Combines deduplication + ranking logic
โข Very common in data cleaning scenarios ๐งน
โข Real-world use case: keeping latest user records
โค๏ธ React if you want more such real interview-level SQL questions ๐
๐
employees(emp_id, email, updated_at)
โ Ques :
๐ Find duplicate emails, but return only the latest record for each duplicate email.
๐งฉ How Interviewers Expect You to Think
โข Identify duplicates using COUNT() ๐
โข Use window functions for ranking
โข Partition by email
โข Order by latest timestamp
โข Filter only duplicates + latest row
๐ก SQL Solution
SELECT emp_id, email, updated_at
FROM (
SELECT
emp_id,
email,
updated_at,
COUNT(*) OVER (PARTITION BY email) AS cnt,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY updated_at DESC
) AS rn
FROM employees
) t
WHERE cnt > 1
AND rn = 1;
๐ฅ Why This Question Is Powerful
โข Tests window functions (COUNT OVER, ROW_NUMBER) ๐ง
โข Combines deduplication + ranking logic
โข Very common in data cleaning scenarios ๐งน
โข Real-world use case: keeping latest user records
โค๏ธ React if you want more such real interview-level SQL questions ๐
โค5
๐๐ฎ๐๐ฎ ๐ฆ๐ฐ๐ถ๐ฒ๐ป๐ฐ๐ฒ ๐๐ฅ๐๐ ๐ข๐ป๐น๐ถ๐ป๐ฒ ๐ ๐ฎ๐๐๐ฒ๐ฟ๐ฐ๐น๐ฎ๐๐๐
Kickstart Your Data Science Career In Top Tech Companies
๐ซLearn Tools, Skills & Mindset to Land your first Job
๐ซJoin this free Masterclass for an expert-led session on Data Science
Eligibility :- Students ,Freshers & Working Professionals
๐ฅ๐ฒ๐ด๐ถ๐๐๐ฒ๐ฟ ๐๐ผ๐ฟ ๐๐ฅ๐๐๐ :-
https://pdlink.in/4dLRDo6
( Limited Slots ..Hurry Up๐โโ๏ธ )
Date & Time :- 26th March 2026 , 7:00 PM
Kickstart Your Data Science Career In Top Tech Companies
๐ซLearn Tools, Skills & Mindset to Land your first Job
๐ซJoin this free Masterclass for an expert-led session on Data Science
Eligibility :- Students ,Freshers & Working Professionals
๐ฅ๐ฒ๐ด๐ถ๐๐๐ฒ๐ฟ ๐๐ผ๐ฟ ๐๐ฅ๐๐๐ :-
https://pdlink.in/4dLRDo6
( Limited Slots ..Hurry Up๐โโ๏ธ )
Date & Time :- 26th March 2026 , 7:00 PM
โค1
๐ข ๐๐ฒ๐ฟ๐๐ถ๐ณ๐ถ๐ฐ๐ฎ๐๐ถ๐ผ๐ป ๐๐น๐ฒ๐ฟ๐ โ ๐๐ฎ๐๐ฎ ๐๐ป๐ฎ๐น๐๐๐ถ๐ฐ๐ ๐๐ถ๐๐ต ๐๐
(No Coding Background Required)
Freshers are getting paid 10 - 15 Lakhs by learning Data Analytics WIth AI skill
๐ Learn Data Analytics from Scratch
๐ซ AI Tools & Automation
๐ Build real world Projects for job ready portfolio
๐ E&ICT IIT Roorkee Certification Program
๐ฅDeadline :- 29th March
๐๐ฝ๐ฝ๐น๐ ๐ก๐ผ๐๐ :-
https://pdlink.in/41f0Vlr
Don't Miss This Opportunity. Get Placement Assistance With 5000+ Companies
(No Coding Background Required)
Freshers are getting paid 10 - 15 Lakhs by learning Data Analytics WIth AI skill
๐ Learn Data Analytics from Scratch
๐ซ AI Tools & Automation
๐ Build real world Projects for job ready portfolio
๐ E&ICT IIT Roorkee Certification Program
๐ฅDeadline :- 29th March
๐๐ฝ๐ฝ๐น๐ ๐ก๐ผ๐๐ :-
https://pdlink.in/41f0Vlr
Don't Miss This Opportunity. Get Placement Assistance With 5000+ Companies
Key Power BI Functions Every Analyst Should Master
DAX Functions:
1. CALCULATE():
Purpose: Modify context or filter data for calculations.
Example: CALCULATE(SUM(Sales[Amount]), Sales[Region] = "East")
2. SUM():
Purpose: Adds up column values.
Example: SUM(Sales[Amount])
3. AVERAGE():
Purpose: Calculates the mean of column values.
Example: AVERAGE(Sales[Amount])
4. RELATED():
Purpose: Fetch values from a related table.
Example: RELATED(Customers[Name])
5. FILTER():
Purpose: Create a subset of data for calculations.
Example: FILTER(Sales, Sales[Amount] > 100)
6. IF():
Purpose: Apply conditional logic.
Example: IF(Sales[Amount] > 1000, "High", "Low")
7. ALL():
Purpose: Removes filters to calculate totals.
Example: ALL(Sales[Region])
8. DISTINCT():
Purpose: Return unique values in a column.
Example: DISTINCT(Sales[Product])
9. RANKX():
Purpose: Rank values in a column.
Example: RANKX(ALL(Sales[Region]), SUM(Sales[Amount]))
10. FORMAT():
Purpose: Format numbers or dates as text.
Example: FORMAT(TODAY(), "MM/DD/YYYY")
You can refer these Power BI Interview Resources to learn more: https://whatsapp.com/channel/0029VaGgzAk72WTmQFERKh02
Like this post if you want me to continue this Power BI series ๐โฅ๏ธ
Share with credits: https://t.me/sqlspecialist
Hope it helps :)
DAX Functions:
1. CALCULATE():
Purpose: Modify context or filter data for calculations.
Example: CALCULATE(SUM(Sales[Amount]), Sales[Region] = "East")
2. SUM():
Purpose: Adds up column values.
Example: SUM(Sales[Amount])
3. AVERAGE():
Purpose: Calculates the mean of column values.
Example: AVERAGE(Sales[Amount])
4. RELATED():
Purpose: Fetch values from a related table.
Example: RELATED(Customers[Name])
5. FILTER():
Purpose: Create a subset of data for calculations.
Example: FILTER(Sales, Sales[Amount] > 100)
6. IF():
Purpose: Apply conditional logic.
Example: IF(Sales[Amount] > 1000, "High", "Low")
7. ALL():
Purpose: Removes filters to calculate totals.
Example: ALL(Sales[Region])
8. DISTINCT():
Purpose: Return unique values in a column.
Example: DISTINCT(Sales[Product])
9. RANKX():
Purpose: Rank values in a column.
Example: RANKX(ALL(Sales[Region]), SUM(Sales[Amount]))
10. FORMAT():
Purpose: Format numbers or dates as text.
Example: FORMAT(TODAY(), "MM/DD/YYYY")
You can refer these Power BI Interview Resources to learn more: https://whatsapp.com/channel/0029VaGgzAk72WTmQFERKh02
Like this post if you want me to continue this Power BI series ๐โฅ๏ธ
Share with credits: https://t.me/sqlspecialist
Hope it helps :)
โค5
๐ ๐ช๐ฎ๐ป๐ ๐๐ผ ๐๐๐ฎ๐ป๐ฑ ๐ผ๐๐ ๐ถ๐ป ๐ฝ๐น๐ฎ๐ฐ๐ฒ๐บ๐ฒ๐ป๐๐ ?
Join our FREE live masterclasses and learn the skills recruiters actually look for.
- Excel for real business use
- Strategies to crack placements in 2026
- Prompt engineering for top jobs
๐ Live expert sessions | Limited seats
๐ฅ๐ฒ๐ด๐ถ๐๐๐ฒ๐ฟ ๐๐ผ๐ฟ ๐๐ฅ๐๐๐ :-
https://pdlink.in/47pYJLl
Date & Time :- 27th March 2026 , 6:00 PM
Join our FREE live masterclasses and learn the skills recruiters actually look for.
- Excel for real business use
- Strategies to crack placements in 2026
- Prompt engineering for top jobs
๐ Live expert sessions | Limited seats
๐ฅ๐ฒ๐ด๐ถ๐๐๐ฒ๐ฟ ๐๐ผ๐ฟ ๐๐ฅ๐๐๐ :-
https://pdlink.in/47pYJLl
Date & Time :- 27th March 2026 , 6:00 PM
โ
How to Grow Fast in Data Analytics ๐๐ผ
1๏ธโฃ Master Core Tools
- Excel: Pivot tables, lookups, charts
- SQL: Joins, aggregations, subqueries
- Power BI / Tableau: Dashboards, filters, visuals
- Python: pandas, matplotlib, seaborn for deeper analysis
2๏ธโฃ Learn Key Concepts
- Descriptive stats: mean, median, variance
- Data cleaning: missing values, outliers
- Visualization best practices
- Business KPIs and metrics (e.g., churn rate, CAC, ROI)
3๏ธโฃ Build Practical Projects
- Sales dashboard in Power BI
- SQL analysis of e-commerce data
- Python analysis of COVID-19 trends
- Excel-based budget tracker
4๏ธโฃ Share Your Work
- Post dashboards on LinkedIn
- Upload projects to GitHub
- Record quick YouTube explainers
5๏ธโฃ Join the Community
- LinkedIn groups, Reddit (r/dataisbeautiful), Kaggle
- Attend webinars, local meetups, analytics bootcamps
6๏ธโฃ Stay Current
- Follow Google Analytics, Microsoft BI, Mode
- Subscribe to newsletters: Data Elixir, Analytics Vidhya
- Learn new tools: Looker, BigQuery, Power Query
๐ฏ Practice daily. Improve weekly. Share monthly.
๐ฌ Tap โค๏ธ if this helped you!
1๏ธโฃ Master Core Tools
- Excel: Pivot tables, lookups, charts
- SQL: Joins, aggregations, subqueries
- Power BI / Tableau: Dashboards, filters, visuals
- Python: pandas, matplotlib, seaborn for deeper analysis
2๏ธโฃ Learn Key Concepts
- Descriptive stats: mean, median, variance
- Data cleaning: missing values, outliers
- Visualization best practices
- Business KPIs and metrics (e.g., churn rate, CAC, ROI)
3๏ธโฃ Build Practical Projects
- Sales dashboard in Power BI
- SQL analysis of e-commerce data
- Python analysis of COVID-19 trends
- Excel-based budget tracker
4๏ธโฃ Share Your Work
- Post dashboards on LinkedIn
- Upload projects to GitHub
- Record quick YouTube explainers
5๏ธโฃ Join the Community
- LinkedIn groups, Reddit (r/dataisbeautiful), Kaggle
- Attend webinars, local meetups, analytics bootcamps
6๏ธโฃ Stay Current
- Follow Google Analytics, Microsoft BI, Mode
- Subscribe to newsletters: Data Elixir, Analytics Vidhya
- Learn new tools: Looker, BigQuery, Power Query
๐ฏ Practice daily. Improve weekly. Share monthly.
๐ฌ Tap โค๏ธ if this helped you!
โค6
๐ฃ๐ฎ๐ ๐๐ณ๐๐ฒ๐ฟ ๐ฃ๐น๐ฎ๐ฐ๐ฒ๐บ๐ฒ๐ป๐ - ๐๐ฒ๐ฎ๐ฟ๐ป ๐๐ผ๐ฑ๐ถ๐ป๐ด ๐๐ฟ๐ผ๐บ ๐๐๐ง ๐๐น๐๐บ๐ป๐ถ๐ฅ
๐ป Learn Frontend + Backend from scratch
๐ Build Real Projects (Portfolio Ready)
๐ 2000+ Students Placed
๐ค 500+ Hiring Partners
๐ผ Avg. Rs. 7.4 LPA
๐ 41 LPA Highest Package
๐ Skills = Opportunities = High Salary
๐๐ฝ๐ฝ๐น๐ ๐ก๐ผ๐๐:-
https://pdlink.in/4hO7rWY
๐ฅ Stop scrolling. Start building yourTech career
๐ป Learn Frontend + Backend from scratch
๐ Build Real Projects (Portfolio Ready)
๐ 2000+ Students Placed
๐ค 500+ Hiring Partners
๐ผ Avg. Rs. 7.4 LPA
๐ 41 LPA Highest Package
๐ Skills = Opportunities = High Salary
๐๐ฝ๐ฝ๐น๐ ๐ก๐ผ๐๐:-
https://pdlink.in/4hO7rWY
๐ฅ Stop scrolling. Start building yourTech career
โค1
๐ง SQL Interview Question (Self Join + Salary Comparison)
๐
employees(emp_id, manager_id, salary)
โ Ques :
๐ Find employees whose salary is higher than their managerโs salary.
๐งฉ How Interviewers Expect You to Think
โข Understand hierarchical relationships ๐ฅ
โข Use self join on same table
โข Compare values across related rows
โข Handle NULL manager cases
๐ก SQL Solution
SELECT
e.emp_id,
e.salary AS emp_salary,
m.salary AS manager_salary
FROM employees e
JOIN employees m
ON e.manager_id = m.emp_id
WHERE e.salary > m.salary;
๐ฅ Why This Question Is Powerful
โข Tests self join concept deeply ๐ง
โข Real-world scenario in org hierarchy analysis
โข Checks ability to compare across rows
โข Frequently asked in interviews
โค๏ธ React if you want more real interview-level SQL questions ๐
๐
employees(emp_id, manager_id, salary)
โ Ques :
๐ Find employees whose salary is higher than their managerโs salary.
๐งฉ How Interviewers Expect You to Think
โข Understand hierarchical relationships ๐ฅ
โข Use self join on same table
โข Compare values across related rows
โข Handle NULL manager cases
๐ก SQL Solution
SELECT
e.emp_id,
e.salary AS emp_salary,
m.salary AS manager_salary
FROM employees e
JOIN employees m
ON e.manager_id = m.emp_id
WHERE e.salary > m.salary;
๐ฅ Why This Question Is Powerful
โข Tests self join concept deeply ๐ง
โข Real-world scenario in org hierarchy analysis
โข Checks ability to compare across rows
โข Frequently asked in interviews
โค๏ธ React if you want more real interview-level SQL questions ๐
โค2๐2
Learn Ai in 2026 โAbsolutely FREE!๐
๐ธ Cost: ~โน10,000~ โน0 (FREE!)
What youโll learn:
โ 25+ Powerful AI Tools
โ Crack Interviews with Ai
โ Build Websites in seconds
โ Make Videos PPT
Enroll Now (free): https://tinyurl.com/Free-Ai-Course-a
โ ๏ธ Register Get Ai Certificate for resume
๐ธ Cost: ~โน10,000~ โน0 (FREE!)
What youโll learn:
โ 25+ Powerful AI Tools
โ Crack Interviews with Ai
โ Build Websites in seconds
โ Make Videos PPT
Enroll Now (free): https://tinyurl.com/Free-Ai-Course-a
โ ๏ธ Register Get Ai Certificate for resume
โค2
Data Analyst Interview Preparation Roadmap โ
Technical skills to revise
- SQL
Write queries from scratch.
Practice joins, group by, subqueries.
Handle duplicates and NULLs.
Window functions basics.
- Excel
Pivot tables without help.
XLOOKUP and IF confidently.
Data cleaning steps.
- Power BI or Tableau
Explain data model.
Write basic DAX.
Explain one dashboard end to end.
- Statistics
Mean vs median.
Standard deviation meaning.
Correlation vs causation.
- Python. If required
Pandas basics.
Groupby and filtering.
Interview question types
- SQL questions
Top N per group.
Running totals.
Duplicate records.
Date based queries.
- Business case questions
Why did sales drop.
Which metric matters most and why.
- Dashboard questions
Explain one KPI.
How users will use this report.
- Project questions
Data source.
Cleaning logic.
Key insight.
Business action.
Resume preparation
- Must have Tools section.
- One strong project.
- Metrics driven points.
Example: Improved reporting time by 30 percent using Power BI.
Mock interviews
- Practice explaining out loud.
- Time your answers.
- Use real datasets.
Daily prep plan
1 SQL problem.
1 dashboard review.
10 interview questions.
- Common mistakes
Memorizing queries.
No project explanation.
Weak business reasoning.
- Final task
- Prepare one project story.
- Prepare one SQL solution on paper.
- Prepare one business metric explanation.
Double Tap โฅ๏ธ For More
Technical skills to revise
- SQL
Write queries from scratch.
Practice joins, group by, subqueries.
Handle duplicates and NULLs.
Window functions basics.
- Excel
Pivot tables without help.
XLOOKUP and IF confidently.
Data cleaning steps.
- Power BI or Tableau
Explain data model.
Write basic DAX.
Explain one dashboard end to end.
- Statistics
Mean vs median.
Standard deviation meaning.
Correlation vs causation.
- Python. If required
Pandas basics.
Groupby and filtering.
Interview question types
- SQL questions
Top N per group.
Running totals.
Duplicate records.
Date based queries.
- Business case questions
Why did sales drop.
Which metric matters most and why.
- Dashboard questions
Explain one KPI.
How users will use this report.
- Project questions
Data source.
Cleaning logic.
Key insight.
Business action.
Resume preparation
- Must have Tools section.
- One strong project.
- Metrics driven points.
Example: Improved reporting time by 30 percent using Power BI.
Mock interviews
- Practice explaining out loud.
- Time your answers.
- Use real datasets.
Daily prep plan
1 SQL problem.
1 dashboard review.
10 interview questions.
- Common mistakes
Memorizing queries.
No project explanation.
Weak business reasoning.
- Final task
- Prepare one project story.
- Prepare one SQL solution on paper.
- Prepare one business metric explanation.
Double Tap โฅ๏ธ For More
โค3
๐ง SQL Interview Question (Products Frequently Bought Together)
๐
order_items(order_id, product_id)
โ Ques :
๐ Find pairs of products that are frequently bought together in the same order
๐ Return product_id_1, product_id_2, pair_count
๐งฉ How Interviewers Expect You to Think
โข Self-join on same order ๐
โข Avoid duplicate/reverse pairs
โข Count frequency of each pair
๐ก SQL Solution
SELECT
o1.product_id AS product_id_1,
o2.product_id AS product_id_2,
COUNT(*) AS pair_count
FROM order_items o1
JOIN order_items o2
ON o1.order_id = o2.order_id
AND o1.product_id < o2.product_id
GROUP BY
o1.product_id,
o2.product_id
ORDER BY pair_count DESC;
๐ฅ Why This Question Is Powerful
โข Classic market basket analysis ๐ง
โข Tests self-join + combinations logic
โข Frequently asked in e-commerce & analytics roles
โค๏ธ React for more SQL interview questions ๐
๐
order_items(order_id, product_id)
โ Ques :
๐ Find pairs of products that are frequently bought together in the same order
๐ Return product_id_1, product_id_2, pair_count
๐งฉ How Interviewers Expect You to Think
โข Self-join on same order ๐
โข Avoid duplicate/reverse pairs
โข Count frequency of each pair
๐ก SQL Solution
SELECT
o1.product_id AS product_id_1,
o2.product_id AS product_id_2,
COUNT(*) AS pair_count
FROM order_items o1
JOIN order_items o2
ON o1.order_id = o2.order_id
AND o1.product_id < o2.product_id
GROUP BY
o1.product_id,
o2.product_id
ORDER BY pair_count DESC;
๐ฅ Why This Question Is Powerful
โข Classic market basket analysis ๐ง
โข Tests self-join + combinations logic
โข Frequently asked in e-commerce & analytics roles
โค๏ธ React for more SQL interview questions ๐
โค5
๐ข Advertising in this channel
You can place an ad via Telegaโคio. It takes just a few minutes.
Formats and current rates: View details
You can place an ad via Telegaโคio. It takes just a few minutes.
Formats and current rates: View details
๐ฅ Top SQL Interview Questions with Answers
๐ฏ 1๏ธโฃ Find 2nd Highest Salary
๐ Table: employees
id | name | salary
1 | Rahul | 50000
2 | Priya | 70000
3 | Amit | 60000
4 | Neha | 70000
โ Problem Statement: Find the second highest distinct salary from the employees table.
โ Solution
SELECT MAX(salary) FROM employees WHERE salary < ( SELECT MAX(salary) FROM employees );
๐ฏ 2๏ธโฃ Find Nth Highest Salary
๐ Table: employees
id | name | salary
1 | A | 100
2 | B | 200
3 | C | 300
4 | D | 200
โ Problem Statement: Write a query to find the 3rd highest salary.
โ Solution
SELECT salary FROM ( SELECT salary, DENSE_RANK() OVER(ORDER BY salary DESC) r FROM employees ) t WHERE r = 3;
๐ฏ 3๏ธโฃ Find Duplicate Records
๐ Table: employees
id | name
1 | Rahul
2 | Amit
3 | Rahul
4 | Neha
โ Problem Statement: Find all duplicate names in the employees table.
โ Solution
SELECT name, COUNT(*) FROM employees GROUP BY name HAVING COUNT(*) > 1;
๐ฏ 4๏ธโฃ Customers with No Orders
๐ Table: customers
customer_id | name
1 | Rahul
2 | Priya
3 | Amit
๐ Table: orders
order_id | customer_id
101 | 1
102 | 2
โ Problem Statement: Find customers who have not placed any orders.
โ Solution
SELECT c.name FROM customers c LEFT JOIN orders o ON c.customer_id = o.customer_id WHERE o.customer_id IS NULL;
๐ฏ 5๏ธโฃ Top 3 Salaries per Department
๐ Table: employees
name | department | salary
A | IT | 100
B | IT | 200
C | IT | 150
D | HR | 120
E | HR | 180
โ Problem Statement: Find the top 3 highest salaries in each department.
โ Solution
SELECT * FROM ( SELECT name, department, salary, ROW_NUMBER() OVER( PARTITION BY department ORDER BY salary DESC ) r FROM employees ) t WHERE r <= 3;
๐ฏ 6๏ธโฃ Running Total of Sales
๐ Table: sales
date | sales
2024-01-01 | 100
2024-01-02 | 200
2024-01-03 | 300
โ Problem Statement: Calculate the running total of sales by date.
โ Solution
SELECT date, sales, SUM(sales) OVER(ORDER BY date) AS running_total FROM sales;
๐ฏ 7๏ธโฃ Employees Above Average Salary
๐ Table: employees
name | salary
A | 100
B | 200
C | 300
โ Problem Statement: Find employees earning more than the average salary.
โ Solution
SELECT name, salary FROM employees WHERE salary > ( SELECT AVG(salary) FROM employees );
๐ฏ 8๏ธโฃ Department with Highest Total Salary
๐ Table: employees
name | department | salary
A | IT | 100
B | IT | 200
C | HR | 500
โ Problem Statement: Find the department with the highest total salary.
โ Solution
SELECT department, SUM(salary) AS total_salary FROM employees GROUP BY department ORDER BY total_salary DESC LIMIT 1;
๐ฏ 9๏ธโฃ Customers Who Placed Orders
๐ Tables: Same as Q4
โ Problem Statement: Find customers who have placed at least one order.
โ Solution
SELECT name FROM customers c WHERE EXISTS ( SELECT 1 FROM orders o WHERE c.customer_id = o.customer_id );
๐ฏ ๐ Remove Duplicate Records
๐ Table: employees
id | name
1 | Rahul
2 | Rahul
3 | Amit
โ Problem Statement: Delete duplicate records but keep one unique record.
โ Solution
DELETE FROM employees WHERE id NOT IN ( SELECT MIN(id) FROM employees GROUP BY name );
๐ Pro Tip:
๐ In interviews:
First explain logic
Then write query
Then optimize
Double Tap โฅ๏ธ For More
๐ฏ 1๏ธโฃ Find 2nd Highest Salary
๐ Table: employees
id | name | salary
1 | Rahul | 50000
2 | Priya | 70000
3 | Amit | 60000
4 | Neha | 70000
โ Problem Statement: Find the second highest distinct salary from the employees table.
โ Solution
SELECT MAX(salary) FROM employees WHERE salary < ( SELECT MAX(salary) FROM employees );
๐ฏ 2๏ธโฃ Find Nth Highest Salary
๐ Table: employees
id | name | salary
1 | A | 100
2 | B | 200
3 | C | 300
4 | D | 200
โ Problem Statement: Write a query to find the 3rd highest salary.
โ Solution
SELECT salary FROM ( SELECT salary, DENSE_RANK() OVER(ORDER BY salary DESC) r FROM employees ) t WHERE r = 3;
๐ฏ 3๏ธโฃ Find Duplicate Records
๐ Table: employees
id | name
1 | Rahul
2 | Amit
3 | Rahul
4 | Neha
โ Problem Statement: Find all duplicate names in the employees table.
โ Solution
SELECT name, COUNT(*) FROM employees GROUP BY name HAVING COUNT(*) > 1;
๐ฏ 4๏ธโฃ Customers with No Orders
๐ Table: customers
customer_id | name
1 | Rahul
2 | Priya
3 | Amit
๐ Table: orders
order_id | customer_id
101 | 1
102 | 2
โ Problem Statement: Find customers who have not placed any orders.
โ Solution
SELECT c.name FROM customers c LEFT JOIN orders o ON c.customer_id = o.customer_id WHERE o.customer_id IS NULL;
๐ฏ 5๏ธโฃ Top 3 Salaries per Department
๐ Table: employees
name | department | salary
A | IT | 100
B | IT | 200
C | IT | 150
D | HR | 120
E | HR | 180
โ Problem Statement: Find the top 3 highest salaries in each department.
โ Solution
SELECT * FROM ( SELECT name, department, salary, ROW_NUMBER() OVER( PARTITION BY department ORDER BY salary DESC ) r FROM employees ) t WHERE r <= 3;
๐ฏ 6๏ธโฃ Running Total of Sales
๐ Table: sales
date | sales
2024-01-01 | 100
2024-01-02 | 200
2024-01-03 | 300
โ Problem Statement: Calculate the running total of sales by date.
โ Solution
SELECT date, sales, SUM(sales) OVER(ORDER BY date) AS running_total FROM sales;
๐ฏ 7๏ธโฃ Employees Above Average Salary
๐ Table: employees
name | salary
A | 100
B | 200
C | 300
โ Problem Statement: Find employees earning more than the average salary.
โ Solution
SELECT name, salary FROM employees WHERE salary > ( SELECT AVG(salary) FROM employees );
๐ฏ 8๏ธโฃ Department with Highest Total Salary
๐ Table: employees
name | department | salary
A | IT | 100
B | IT | 200
C | HR | 500
โ Problem Statement: Find the department with the highest total salary.
โ Solution
SELECT department, SUM(salary) AS total_salary FROM employees GROUP BY department ORDER BY total_salary DESC LIMIT 1;
๐ฏ 9๏ธโฃ Customers Who Placed Orders
๐ Tables: Same as Q4
โ Problem Statement: Find customers who have placed at least one order.
โ Solution
SELECT name FROM customers c WHERE EXISTS ( SELECT 1 FROM orders o WHERE c.customer_id = o.customer_id );
๐ฏ ๐ Remove Duplicate Records
๐ Table: employees
id | name
1 | Rahul
2 | Rahul
3 | Amit
โ Problem Statement: Delete duplicate records but keep one unique record.
โ Solution
DELETE FROM employees WHERE id NOT IN ( SELECT MIN(id) FROM employees GROUP BY name );
๐ Pro Tip:
๐ In interviews:
First explain logic
Then write query
Then optimize
Double Tap โฅ๏ธ For More
โค4