β
Interviewer: Count the number of employees in each department. π
Me: Using GROUP BY and COUNT():
β Why it works:
β COUNT() tallies employees per department by counting non-null IDs.
β GROUP BY segments the results by department name for aggregated output.
β INNER JOIN links employees to departments only where IDs match, avoiding nullsβadd ORDER BY employee_count DESC to sort by largest teams first!
π¬ Tap β€οΈ if you're learning something new!
Me: Using GROUP BY and COUNT():
SELECT d.dept_name,
COUNT(e.id) AS employee_count
FROM employees e
INNER JOIN departments d
ON e.dept_id = d.dept_id
GROUP BY d.dept_name;
β Why it works:
β COUNT() tallies employees per department by counting non-null IDs.
β GROUP BY segments the results by department name for aggregated output.
β INNER JOIN links employees to departments only where IDs match, avoiding nullsβadd ORDER BY employee_count DESC to sort by largest teams first!
π¬ Tap β€οΈ if you're learning something new!
β€7
β
10 Most Useful SQL Interview Queries (with Examples) πΌ
1οΈβ£ Find the second highest salary:
2οΈβ£ Count employees in each department:
3οΈβ£ Fetch duplicate emails:
4οΈβ£ Join orders with customer names:
5οΈβ£ Get top 3 highest salaries:
6οΈβ£ Retrieve latest 5 logins:
7οΈβ£ Employees with no manager:
8οΈβ£ Search names starting with βSβ:
9οΈβ£ Total sales per month:
π Delete inactive users:
β Tip: Master subqueries, joins, groupings & filters β they show up in nearly every interview!
π¬ Tap β€οΈ for more!
1οΈβ£ Find the second highest salary:
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
2οΈβ£ Count employees in each department:
SELECT department, COUNT(*)
FROM employees
GROUP BY department;
3οΈβ£ Fetch duplicate emails:
SELECT email, COUNT(*)
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
4οΈβ£ Join orders with customer names:
SELECT c.name, o.order_date
FROM customers c
JOIN orders o ON c.id = o.customer_id;
5οΈβ£ Get top 3 highest salaries:
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 3;
6οΈβ£ Retrieve latest 5 logins:
SELECT * FROM logins
ORDER BY login_time DESC
LIMIT 5;
7οΈβ£ Employees with no manager:
SELECT name
FROM employees
WHERE manager_id IS NULL;
8οΈβ£ Search names starting with βSβ:
SELECT * FROM employees
WHERE name LIKE 'S%';
9οΈβ£ Total sales per month:
SELECT MONTH(order_date) AS month, SUM(amount)
FROM sales
GROUP BY MONTH(order_date);
π Delete inactive users:
DELETE FROM users
WHERE last_active < '2023-01-01';
β Tip: Master subqueries, joins, groupings & filters β they show up in nearly every interview!
π¬ Tap β€οΈ for more!
β€33π1
β
Advanced SQL Queries ποΈπ‘
1οΈβ£ GROUP BY & HAVING
β¦ GROUP BY groups rows sharing a value to perform aggregate calculations.
β¦ HAVING filters groups based on conditions (like WHERE but for groups).
Example:
Find total sales per product with sales > 1000:
SELECT product_id, SUM(sales) AS total_sales
FROM sales_data
GROUP BY product_id
HAVING SUM(sales) > 1000;
2οΈβ£ Subqueries
β¦ A query inside another query. Useful for filtering or calculating values dynamically.
Example:
Get customers who placed orders over 500:
SELECT customer_id, order_id, amount
FROM orders
WHERE amount > (SELECT AVG(amount) FROM orders);
3οΈβ£ Aggregate Functions
β¦ Perform calculations on sets of rows:
β¦ COUNT() counts rows
β¦ SUM() adds numeric values
β¦ AVG() calculates average
β¦ MAX() and MIN() find extremes
Example:
Find average order amount per customer:
SELECT customer_id, AVG(amount) AS avg_order
FROM orders
GROUP BY customer_id;
4οΈβ£ Complex Joins with Filtering
β¦ Join tables and filter results in one query.
Example:
List customers with orders over100:
SELECT c.customer_name, o.order_id, o.amount
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
WHERE o.amount > 100;
π SQL Roadmap: https://whatsapp.com/channel/0029VanC5rODzgT6TiTGoa1v/1506
π¬ Double Tap β€οΈ For More!
1οΈβ£ GROUP BY & HAVING
β¦ GROUP BY groups rows sharing a value to perform aggregate calculations.
β¦ HAVING filters groups based on conditions (like WHERE but for groups).
Example:
Find total sales per product with sales > 1000:
SELECT product_id, SUM(sales) AS total_sales
FROM sales_data
GROUP BY product_id
HAVING SUM(sales) > 1000;
2οΈβ£ Subqueries
β¦ A query inside another query. Useful for filtering or calculating values dynamically.
Example:
Get customers who placed orders over 500:
SELECT customer_id, order_id, amount
FROM orders
WHERE amount > (SELECT AVG(amount) FROM orders);
3οΈβ£ Aggregate Functions
β¦ Perform calculations on sets of rows:
β¦ COUNT() counts rows
β¦ SUM() adds numeric values
β¦ AVG() calculates average
β¦ MAX() and MIN() find extremes
Example:
Find average order amount per customer:
SELECT customer_id, AVG(amount) AS avg_order
FROM orders
GROUP BY customer_id;
4οΈβ£ Complex Joins with Filtering
β¦ Join tables and filter results in one query.
Example:
List customers with orders over100:
SELECT c.customer_name, o.order_id, o.amount
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
WHERE o.amount > 100;
π SQL Roadmap: https://whatsapp.com/channel/0029VanC5rODzgT6TiTGoa1v/1506
π¬ Double Tap β€οΈ For More!
β€7π1
Data Analytics isn't rocket science. It's just a different language.
Here's a beginner's guide to the world of data analytics:
1) Understand the fundamentals:
- Mathematics
- Statistics
- Technology
2) Learn the tools:
- SQL
- Python
- Excel (yes, it's still relevant!)
3) Understand the data:
- What do you want to measure?
- How are you measuring it?
- What metrics are important to you?
4) Data Visualization:
- A picture is worth a thousand words
5) Practice:
- There's no better way to learn than to do it yourself.
Data Analytics is a valuable skill that can help you make better decisions, understand your audience better, and ultimately grow your business.
It's never too late to start learning!
Here's a beginner's guide to the world of data analytics:
1) Understand the fundamentals:
- Mathematics
- Statistics
- Technology
2) Learn the tools:
- SQL
- Python
- Excel (yes, it's still relevant!)
3) Understand the data:
- What do you want to measure?
- How are you measuring it?
- What metrics are important to you?
4) Data Visualization:
- A picture is worth a thousand words
5) Practice:
- There's no better way to learn than to do it yourself.
Data Analytics is a valuable skill that can help you make better decisions, understand your audience better, and ultimately grow your business.
It's never too late to start learning!
β€7
β
SQL Practice Questions with Answers π§ ποΈ
π Q1. How to find the 2nd highest salary from a table?
β Answer:
π Q2. How to find duplicate values in a column?
β Answer:
π Q3. How to select records that exist in one table but not in another?
β Answer:
π Q4. How to get the top 3 highest salaries? (MySQL)
β Answer:
π Q5. How to fetch employees with the same salary?
β Answer:
π Q6. How to get the department-wise highest salary?
β Answer:
π¬ Tap β€οΈ for more!
π Q1. How to find the 2nd highest salary from a table?
β Answer:
SELECT MAX(salary) FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
π Q2. How to find duplicate values in a column?
β Answer:
SELECT name, COUNT(*) FROM employees
GROUP BY name
HAVING COUNT(*) > 1;
π Q3. How to select records that exist in one table but not in another?
β Answer:
SELECT * FROM employees
WHERE id NOT IN (SELECT employee_id FROM payroll);
π Q4. How to get the top 3 highest salaries? (MySQL)
β Answer:
SELECT DISTINCT salary FROM employees
ORDER BY salary DESC
LIMIT 3;
π Q5. How to fetch employees with the same salary?
β Answer:
SELECT * FROM employees e1
WHERE EXISTS (
SELECT 1 FROM employees e2
WHERE e1.salary = e2.salary AND e1.id <> e2.id
);
π Q6. How to get the department-wise highest salary?
β Answer:
SELECT department, MAX(salary) AS max_salary
FROM employees
GROUP BY department;
π¬ Tap β€οΈ for more!
β€7π1π1
β
SQL Practice Questions with Answers: Part-2 π§ ποΈ
π Q7. Find employees who never received a bonus
π€ Table: employees
id | name
1 | Arjun
2 | Riya
3 | Meena
π° Table: bonus
employee_id | bonus_amount
1 | 3000
3 | 5000
π Query:
π Result: Riya
π Q8. Get highest salary employee from each department
π§Ύ Table: employees
id | name | dept | salary
1 | Arjun | HR | 40000
2 | Riya | IT | 55000
3 | Meena | IT | 62000
4 | Kabir | HR | 45000
π Query:
π Result: Kabir (HR), Meena (IT)
π Q9. Count number of employees who joined each year
π Table: employees
id | name | join_date
1 | Arjun | 2021-03-10
2 | Riya | 2022-05-12
3 | Meena | 2021-11-03
4 | Kabir | 2023-01-09
π Query:
π Result:
2021 β 2
2022 β 1
2023 β 1
π Q10. Find employees earning more than department average
π§Ύ Table: employees
id | name | dept | salary
1 | Arjun | HR | 40000
2 | Riya | IT | 55000
3 | Meena | IT | 62000
4 | Kabir | HR | 45000
π Query:
π Result: Kabir (HR), Meena (IT)
π Q11. Fetch the 5th highest salary from employee table
π§Ύ Table: employees
Salaries: 90000, 85000, 78000, 76000, 72000, 70000
π Query:
π Result: 72000
π Q12. Find employees working on more than one project
π Table: project_assignments
employee_id | project_id
1 | 101
1 | 102
2 | 103
3 | 104
3 | 105
3 | 106
π Query:
π Result:
1 β 2 projects
3 β 3 projects
π¬ Tap β€οΈ for more!
π Q7. Find employees who never received a bonus
π€ Table: employees
id | name
1 | Arjun
2 | Riya
3 | Meena
π° Table: bonus
employee_id | bonus_amount
1 | 3000
3 | 5000
π Query:
SELECT e.id, e.name
FROM employees e
LEFT JOIN bonus b ON e.id = b.employee_id
WHERE b.employee_id IS NULL;
π Result: Riya
π Q8. Get highest salary employee from each department
π§Ύ Table: employees
id | name | dept | salary
1 | Arjun | HR | 40000
2 | Riya | IT | 55000
3 | Meena | IT | 62000
4 | Kabir | HR | 45000
π Query:
SELECT e.*
FROM employees e
JOIN (
SELECT department, MAX(salary) AS max_salary
FROM employees
GROUP BY department
) t
ON e.department = t.department
AND e.salary = t.max_salary;
π Result: Kabir (HR), Meena (IT)
π Q9. Count number of employees who joined each year
π Table: employees
id | name | join_date
1 | Arjun | 2021-03-10
2 | Riya | 2022-05-12
3 | Meena | 2021-11-03
4 | Kabir | 2023-01-09
π Query:
SELECT YEAR(join_date) AS join_year, COUNT(*) AS total
FROM employees
GROUP BY YEAR(join_date)
ORDER BY join_year;
π Result:
2021 β 2
2022 β 1
2023 β 1
π Q10. Find employees earning more than department average
π§Ύ Table: employees
id | name | dept | salary
1 | Arjun | HR | 40000
2 | Riya | IT | 55000
3 | Meena | IT | 62000
4 | Kabir | HR | 45000
π Query:
SELECT e.*
FROM employees e
JOIN (
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
) t
ON e.department = t.department
WHERE e.salary > t.avg_salary;
π Result: Kabir (HR), Meena (IT)
π Q11. Fetch the 5th highest salary from employee table
π§Ύ Table: employees
Salaries: 90000, 85000, 78000, 76000, 72000, 70000
π Query:
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 4;
π Result: 72000
π Q12. Find employees working on more than one project
π Table: project_assignments
employee_id | project_id
1 | 101
1 | 102
2 | 103
3 | 104
3 | 105
3 | 106
π Query:
SELECT employee_id, COUNT(*) AS project_count
FROM project_assignments
GROUP BY employee_id
HAVING COUNT(*) > 1;
π Result:
1 β 2 projects
3 β 3 projects
π¬ Tap β€οΈ for more!
β€13
β
SQL Practice Questions with Answers: Part-3 π§ ποΈ
π Q13. Find employees whose salary is above the company average
π§Ύ Table: employees
id | name | salary
1 | Arjun | 40000
2 | Riya | 55000
3 | Meena | 62000
4 | Kabir | 45000
π Query:
π Result: Riya, Meena
π Q14. Get the 3 most recent joined employees
π Table: employees
id | name | join_date
1 | Arjun | 2021-03-10
2 | Riya | 2022-05-12
3 | Meena | 2023-02-01
4 | Kabir | 2023-11-09
π Query:
π Result: Kabir, Meena, Riya
π Q15. Retrieve employees who donβt have a manager assigned
π§Ύ Table: employees
id | name | manager_id
1 | Arjun | NULL
2 | Riya | 1
3 | Meena | NULL
4 | Kabir | 2
π Query:
π Result: Arjun, Meena
π Q16. Find departments where more than 2 employees work
π§Ύ Table: employees
id | name | department
1 | Arjun | HR
2 | Riya | IT
3 | Meena | IT
4 | Kabir | HR
5 | John | IT
π Query:
π Result: IT β 3 employees
π Q17. Select employees whose salary equals department average
π§Ύ Table: employees
id | name | dept | salary
1 | Arjun | HR | 40000
2 | Riya | IT | 55000
3 | Meena | IT | 62000
4 | Kabir | HR | 45000
π Query:
π Result: None (but logic works if matches exist)
π Q18. Get employees who have at least one matching project
π Table: project_assignments
employee_id | project_id
1 | 101
2 | 101
2 | 102
3 | 103
4 | 101
π Query:
π Result:
Employees 1, 2, 4 share project 101
π¬ Tap β€οΈ for more!
π Q13. Find employees whose salary is above the company average
π§Ύ Table: employees
id | name | salary
1 | Arjun | 40000
2 | Riya | 55000
3 | Meena | 62000
4 | Kabir | 45000
π Query:
SELECT *
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
π Result: Riya, Meena
π Q14. Get the 3 most recent joined employees
π Table: employees
id | name | join_date
1 | Arjun | 2021-03-10
2 | Riya | 2022-05-12
3 | Meena | 2023-02-01
4 | Kabir | 2023-11-09
π Query:
SELECT *
FROM employees
ORDER BY join_date DESC
LIMIT 3;
π Result: Kabir, Meena, Riya
π Q15. Retrieve employees who donβt have a manager assigned
π§Ύ Table: employees
id | name | manager_id
1 | Arjun | NULL
2 | Riya | 1
3 | Meena | NULL
4 | Kabir | 2
π Query:
SELECT id, name
FROM employees
WHERE manager_id IS NULL;
π Result: Arjun, Meena
π Q16. Find departments where more than 2 employees work
π§Ύ Table: employees
id | name | department
1 | Arjun | HR
2 | Riya | IT
3 | Meena | IT
4 | Kabir | HR
5 | John | IT
π Query:
SELECT department, COUNT(*) AS total
FROM employees
GROUP BY department
HAVING COUNT(*) > 2;
π Result: IT β 3 employees
π Q17. Select employees whose salary equals department average
π§Ύ Table: employees
id | name | dept | salary
1 | Arjun | HR | 40000
2 | Riya | IT | 55000
3 | Meena | IT | 62000
4 | Kabir | HR | 45000
π Query:
SELECT e.*
FROM employees e
JOIN (
SELECT dept, AVG(salary) AS avg_salary
FROM employees
GROUP BY dept
) t ON e.dept = t.dept
WHERE e.salary = t.avg_salary;
π Result: None (but logic works if matches exist)
π Q18. Get employees who have at least one matching project
π Table: project_assignments
employee_id | project_id
1 | 101
2 | 101
2 | 102
3 | 103
4 | 101
π Query:
SELECT p1.employee_id, p2.employee_id AS colleague
FROM project_assignments p1
JOIN project_assignments p2
ON p1.project_id = p2.project_id
AND p1.employee_id <> p2.employee_id;
π Result:
Employees 1, 2, 4 share project 101
π¬ Tap β€οΈ for more!
β€18
β
Free Resources to Learn SQL in 2025 π§ π
1. YouTube Channels
β’ freeCodeCamp β Comprehensive SQL courses
β’ Simplilearn β SQL basics and advanced topics
β’ CodeWithMosh β SQL tutorial for beginners
β’ Alex The Analyst β Practical SQL for data analysis
2. Websites
β’ W3Schools SQL Tutorial β Easy-to-understand basics
β’ SQLZoo β Interactive SQL tutorials with exercises
β’ GeeksforGeeks SQL β Concepts, interview questions, and examples
β’ LearnSQL β Free courses and interactive editor
3. Practice Platforms
β’ LeetCode (SQL section) β Interview-style SQL problems
β’ HackerRank (SQL section) β Challenges and practice problems
β’ StrataScratch β Real-world SQL questions from companies
β’ SQL Fiddle β Online SQL sandbox for testing queries
4. Free Courses
β’ Khan Academy: Intro to SQL β Basic database concepts and SQL
β’ Codecademy: Learn SQL (Basic) β Interactive lessons
β’ Great Learning: SQL for Beginners β Free certification course
β’ Udemy (search for free courses) β Many introductory SQL courses often available for free
5. Books for Starters
β’ βSQL in 10 Minutes, Sams Teach Yourselfβ β Ben Forta
β’ βSQL Practice Problems: 57 Problems to Test Your SQL Skillsβ β Sylvia Moestl Wasserman
β’ βLearning SQLβ β Alan Beaulieu
6. Must-Know Concepts
β’ SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY
β’ JOINs (INNER, LEFT, RIGHT, FULL)
β’ Subqueries, CTEs (Common Table Expressions)
β’ Window Functions (RANK, ROW_NUMBER, LEAD, LAG)
β’ Basic DDL (CREATE TABLE) and DML (INSERT, UPDATE, DELETE)
π‘ Practice consistently with real-world scenarios.
π¬ Tap β€οΈ for more!
1. YouTube Channels
β’ freeCodeCamp β Comprehensive SQL courses
β’ Simplilearn β SQL basics and advanced topics
β’ CodeWithMosh β SQL tutorial for beginners
β’ Alex The Analyst β Practical SQL for data analysis
2. Websites
β’ W3Schools SQL Tutorial β Easy-to-understand basics
β’ SQLZoo β Interactive SQL tutorials with exercises
β’ GeeksforGeeks SQL β Concepts, interview questions, and examples
β’ LearnSQL β Free courses and interactive editor
3. Practice Platforms
β’ LeetCode (SQL section) β Interview-style SQL problems
β’ HackerRank (SQL section) β Challenges and practice problems
β’ StrataScratch β Real-world SQL questions from companies
β’ SQL Fiddle β Online SQL sandbox for testing queries
4. Free Courses
β’ Khan Academy: Intro to SQL β Basic database concepts and SQL
β’ Codecademy: Learn SQL (Basic) β Interactive lessons
β’ Great Learning: SQL for Beginners β Free certification course
β’ Udemy (search for free courses) β Many introductory SQL courses often available for free
5. Books for Starters
β’ βSQL in 10 Minutes, Sams Teach Yourselfβ β Ben Forta
β’ βSQL Practice Problems: 57 Problems to Test Your SQL Skillsβ β Sylvia Moestl Wasserman
β’ βLearning SQLβ β Alan Beaulieu
6. Must-Know Concepts
β’ SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY
β’ JOINs (INNER, LEFT, RIGHT, FULL)
β’ Subqueries, CTEs (Common Table Expressions)
β’ Window Functions (RANK, ROW_NUMBER, LEAD, LAG)
β’ Basic DDL (CREATE TABLE) and DML (INSERT, UPDATE, DELETE)
π‘ Practice consistently with real-world scenarios.
π¬ Tap β€οΈ for more!
β€13π1
β
Top 5 Mistakes to Avoid When Learning SQL βπ
1οΈβ£ Ignoring Data Basics
Don't skip understanding tables, rows, primary keys, and relationships. These are the foundation of SQL.
2οΈβ£ Memorizing Queries Without Practice
Reading syntax isn't enough. Write real queries on sample databases to retain concepts.
3οΈβ£ Not Using Joins Early On
Many avoid JOINs thinking they're hard. Practice INNER, LEFT, and RIGHT JOINs with real examples to understand table relationships.
4οΈβ£ Skipping GROUP BY and Aggregates
GROUP BY with COUNT, SUM, AVG, etc., is core to analytics. Learn it early and use it often.
5οΈβ£ Not Practicing Real-World Scenarios
Writing SELECT * from a table isn't enough. Use projects like sales reports, user activity tracking, or inventory queries.
π¬ Tap β€οΈ for more!
1οΈβ£ Ignoring Data Basics
Don't skip understanding tables, rows, primary keys, and relationships. These are the foundation of SQL.
2οΈβ£ Memorizing Queries Without Practice
Reading syntax isn't enough. Write real queries on sample databases to retain concepts.
3οΈβ£ Not Using Joins Early On
Many avoid JOINs thinking they're hard. Practice INNER, LEFT, and RIGHT JOINs with real examples to understand table relationships.
4οΈβ£ Skipping GROUP BY and Aggregates
GROUP BY with COUNT, SUM, AVG, etc., is core to analytics. Learn it early and use it often.
5οΈβ£ Not Practicing Real-World Scenarios
Writing SELECT * from a table isn't enough. Use projects like sales reports, user activity tracking, or inventory queries.
π¬ Tap β€οΈ for more!
β€20π2
π ππ»ππ²πΏππΆπ²ππ²πΏ: How do you use
π π π²: Use
Example:
π§ Logic Breakdown:
- Works like if-else
- Evaluates conditions top to bottom
- Returns the first match
-
β Use Case:
- Create custom categories
- Replace values based on logic
- Conditional ordering or filtering
π¬ Tap β€οΈ for more!
CASE in SQL?π π π²: Use
CASE to add conditional logic inside SELECT, WHERE, or ORDER BY.Example:
SELECT name,
salary,
CASE
WHEN salary >= 80000 THEN 'High'
WHEN salary >= 50000 THEN 'Medium'
ELSE 'Low'
END AS salary_level
FROM employees;
π§ Logic Breakdown:
- Works like if-else
- Evaluates conditions top to bottom
- Returns the first match
-
ELSE is optional (defaults to NULL)β Use Case:
- Create custom categories
- Replace values based on logic
- Conditional ordering or filtering
π¬ Tap β€οΈ for more!
β€17π2
β
SQL Skills Every Beginner Should Learn ππ»
1οΈβ£ Understanding the Basics
β¦ What is a database and table
β¦ Rows, columns, primary keys, foreign keys
β¦ Relational database concepts
2οΈβ£ Core SQL Queries
β¦ SELECT, FROM, WHERE β Get filtered data
β¦ ORDER BY, LIMIT β Sort and control output
β¦ DISTINCT, BETWEEN, IN, LIKE β Filter smarter
3οΈβ£ Joins (Combine Tables)
β¦ INNER JOIN β Matching records in both tables
β¦ LEFT JOIN, RIGHT JOIN β Include unmatched from one side
β¦ FULL OUTER JOIN β All records, matched or not
4οΈβ£ Aggregations
β¦ COUNT(), SUM(), AVG(), MIN(), MAX()
β¦ GROUP BY to summarize data
β¦ HAVING to filter aggregated results
5οΈβ£ Subqueries & CTEs
β¦ Subquery inside WHERE or SELECT
β¦ WITH clause for clean and reusable code
6οΈβ£ Window Functions
β¦ ROW_NUMBER(), RANK(), DENSE_RANK()
β¦ PARTITION BY, ORDER BY inside OVER()
7οΈβ£ Data Cleaning & Logic
β¦ Handle NULL values
β¦ Use CASE WHEN for conditional columns
β¦ Remove duplicates using DISTINCT or ROW_NUMBER()
8οΈβ£ Practice & Projects
β¦ Sales reports, user activity, inventory tracking
β¦ Work on public datasets
β¦ Solve SQL questions on LeetCode or HackerRank
Double Tap β₯οΈ For More
1οΈβ£ Understanding the Basics
β¦ What is a database and table
β¦ Rows, columns, primary keys, foreign keys
β¦ Relational database concepts
2οΈβ£ Core SQL Queries
β¦ SELECT, FROM, WHERE β Get filtered data
β¦ ORDER BY, LIMIT β Sort and control output
β¦ DISTINCT, BETWEEN, IN, LIKE β Filter smarter
3οΈβ£ Joins (Combine Tables)
β¦ INNER JOIN β Matching records in both tables
β¦ LEFT JOIN, RIGHT JOIN β Include unmatched from one side
β¦ FULL OUTER JOIN β All records, matched or not
4οΈβ£ Aggregations
β¦ COUNT(), SUM(), AVG(), MIN(), MAX()
β¦ GROUP BY to summarize data
β¦ HAVING to filter aggregated results
5οΈβ£ Subqueries & CTEs
β¦ Subquery inside WHERE or SELECT
β¦ WITH clause for clean and reusable code
6οΈβ£ Window Functions
β¦ ROW_NUMBER(), RANK(), DENSE_RANK()
β¦ PARTITION BY, ORDER BY inside OVER()
7οΈβ£ Data Cleaning & Logic
β¦ Handle NULL values
β¦ Use CASE WHEN for conditional columns
β¦ Remove duplicates using DISTINCT or ROW_NUMBER()
8οΈβ£ Practice & Projects
β¦ Sales reports, user activity, inventory tracking
β¦ Work on public datasets
β¦ Solve SQL questions on LeetCode or HackerRank
Double Tap β₯οΈ For More
β€13π2
β
SQL Aggregation & GROUP BY Explained ππ§
Aggregation functions are used to summarize data, especially when working with grouped values.
1οΈβ£ Common Aggregate Functions
β¦ COUNT() β Total number of rows
β¦ SUM() β Adds up numeric values
β¦ AVG() β Calculates the average
β¦ MIN() / MAX() β Finds smallest/largest value
Example:
β‘οΈ Returns the number of employees in each department.
2οΈβ£ GROUP BY
Used with aggregate functions to group rows based on column values.
β‘οΈ Shows average salary by city.
3οΈβ£ HAVING vs WHERE
β¦ WHERE filters rows before grouping
β¦ HAVING filters groups after aggregation
Example:
β‘οΈ Shows departments with more than 5 employees.
4οΈβ£ GROUP BY Multiple Columns
β‘οΈ Groups by department and role for detailed summaries.
5οΈβ£ Real-World Use Cases
β Sales by region
β Orders per customer
β Avg. rating per product
β Monthly revenue reports
π¬ Tap β€οΈ for more!
Aggregation functions are used to summarize data, especially when working with grouped values.
1οΈβ£ Common Aggregate Functions
β¦ COUNT() β Total number of rows
β¦ SUM() β Adds up numeric values
β¦ AVG() β Calculates the average
β¦ MIN() / MAX() β Finds smallest/largest value
Example:
SELECT department, COUNT(*)
FROM employees
GROUP BY department;
β‘οΈ Returns the number of employees in each department.
2οΈβ£ GROUP BY
Used with aggregate functions to group rows based on column values.
SELECT city, AVG(salary)
FROM employees
GROUP BY city;
β‘οΈ Shows average salary by city.
3οΈβ£ HAVING vs WHERE
β¦ WHERE filters rows before grouping
β¦ HAVING filters groups after aggregation
Example:
SELECT dept_id, COUNT(*)
FROM employees
GROUP BY dept_id
HAVING COUNT(*) > 5;
β‘οΈ Shows departments with more than 5 employees.
4οΈβ£ GROUP BY Multiple Columns
SELECT dept_id, role, COUNT(*)
FROM employees
GROUP BY dept_id, role;
β‘οΈ Groups by department and role for detailed summaries.
5οΈβ£ Real-World Use Cases
β Sales by region
β Orders per customer
β Avg. rating per product
β Monthly revenue reports
π¬ Tap β€οΈ for more!
β€16π2π1
β
SQL Window Functions πͺπ
Window functions perform calculations across rows related to the current row without collapsing data, unlike
1οΈβ£ ROW_NUMBER()
Assigns a unique number to each row within a partition.
π *Use case:* Rank employees by salary within each department.
2οΈβ£ RANK() vs DENSE_RANK()
β’
β’
3οΈβ£ LAG() & LEAD()
Access previous or next row values.
π Use case: Compare current vs previous/next values
(e.g., salary change, stock price movement).
4οΈβ£ NTILE(n)
Divides rows into *n* equal buckets.
π Use case: Quartiles & percentile-based analysis.
5οΈβ£ Aggregates with OVER()
Running totals & partition-wise calculations.
π§ Interview Q&A
Q1οΈβ£ GROUP BY vs OVER()?
β’
β’
Q2οΈβ£ When to use LAG()?
To compare current row with previous data
(e.g., daily revenue change, previous month balance).
Q3οΈβ£ No PARTITION BY used?
The function runs over the entire result set.
Q4οΈβ£ Can we use ORDER BY inside OVER()?
β Yes. Required for ranking, LAG/LEAD, running totals.
π¬ Double tap β€οΈ & share for more SQL tips! π
Window functions perform calculations across rows related to the current row without collapsing data, unlike
GROUP BY.1οΈβ£ ROW_NUMBER()
Assigns a unique number to each row within a partition.
SELECT name, dept_id,
ROW_NUMBER() OVER (
PARTITION BY dept_id
ORDER BY salary DESC
) AS rank
FROM employees;
π *Use case:* Rank employees by salary within each department.
2οΈβ£ RANK() vs DENSE_RANK()
β’
RANK() β Skips numbers on ties (1, 2, 2, 4)β’
DENSE_RANK() β No gaps (1, 2, 2, 3)SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk
FROM employees;
3οΈβ£ LAG() & LEAD()
Access previous or next row values.
SELECT name, salary,
LAG(salary) OVER (ORDER BY id) AS prev_salary,
LEAD(salary) OVER (ORDER BY id) AS next_salary
FROM employees;
π Use case: Compare current vs previous/next values
(e.g., salary change, stock price movement).
4οΈβ£ NTILE(n)
Divides rows into *n* equal buckets.
SELECT name,
NTILE(4) OVER (ORDER BY salary DESC) AS quartile
FROM employees;
π Use case: Quartiles & percentile-based analysis.
5οΈβ£ Aggregates with OVER()
Running totals & partition-wise calculations.
SELECT name, dept_id, salary,
SUM(salary) OVER (PARTITION BY dept_id) AS dept_total
FROM employees;
π§ Interview Q&A
Q1οΈβ£ GROUP BY vs OVER()?
β’
GROUP BY β Collapses rows (one row per group)β’
OVER() β Keeps all rows and adds calculated columnsQ2οΈβ£ When to use LAG()?
To compare current row with previous data
(e.g., daily revenue change, previous month balance).
Q3οΈβ£ No PARTITION BY used?
The function runs over the entire result set.
Q4οΈβ£ Can we use ORDER BY inside OVER()?
β Yes. Required for ranking, LAG/LEAD, running totals.
π¬ Double tap β€οΈ & share for more SQL tips! π
β€10π1
β
SQL Basics You Should Know π»π
1οΈβ£ What is SQL?
SQL (Structured Query Language) is a standardized language used to manage and manipulate relational databases.
2οΈβ£ Most Common SQL Commands:
β’ SELECT β fetch data
β’ INSERT β add data
β’ UPDATE β modify existing data
β’ DELETE β remove data
β’ CREATE β create a new table or database
β’ DROP β delete a table or database
3οΈβ£ Filtering Data:
To filter records based on conditions:
4οΈβ£ Sorting Data:
To sort results in ascending or descending order:
5οΈβ£ Using Functions:
Common aggregate functions:
β’ COUNT() β counts the number of records
β’ AVG() β calculates the average value
β’ MAX() / MIN() β returns the highest/lowest value
β’ SUM() β computes the total sum
6οΈβ£ Grouping Data:
To group records and perform calculations:
7οΈβ£ Joins:
Combining rows from two or more tables based on related columns:
β’ INNER JOIN: Returns matching records in both tables
β’ LEFT JOIN: Returns all records from the left table and matching records from the right table
β’ RIGHT JOIN: Returns all records from the right table and matching records from the left table
β’ FULL JOIN: Returns all records when there is a match in either left or right table
8οΈβ£ Aliases:
To rename a column or table for readability:
9οΈβ£ Subqueries:
Using a query within another query:
π Real Use Cases:
β’ Managing employee records
β’ Generating sales reports
β’ Tracking inventory levels
β’ Analyzing customer insights
π¬ Tap β€οΈ for more SQL tips and tricks!
1οΈβ£ What is SQL?
SQL (Structured Query Language) is a standardized language used to manage and manipulate relational databases.
2οΈβ£ Most Common SQL Commands:
β’ SELECT β fetch data
β’ INSERT β add data
β’ UPDATE β modify existing data
β’ DELETE β remove data
β’ CREATE β create a new table or database
β’ DROP β delete a table or database
3οΈβ£ Filtering Data:
To filter records based on conditions:
SELECT * FROM employees WHERE salary > 50000;
4οΈβ£ Sorting Data:
To sort results in ascending or descending order:
SELECT name FROM students ORDER BY marks DESC;
5οΈβ£ Using Functions:
Common aggregate functions:
β’ COUNT() β counts the number of records
β’ AVG() β calculates the average value
β’ MAX() / MIN() β returns the highest/lowest value
β’ SUM() β computes the total sum
6οΈβ£ Grouping Data:
To group records and perform calculations:
SELECT department, COUNT(*) FROM employees GROUP BY department;
7οΈβ£ Joins:
Combining rows from two or more tables based on related columns:
β’ INNER JOIN: Returns matching records in both tables
β’ LEFT JOIN: Returns all records from the left table and matching records from the right table
β’ RIGHT JOIN: Returns all records from the right table and matching records from the left table
β’ FULL JOIN: Returns all records when there is a match in either left or right table
8οΈβ£ Aliases:
To rename a column or table for readability:
SELECT name AS employee_name FROM employees;
9οΈβ£ Subqueries:
Using a query within another query:
SELECT name FROM students WHERE marks > (SELECT AVG(marks) FROM students);
π Real Use Cases:
β’ Managing employee records
β’ Generating sales reports
β’ Tracking inventory levels
β’ Analyzing customer insights
π¬ Tap β€οΈ for more SQL tips and tricks!
β€17π1
β
Useful SQL Concepts You Should Know ππ
1οΈβ£ Constraints in SQL:
-
-
-
-
-
2οΈβ£ SQL Views:
Virtual tables based on result of a query
3οΈβ£ Indexing:
Improves query performance
4οΈβ£ SQL Transactions:
Ensure data integrity
5οΈβ£ Triggers:
Automatic actions when events occur
6οΈβ£ Stored Procedures:
Reusable blocks of SQL logic
7οΈβ£ Common Table Expressions (CTEs):
Temporary named result sets
π¬ Double Tap β€οΈ For More!
1οΈβ£ Constraints in SQL:
-
PRIMARY KEY β Uniquely identifies each row -
FOREIGN KEY β Links to another table -
UNIQUE β Ensures all values are different -
NOT NULL β Column must have a value -
CHECK β Validates data before insert/update2οΈβ£ SQL Views:
Virtual tables based on result of a query
CREATE VIEW top_students AS
SELECT name, marks FROM students WHERE marks > 90;
3οΈβ£ Indexing:
Improves query performance
CREATE INDEX idx_name ON employees(name);
4οΈβ£ SQL Transactions:
Ensure data integrity
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
5οΈβ£ Triggers:
Automatic actions when events occur
CREATE TRIGGER log_update
AFTER UPDATE ON employees
FOR EACH ROW
INSERT INTO logs(action) VALUES ('Employee updated');
6οΈβ£ Stored Procedures:
Reusable blocks of SQL logic
CREATE PROCEDURE getTopStudents()
BEGIN
SELECT * FROM students WHERE marks > 90;
END;
7οΈβ£ Common Table Expressions (CTEs):
Temporary named result sets
WITH dept_count AS (
SELECT department, COUNT(*) AS total FROM employees GROUP BY department
)
SELECT * FROM dept_count;
π¬ Double Tap β€οΈ For More!
β€15
β
SQL Coding Questions with Answers: Part-1 ππ»
1οΈβ£ Get the Second Highest Salary
Table: Employees
| id | name | salary |
|----|---------|--------|
| 1 | Alice | 5000 |
| 2 | Bob | 7000 |
| 3 | Charlie | 7000 |
| 4 | David | 6000 |
Query:
This returns the highest salary less than the maximumβi.e., the second highest.
2οΈβ£ Count Employees Per Department
Table: Employees
| id | name | dept |
|----|--------|--------|
| 1 | Alice | HR |
| 2 | Bob | IT |
| 3 | Clara | IT |
| 4 | Dan | Sales |
Query:
This groups employees by department and counts how many are in each.
3οΈβ£ Find Duplicate Emails
Table: Users
| id | email |
|----|------------------|
| 1 | [email protected] |
| 2 | [email protected] |
| 3 | [email protected] |
Query:
Returns all emails that appear more than once.
4οΈβ£ Get Top 2 Salaries Per Department
Table: Employees
| id | name | dept | salary |
|----|--------|-------|--------|
| 1 | Alice | IT | 7000 |
| 2 | Bob | IT | 6500 |
| 3 | Clara | HR | 6000 |
| 4 | Dan | HR | 5900 |
Query:
Ranks salaries within each department and returns top 2 per group.
5οΈβ£ Employees With No Manager Assigned
Table: Employees
| id | name | manager_id |
|----|-------|------------|
| 1 | John | NULL |
| 2 | Sarah | 1 |
| 3 | Alex | 2 |
Query:
Returns employees without any assigned manager.
π¬ Double Tap β€οΈ for Part-2!
1οΈβ£ Get the Second Highest Salary
Table: Employees
| id | name | salary |
|----|---------|--------|
| 1 | Alice | 5000 |
| 2 | Bob | 7000 |
| 3 | Charlie | 7000 |
| 4 | David | 6000 |
Query:
SELECT MAX(salary) AS Second_Highest
FROM Employees
WHERE salary < (
SELECT MAX(salary) FROM Employees
);
This returns the highest salary less than the maximumβi.e., the second highest.
2οΈβ£ Count Employees Per Department
Table: Employees
| id | name | dept |
|----|--------|--------|
| 1 | Alice | HR |
| 2 | Bob | IT |
| 3 | Clara | IT |
| 4 | Dan | Sales |
Query:
SELECT dept, COUNT(*) AS total_employees
FROM Employees
GROUP BY dept;
This groups employees by department and counts how many are in each.
3οΈβ£ Find Duplicate Emails
Table: Users
| id | email |
|----|------------------|
| 1 | [email protected] |
| 2 | [email protected] |
| 3 | [email protected] |
Query:
SELECT email, COUNT(*) AS count
FROM Users
GROUP BY email
HAVING COUNT(*) > 1;
Returns all emails that appear more than once.
4οΈβ£ Get Top 2 Salaries Per Department
Table: Employees
| id | name | dept | salary |
|----|--------|-------|--------|
| 1 | Alice | IT | 7000 |
| 2 | Bob | IT | 6500 |
| 3 | Clara | HR | 6000 |
| 4 | Dan | HR | 5900 |
Query:
SELECT * FROM (
SELECT *, RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rnk
FROM Employees
) AS ranked
WHERE rnk <= 2;
Ranks salaries within each department and returns top 2 per group.
5οΈβ£ Employees With No Manager Assigned
Table: Employees
| id | name | manager_id |
|----|-------|------------|
| 1 | John | NULL |
| 2 | Sarah | 1 |
| 3 | Alex | 2 |
Query:
SELECT * FROM Employees
WHERE manager_id IS NULL;
Returns employees without any assigned manager.
π¬ Double Tap β€οΈ for Part-2!
β€14
β
SQL Coding Interview Questions with Answers β Part 2 ππ»
1οΈβ£ Find Employees Who Earn More Than Their Manager
Table: Employees
| id | name | salary | manager_id |
|----|--------|--------|------------|
| 1 | Alice | 8000 | NULL |
| 2 | Bob | 6000 | 1 |
| 3 | Clara | 9000 | 1 |
| 4 | Dan | 5000 | 2 |
Query:
*Finds employees whose salary is greater than their managerβs.*
2οΈβ£ Find Departments With More Than 3 Employees
Table: Employees
| id | name | dept |
|----|-------|-------|
| 1 | Alice | IT |
| 2 | Bob | IT |
| 3 | Clara | HR |
| 4 | Dan | IT |
| 5 | Eva | IT |
Query:
*Lists departments that have more than 3 people.*
3οΈβ£ Find Employees Who Joined in Last 30 Days
Table: Employees
| id | name | join_date |
|----|-------|------------|
| 1 | Alice | 2023-11-10 |
| 2 | Bob | 2023-12-15 |
| 3 | Clara | 2023-12-25 |
Query:
*Shows all recent joiners.*
4οΈβ£ Find Common Records in Two Tables
Tables: A B
| A.id |
|------|
| 1 |
| 2 |
| 3 |
| B.id |
|------|
| 2 |
| 3 |
| 4 |
Query:
*Returns IDs that are present in both tables.*
5οΈβ£ List Employees with Same Salary
Table: Employees
| id | name | salary |
|----|-------|--------|
| 1 | Alice | 5000 |
| 2 | Bob | 6000 |
| 3 | Dan | 5000 |
Query:
*Then join it back if you want full details:*
π¬ Tap β€οΈ for Part-3!
1οΈβ£ Find Employees Who Earn More Than Their Manager
Table: Employees
| id | name | salary | manager_id |
|----|--------|--------|------------|
| 1 | Alice | 8000 | NULL |
| 2 | Bob | 6000 | 1 |
| 3 | Clara | 9000 | 1 |
| 4 | Dan | 5000 | 2 |
Query:
SELECT e.name
FROM Employees e
JOIN Employees m ON e.manager_id = m.id
WHERE e.salary > m.salary;
*Finds employees whose salary is greater than their managerβs.*
2οΈβ£ Find Departments With More Than 3 Employees
Table: Employees
| id | name | dept |
|----|-------|-------|
| 1 | Alice | IT |
| 2 | Bob | IT |
| 3 | Clara | HR |
| 4 | Dan | IT |
| 5 | Eva | IT |
Query:
SELECT dept
FROM Employees
GROUP BY dept
HAVING COUNT(*) > 3;
*Lists departments that have more than 3 people.*
3οΈβ£ Find Employees Who Joined in Last 30 Days
Table: Employees
| id | name | join_date |
|----|-------|------------|
| 1 | Alice | 2023-11-10 |
| 2 | Bob | 2023-12-15 |
| 3 | Clara | 2023-12-25 |
Query:
SELECT * FROM Employees
WHERE join_date >= CURRENT_DATE - INTERVAL 30 DAY;
*Shows all recent joiners.*
4οΈβ£ Find Common Records in Two Tables
Tables: A B
| A.id |
|------|
| 1 |
| 2 |
| 3 |
| B.id |
|------|
| 2 |
| 3 |
| 4 |
Query:
SELECT A.id
FROM A
INNER JOIN B ON A.id = B.id;
*Returns IDs that are present in both tables.*
5οΈβ£ List Employees with Same Salary
Table: Employees
| id | name | salary |
|----|-------|--------|
| 1 | Alice | 5000 |
| 2 | Bob | 6000 |
| 3 | Dan | 5000 |
Query:
SELECT salary
FROM Employees
GROUP BY salary
HAVING COUNT(*) > 1;
*Then join it back if you want full details:*
SELECT * FROM Employees
WHERE salary IN (
SELECT salary
FROM Employees
GROUP BY salary
HAVING COUNT(*) > 1
);
π¬ Tap β€οΈ for Part-3!
β€10
β
SQL Coding Interview Questions with Answers: Part 3 ππ»
1οΈβ£ Get Highest Salary Per Department
Table: Employees
Columns: id, name, dept, salary
Use case: Department-wise pay analysis.
2οΈβ£ Find Employees Without Matching Department
Tables: Employees, Departments
Use case: Data quality checks after joins.
3οΈβ£ Delete Duplicate Records but Keep One
Table: Users
Column: email
Use case: Cleanup before analytics.
4οΈβ£ Find Nth Highest Salary (Example: 3rd)
Table: Employees
Use case: Works even with duplicate salaries.
5οΈβ£ Swap Gender Values
Table: Employees
Column: gender (M, F)
Use case: Data correction tasks.
6οΈβ£ Find Employees with Odd IDs
Table: Employees
Use case: Common filter logic question.
7οΈβ£ Get Running Total of Salary
Table: Employees
Column: salary
Use case: Used in financial and growth reports.
π¬ Tap β€οΈ for Part 4!
1οΈβ£ Get Highest Salary Per Department
Table: Employees
Columns: id, name, dept, salary
SELECT dept, MAX(salary) AS highest_salary
FROM Employees
GROUP BY dept;
Use case: Department-wise pay analysis.
2οΈβ£ Find Employees Without Matching Department
Tables: Employees, Departments
SELECT e.*
FROM Employees e
LEFT JOIN Departments d
ON e.dept_id = d.id
WHERE d.id IS NULL;
Use case: Data quality checks after joins.
3οΈβ£ Delete Duplicate Records but Keep One
Table: Users
Column: email
DELETE FROM Users
WHERE id NOT IN (
SELECT MIN(id)
FROM Users
GROUP BY email
);
Use case: Cleanup before analytics.
4οΈβ£ Find Nth Highest Salary (Example: 3rd)
Table: Employees
SELECT salary
FROM (
SELECT salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM Employees
) t
WHERE rnk = 3;
Use case: Works even with duplicate salaries.
5οΈβ£ Swap Gender Values
Table: Employees
Column: gender (M, F)
UPDATE Employees
SET gender =
CASE
WHEN gender = 'M' THEN 'F'
WHEN gender = 'F' THEN 'M'
END;
Use case: Data correction tasks.
6οΈβ£ Find Employees with Odd IDs
Table: Employees
SELECT *
FROM Employees
WHERE id % 2 = 1;
Use case: Common filter logic question.
7οΈβ£ Get Running Total of Salary
Table: Employees
Column: salary
SELECT id, salary,
SUM(salary) OVER (ORDER BY id) AS running_total
FROM Employees;
Use case: Used in financial and growth reports.
π¬ Tap β€οΈ for Part 4!
β€9π1
β
SQL Coding Interview Questions with Answers: Part 4 ππ»
1οΈβ£ Retrieve Employees with the Highest Salary in Each Department (Full Details)
Table: Employees
Columns: id, name, dept, salary
π§ _Use case:_ Get full employee details, not just the salary, for top earners per department.
2οΈβ£ Find Departments Without Employees
Tables: Departments (id, name), Employees (id, name, dept_id)
π§ _Use case:_ Identify departments that havenβt been staffed yet.
3οΈβ£ Rank Employees by Salary Within Department (With Ties)
Table: Employees
π§ _Use case:_ Useful for performance reviews or compensation analysis.
4οΈβ£ Find Consecutive Login Days Per User
Table: Logins (user_id, login_date)
π§ _Use case:_ Group by user_id and grp to find streaks of consecutive logins.
5οΈβ£ Get Employees with the Minimum Salary in the Company
Table: Employees
π§ _Use case:_ Identify underpaid or entry-level employees.
6οΈβ£ Find Managers Who Donβt Have Any Direct Reports
Table: Employees (id, name, manager_id)
π§ Use case: Spot inactive or placeholder managers.
π¬ Double Tap β€οΈ For More
1οΈβ£ Retrieve Employees with the Highest Salary in Each Department (Full Details)
Table: Employees
Columns: id, name, dept, salary
SELECT *
FROM Employees e
WHERE salary = (
SELECT MAX(salary)
FROM Employees
WHERE dept = e.dept
);
π§ _Use case:_ Get full employee details, not just the salary, for top earners per department.
2οΈβ£ Find Departments Without Employees
Tables: Departments (id, name), Employees (id, name, dept_id)
SELECT d.*
FROM Departments d
LEFT JOIN Employees e ON d.id = e.dept_id
WHERE e.id IS NULL;
π§ _Use case:_ Identify departments that havenβt been staffed yet.
3οΈβ£ Rank Employees by Salary Within Department (With Ties)
Table: Employees
SELECT id, name, dept, salary,
RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS salary_rank
FROM Employees;
π§ _Use case:_ Useful for performance reviews or compensation analysis.
4οΈβ£ Find Consecutive Login Days Per User
Table: Logins (user_id, login_date)
SELECT user_id, login_date,
DATEDIFF(login_date,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date)) AS grp
FROM Logins;
π§ _Use case:_ Group by user_id and grp to find streaks of consecutive logins.
5οΈβ£ Get Employees with the Minimum Salary in the Company
Table: Employees
SELECT *
FROM Employees
WHERE salary = (SELECT MIN(salary) FROM Employees);
π§ _Use case:_ Identify underpaid or entry-level employees.
6οΈβ£ Find Managers Who Donβt Have Any Direct Reports
Table: Employees (id, name, manager_id)
SELECT *
FROM Employees
WHERE id NOT IN (
SELECT DISTINCT manager_id
FROM Employees
WHERE manager_id IS NOT NULL
);
π§ Use case: Spot inactive or placeholder managers.
π¬ Double Tap β€οΈ For More
β€16π1
Most Asked SQL Interview Questions at MAANG Companiesπ₯π₯
Preparing for an SQL Interview at MAANG Companies? Here are some crucial SQL Questions you should be ready to tackle:
1. How do you retrieve all columns from a table?
SELECT * FROM table_name;
2. What SQL statement is used to filter records?
SELECT * FROM table_name
WHERE condition;
The WHERE clause is used to filter records based on a specified condition.
3. How can you join multiple tables? Describe different types of JOINs.
SELECT columns
FROM table1
JOIN table2 ON table1.column = table2.column
JOIN table3 ON table2.column = table3.column;
Types of JOINs:
1. INNER JOIN: Returns records with matching values in both tables
SELECT * FROM table1
INNER JOIN table2 ON table1.column = table2.column;
2. LEFT JOIN: Returns all records from the left table & matched records from the right table. Unmatched records will have NULL values.
SELECT * FROM table1
LEFT JOIN table2 ON table1.column = table2.column;
3. RIGHT JOIN: Returns all records from the right table & matched records from the left table. Unmatched records will have NULL values.
SELECT * FROM table1
RIGHT JOIN table2 ON table1.column = table2.column;
4. FULL JOIN: Returns records when there is a match in either left or right table. Unmatched records will have NULL values.
SELECT * FROM table1
FULL JOIN table2 ON table1.column = table2.column;
4. What is the difference between WHERE & HAVING clauses?
WHERE: Filters records before any groupings are made.
SELECT * FROM table_name
WHERE condition;
HAVING: Filters records after groupings are made.
SELECT column, COUNT(*)
FROM table_name
GROUP BY column
HAVING COUNT(*) > value;
5. How do you calculate average, sum, minimum & maximum values in a column?
Average: SELECT AVG(column_name) FROM table_name;
Sum: SELECT SUM(column_name) FROM table_name;
Minimum: SELECT MIN(column_name) FROM table_name;
Maximum: SELECT MAX(column_name) FROM table_name;
Here you can find essential SQL Interview Resourcesπ
https://t.iss.one/mysqldata
Like this post if you need more πβ€οΈ
Hope it helps :)
Preparing for an SQL Interview at MAANG Companies? Here are some crucial SQL Questions you should be ready to tackle:
1. How do you retrieve all columns from a table?
SELECT * FROM table_name;
2. What SQL statement is used to filter records?
SELECT * FROM table_name
WHERE condition;
The WHERE clause is used to filter records based on a specified condition.
3. How can you join multiple tables? Describe different types of JOINs.
SELECT columns
FROM table1
JOIN table2 ON table1.column = table2.column
JOIN table3 ON table2.column = table3.column;
Types of JOINs:
1. INNER JOIN: Returns records with matching values in both tables
SELECT * FROM table1
INNER JOIN table2 ON table1.column = table2.column;
2. LEFT JOIN: Returns all records from the left table & matched records from the right table. Unmatched records will have NULL values.
SELECT * FROM table1
LEFT JOIN table2 ON table1.column = table2.column;
3. RIGHT JOIN: Returns all records from the right table & matched records from the left table. Unmatched records will have NULL values.
SELECT * FROM table1
RIGHT JOIN table2 ON table1.column = table2.column;
4. FULL JOIN: Returns records when there is a match in either left or right table. Unmatched records will have NULL values.
SELECT * FROM table1
FULL JOIN table2 ON table1.column = table2.column;
4. What is the difference between WHERE & HAVING clauses?
WHERE: Filters records before any groupings are made.
SELECT * FROM table_name
WHERE condition;
HAVING: Filters records after groupings are made.
SELECT column, COUNT(*)
FROM table_name
GROUP BY column
HAVING COUNT(*) > value;
5. How do you calculate average, sum, minimum & maximum values in a column?
Average: SELECT AVG(column_name) FROM table_name;
Sum: SELECT SUM(column_name) FROM table_name;
Minimum: SELECT MIN(column_name) FROM table_name;
Maximum: SELECT MAX(column_name) FROM table_name;
Here you can find essential SQL Interview Resourcesπ
https://t.iss.one/mysqldata
Like this post if you need more πβ€οΈ
Hope it helps :)
β€10π1
β
Top SQL Queries: Part-1 π§ π»
1οΈβ£ SELECT β Retrieve Data
πΉ Use case: Show all employees
SELECT * FROM employees;
2οΈβ£ WHERE β Filter Data
πΉ Use case: Get employees from βSalesβ department
SELECT name FROM employees WHERE department = 'Sales';
3οΈβ£ ORDER BY β Sort Results
πΉ Use case: List products by price (low to high)
SELECT product_name, price FROM products ORDER BY price ASC;
4οΈβ£ GROUP BY β Aggregate Data
πΉ Use case: Count employees in each department
SELECT department, COUNT(*) FROM employees GROUP BY department;
5οΈβ£ JOIN β Combine Tables
πΉ Use case: Show orders with customer names
SELECT o.order_id, c.customer_name
FROM orders o
JOIN customers c ON o.customer_id = c.id;
6οΈβ£ INSERT β Add New Records
πΉ Use case: Add a new product
INSERT INTO products (name, price, category)
VALUES ('Headphones', 1500, 'Electronics');
7οΈβ£ UPDATE β Modify Existing Records
πΉ Use case: Change price of 'Headphones'
UPDATE products SET price = 1700 WHERE name = 'Headphones';
8οΈβ£ DELETE β Remove Data
πΉ Use case: Delete users inactive for 1 year
DELETE FROM users WHERE last_login < '2024-01-01';
9οΈβ£ LIKE β Pattern Matching
πΉ Use case: Find customers whose names start with 'A'
SELECT * FROM customers WHERE name LIKE 'A%';
π LIMIT β Restrict Output
πΉ Use case: Show top 3 most expensive items
SELECT name, price FROM products ORDER BY price DESC LIMIT 3;
π¬ Tap β€οΈ for Part 2!
1οΈβ£ SELECT β Retrieve Data
πΉ Use case: Show all employees
SELECT * FROM employees;
2οΈβ£ WHERE β Filter Data
πΉ Use case: Get employees from βSalesβ department
SELECT name FROM employees WHERE department = 'Sales';
3οΈβ£ ORDER BY β Sort Results
πΉ Use case: List products by price (low to high)
SELECT product_name, price FROM products ORDER BY price ASC;
4οΈβ£ GROUP BY β Aggregate Data
πΉ Use case: Count employees in each department
SELECT department, COUNT(*) FROM employees GROUP BY department;
5οΈβ£ JOIN β Combine Tables
πΉ Use case: Show orders with customer names
SELECT o.order_id, c.customer_name
FROM orders o
JOIN customers c ON o.customer_id = c.id;
6οΈβ£ INSERT β Add New Records
πΉ Use case: Add a new product
INSERT INTO products (name, price, category)
VALUES ('Headphones', 1500, 'Electronics');
7οΈβ£ UPDATE β Modify Existing Records
πΉ Use case: Change price of 'Headphones'
UPDATE products SET price = 1700 WHERE name = 'Headphones';
8οΈβ£ DELETE β Remove Data
πΉ Use case: Delete users inactive for 1 year
DELETE FROM users WHERE last_login < '2024-01-01';
9οΈβ£ LIKE β Pattern Matching
πΉ Use case: Find customers whose names start with 'A'
SELECT * FROM customers WHERE name LIKE 'A%';
π LIMIT β Restrict Output
πΉ Use case: Show top 3 most expensive items
SELECT name, price FROM products ORDER BY price DESC LIMIT 3;
π¬ Tap β€οΈ for Part 2!
β€14π1