โ
Complete Roadmap to Mastering SQL ๐ ๐๏ธ
๐ 1. SQL Fundamentals
โ What is a database & DBMS
โ Basic Syntax: SELECT, FROM, WHERE
โ Data Types: INT, VARCHAR, DATE, etc.
โ Operators: =, >, <, LIKE, IN
โ Aliases & Comments
๐ 2. Filtering & Sorting
โ WHERE Clause: Advanced conditions
โ ORDER BY: Sorting results
โ LIMIT: Restricting rows
โ DISTINCT: Unique values
๐ 3. Aggregate Functions
โ COUNT(), SUM(), AVG(), MIN(), MAX()
โ GROUP BY: Grouping data
โ HAVING: Filtering grouped data
๐ 4. Joins & Relationships
โ INNER JOIN: Matching rows
โ LEFT/RIGHT JOIN: All rows from one table
โ FULL OUTER JOIN: All rows from both tables
โ Self Join: Joining a table to itself
โ Subqueries: Queries within queries
๐ 5. Advanced Filtering
โ IN, BETWEEN, LIKE operators
โ NULL values: IS NULL, IS NOT NULL
โ EXISTS operator
๐ 6. Subqueries & CTEs
โ Subqueries in SELECT, FROM, WHERE
โ Common Table Expressions (CTEs): Reusable queries
๐ 7. Window Functions
โ RANK(), DENSE_RANK(), ROW_NUMBER()
โ LAG(), LEAD()
โ OVER() clause: Defining the window
โ Partitioning: PARTITION BY
๐ 8. Data Manipulation
โ INSERT: Adding new data
โ UPDATE: Modifying existing data
โ DELETE: Removing data
โ MERGE: Combining data (upsert)
๐ 9. Database Design
โ Normalization: Reducing redundancy
โ Primary & Foreign Keys: Relationships
โ Data types & Constraints
โ Indexing: Improving query performance
๐ 10. Advanced Topics
โ Stored Procedures: Precompiled SQL
โ Triggers: Automatic actions
โ Views: Virtual tables
โ Performance Tuning: Optimizing queries
โ Security: User permissions
๐ 11. Practice & Projects
โ Solve coding challenges on platforms like *LeetCode, HackerRank*
โ Work on real-world projects using datasets from *Kaggle, Data.gov*
โ Build a portfolio to showcase your SQL skills
๐ฌ Tap โค๏ธ if you found this helpful!
๐ 1. SQL Fundamentals
โ What is a database & DBMS
โ Basic Syntax: SELECT, FROM, WHERE
โ Data Types: INT, VARCHAR, DATE, etc.
โ Operators: =, >, <, LIKE, IN
โ Aliases & Comments
๐ 2. Filtering & Sorting
โ WHERE Clause: Advanced conditions
โ ORDER BY: Sorting results
โ LIMIT: Restricting rows
โ DISTINCT: Unique values
๐ 3. Aggregate Functions
โ COUNT(), SUM(), AVG(), MIN(), MAX()
โ GROUP BY: Grouping data
โ HAVING: Filtering grouped data
๐ 4. Joins & Relationships
โ INNER JOIN: Matching rows
โ LEFT/RIGHT JOIN: All rows from one table
โ FULL OUTER JOIN: All rows from both tables
โ Self Join: Joining a table to itself
โ Subqueries: Queries within queries
๐ 5. Advanced Filtering
โ IN, BETWEEN, LIKE operators
โ NULL values: IS NULL, IS NOT NULL
โ EXISTS operator
๐ 6. Subqueries & CTEs
โ Subqueries in SELECT, FROM, WHERE
โ Common Table Expressions (CTEs): Reusable queries
๐ 7. Window Functions
โ RANK(), DENSE_RANK(), ROW_NUMBER()
โ LAG(), LEAD()
โ OVER() clause: Defining the window
โ Partitioning: PARTITION BY
๐ 8. Data Manipulation
โ INSERT: Adding new data
โ UPDATE: Modifying existing data
โ DELETE: Removing data
โ MERGE: Combining data (upsert)
๐ 9. Database Design
โ Normalization: Reducing redundancy
โ Primary & Foreign Keys: Relationships
โ Data types & Constraints
โ Indexing: Improving query performance
๐ 10. Advanced Topics
โ Stored Procedures: Precompiled SQL
โ Triggers: Automatic actions
โ Views: Virtual tables
โ Performance Tuning: Optimizing queries
โ Security: User permissions
๐ 11. Practice & Projects
โ Solve coding challenges on platforms like *LeetCode, HackerRank*
โ Work on real-world projects using datasets from *Kaggle, Data.gov*
โ Build a portfolio to showcase your SQL skills
๐ฌ Tap โค๏ธ if you found this helpful!
โค19๐2
โ
20 Medium-Level SQL Interview Questions (with Detailed Answers)
1. Write a SQL query to find the second-highest salary.
2. How would you optimize a slow SQL query?
โข Use appropriate indexes.
โข Avoid
โข Rewrite correlated subqueries as joins.
โข Use
โข Break complex queries into CTEs.
3. What is the difference between INNER JOIN and OUTER JOIN?
โข
โข
4. Write a SQL query to find the top 3 departments with the highest average salary.
5. How do you handle duplicate rows in a SQL query?
Use
6. Write a SQL query to find the employees who have the same name and work in the same department.
7. What is the difference between UNION and UNION ALL?
โข
โข
8. Write a SQL query to find the departments with no employees.
9. How do you use indexing to improve SQL query performance?
โข Indexes reduce the data scanned by filtering or joining.
โข Create indexes on frequently used
10. Write a SQL query to find the employees who have worked for more than 5 years.
11. What is the difference between SUBQUERY and JOIN?
โข
โข
12. Write a SQL query to find the top 2 products with the highest sales.
13. How do you use stored procedures to improve SQL query performance?
โข Pre-compiled and cached.
โข Reduces network traffic with multiple operations in one call.
โข Enhances modularity and reusability.
14. Write a SQL query to find the customers who have placed an order but have not made a payment.
15. What is the difference between GROUP BY and HAVING?
โข
โข
16. Write a SQL query to find the employees who work in the same department as their manager.
17. How do you use window functions to solve complex queries?
โข Use
โข They perform calculations across rows without collapsing them.
18. Write a SQL query to find the top 3 products with the highest average price.
19. What is the difference between TRUNCATE and DELETE?
โข
โข
20. Write a SQL query to find the employees who have not taken any leave in the last 6 months.
1. Write a SQL query to find the second-highest salary.
SELECT MAX(salary) AS SecondHighestSalary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
2. How would you optimize a slow SQL query?
โข Use appropriate indexes.
โข Avoid
SELECT * and fetch only needed columns.โข Rewrite correlated subqueries as joins.
โข Use
EXPLAIN to analyze query plan.โข Break complex queries into CTEs.
3. What is the difference between INNER JOIN and OUTER JOIN?
โข
INNER JOIN: Returns only matching rows between tables.โข
OUTER JOIN: Includes matching rows and non-matching rows with NULLs (LEFT, RIGHT, FULL).4. Write a SQL query to find the top 3 departments with the highest average salary.
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
ORDER BY avg_salary DESC
LIMIT 3;
5. How do you handle duplicate rows in a SQL query?
Use
DISTINCT, or use ROW_NUMBER() in a CTE and filter rows:WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY name, department_id ORDER BY id) AS rn
FROM employees
)
DELETE FROM cte WHERE rn > 1;
6. Write a SQL query to find the employees who have the same name and work in the same department.
SELECT name, department_id
FROM employees
GROUP BY name, department_id
HAVING COUNT(*) > 1;
7. What is the difference between UNION and UNION ALL?
โข
UNION: Removes duplicates.โข
UNION ALL: Keeps all records including duplicates.8. Write a SQL query to find the departments with no employees.
SELECT d.department_id, d.department_name
FROM departments d
LEFT JOIN employees e ON d.department_id = e.department_id
WHERE e.employee_id IS NULL;
9. How do you use indexing to improve SQL query performance?
โข Indexes reduce the data scanned by filtering or joining.
โข Create indexes on frequently used
WHERE, JOIN, and ORDER BY columns.10. Write a SQL query to find the employees who have worked for more than 5 years.
SELECT *
FROM employees
WHERE DATEDIFF(CURDATE(), hire_date) > 5 * 365;
11. What is the difference between SUBQUERY and JOIN?
โข
Subquery: Query inside another query, can be nested.โข
Join: Combines rows from multiple tables based on related columns.12. Write a SQL query to find the top 2 products with the highest sales.
SELECT product_id, SUM(sales) AS total_sales
FROM sales_table
GROUP BY product_id
ORDER BY total_sales DESC
LIMIT 2;
13. How do you use stored procedures to improve SQL query performance?
โข Pre-compiled and cached.
โข Reduces network traffic with multiple operations in one call.
โข Enhances modularity and reusability.
14. Write a SQL query to find the customers who have placed an order but have not made a payment.
SELECT o.customer_id
FROM orders o
LEFT JOIN payments p ON o.order_id = p.order_id
WHERE p.payment_id IS NULL;
15. What is the difference between GROUP BY and HAVING?
โข
GROUP BY: Groups rows based on one or more columns.โข
HAVING: Filters groups, like WHERE but for aggregated data.16. Write a SQL query to find the employees who work in the same department as their manager.
SELECT e.employee_id, e.name
FROM employees e
JOIN employees m ON e.department_id = m.department_id AND e.manager_id = m.employee_id;
17. How do you use window functions to solve complex queries?
โข Use
ROW_NUMBER(), RANK(), SUM() OVER(), LAG() etc.โข They perform calculations across rows without collapsing them.
18. Write a SQL query to find the top 3 products with the highest average price.
SELECT product_id, AVG(price) AS avg_price
FROM products
GROUP BY product_id
ORDER BY avg_price DESC
LIMIT 3;
19. What is the difference between TRUNCATE and DELETE?
โข
TRUNCATE: Removes all rows, faster, canโt rollback in most DBs.โข
DELETE: Removes selected rows, supports WHERE, and rollback.20. Write a SQL query to find the employees who have not taken any leave in the last 6 months.
SELECT e.*
FROM employees e
LEFT JOIN leaves l ON e.employee_id = l.employee_id AND l.leave_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
WHERE l.leave_id IS NULL;
โค16๐ค1
๐ Essential SQL Commands & Functions Cheatsheet ๐ง๐ป
Whether beginner or prepping for data roles, mastering these essentials helps a lot! ๐ก
โฌ๏ธ *Quick SQL reference:*
1) SELECT โ Retrieve data
2) WHERE โ Filter rows by condition
3) GROUP BY โ Aggregate by column(s)
4) HAVING โ Filter aggregated groups
5) ORDER BY โ Sort results
6) JOIN โ Combine tables
7) UNION โ Merge query results
8) INSERT INTO โ Add new records
9) UPDATE โ Modify records
10) DELETE โ Remove records
11) CREATE TABLE โ Make a new table
12) ALTER TABLE โ Modify table structure
13) DROP TABLE โ Delete a table
14) TRUNCATE TABLE โ Remove all rows
15) DISTINCT โ Get unique values
16) LIMIT โ Restrict result count
17) IN / BETWEEN โ Filter by multiple values/ranges
18) LIKE โ Pattern match
19) IS NULL โ Filter NULLs
20) COUNT()/SUM()/AVG() โ Aggregate functions
โ Save & save time in your next SQL task! ๐
Whether beginner or prepping for data roles, mastering these essentials helps a lot! ๐ก
โฌ๏ธ *Quick SQL reference:*
1) SELECT โ Retrieve data
2) WHERE โ Filter rows by condition
3) GROUP BY โ Aggregate by column(s)
4) HAVING โ Filter aggregated groups
5) ORDER BY โ Sort results
6) JOIN โ Combine tables
7) UNION โ Merge query results
8) INSERT INTO โ Add new records
9) UPDATE โ Modify records
10) DELETE โ Remove records
11) CREATE TABLE โ Make a new table
12) ALTER TABLE โ Modify table structure
13) DROP TABLE โ Delete a table
14) TRUNCATE TABLE โ Remove all rows
15) DISTINCT โ Get unique values
16) LIMIT โ Restrict result count
17) IN / BETWEEN โ Filter by multiple values/ranges
18) LIKE โ Pattern match
19) IS NULL โ Filter NULLs
20) COUNT()/SUM()/AVG() โ Aggregate functions
โ Save & save time in your next SQL task! ๐
โค6
โ
50 Must-Know SQL Concepts for Interviews ๐ง ๐
๐ Core Concepts
1. SELECT, FROM, WHERE
2. ORDER BY, LIMIT
3. AND, OR, NOT, IN, BETWEEN
4. NULL & IS NULL
5. DISTINCT
๐ Aggregations
6. COUNT(), SUM(), AVG()
7. MIN(), MAX()
8. GROUP BY
9. HAVING
๐ Joins
10. INNER JOIN
11. LEFT JOIN
12. RIGHT JOIN
13. FULL OUTER JOIN
14. SELF JOIN
15. CROSS JOIN
๐ Subqueries & CTEs
16. Subquery in SELECT
17. Subquery in WHERE
18. WITH (Common Table Expression)
19. Correlated Subqueries
๐ Window Functions
20. ROW_NUMBER()
21. RANK(), DENSE_RANK()
22. LEAD(), LAG()
23. OVER(), PARTITION BY
๐ String & Date Functions
24. CONCAT(), LENGTH(), UPPER()/LOWER()
25. SUBSTRING(), REPLACE()
26. DATE(), NOW(), DATEDIFF()
๐ Advanced Features
27. CASE WHEN
28. IF() & IFNULL()
29. COALESCE()
30. Nested Queries
31. Temporary Tables
32. Views
33. Stored Procedures (Basic)
34. Indexes & Performance
35. Transactions (BEGIN, COMMIT, ROLLBACK)
36. Primary & Foreign Keys
๐ Analytics Use Cases
37. Cohort Analysis
38. Retention Metrics
39. Funnel Analysis
40. Rolling Averages
41. AB Testing Query Logic
๐ Best Practices
42. Aliasing (AS)
43. Use EXPLAIN to check query plan
44. Avoid SELECT \* in production
45. Proper indexing
46. Normalize vs Denormalize
๐ Real-Life Scenarios
47. Querying large datasets
48. Optimizing slow queries
49. Joining multiple large tables
50. Writing reusable queries
๐ก Tap โค๏ธ for more!
๐ Core Concepts
1. SELECT, FROM, WHERE
2. ORDER BY, LIMIT
3. AND, OR, NOT, IN, BETWEEN
4. NULL & IS NULL
5. DISTINCT
๐ Aggregations
6. COUNT(), SUM(), AVG()
7. MIN(), MAX()
8. GROUP BY
9. HAVING
๐ Joins
10. INNER JOIN
11. LEFT JOIN
12. RIGHT JOIN
13. FULL OUTER JOIN
14. SELF JOIN
15. CROSS JOIN
๐ Subqueries & CTEs
16. Subquery in SELECT
17. Subquery in WHERE
18. WITH (Common Table Expression)
19. Correlated Subqueries
๐ Window Functions
20. ROW_NUMBER()
21. RANK(), DENSE_RANK()
22. LEAD(), LAG()
23. OVER(), PARTITION BY
๐ String & Date Functions
24. CONCAT(), LENGTH(), UPPER()/LOWER()
25. SUBSTRING(), REPLACE()
26. DATE(), NOW(), DATEDIFF()
๐ Advanced Features
27. CASE WHEN
28. IF() & IFNULL()
29. COALESCE()
30. Nested Queries
31. Temporary Tables
32. Views
33. Stored Procedures (Basic)
34. Indexes & Performance
35. Transactions (BEGIN, COMMIT, ROLLBACK)
36. Primary & Foreign Keys
๐ Analytics Use Cases
37. Cohort Analysis
38. Retention Metrics
39. Funnel Analysis
40. Rolling Averages
41. AB Testing Query Logic
๐ Best Practices
42. Aliasing (AS)
43. Use EXPLAIN to check query plan
44. Avoid SELECT \* in production
45. Proper indexing
46. Normalize vs Denormalize
๐ Real-Life Scenarios
47. Querying large datasets
48. Optimizing slow queries
49. Joining multiple large tables
50. Writing reusable queries
๐ก Tap โค๏ธ for more!
โค13
The Only SQL You Actually Need For Your First Job (Data Analytics)
The Learning Trap: What Most Beginners Fall Into
When starting out, it's common to feel like you need to master every possible SQL concept. You binge YouTube videos, tutorials, and courses, yet still feel lost in interviews or when given a real dataset.
Common traps:
- Complex subqueries
- Advanced CTEs
- Recursive queries
- 100+ tutorials watched
- 0 practical experience
Reality Check: What You'll Actually Use 75% of the Time
Most data analytics roles (especially entry-level) require clarity, speed, and confidence with core SQL operations. Hereโs what covers most daily work:
1. SELECT, FROM, WHERE โ The Foundation
SELECT name, age
FROM employees
WHERE department = 'Finance';
This is how almost every query begins. Whether exploring a dataset or building a dashboard, these are always in use.
2. JOINs โ Combining Data From Multiple Tables
SELECT e.name, d.department_name
FROM employees e
JOIN departments d ON e.department_id = d.id;
Youโll often join tables like employee data with department, customer orders with payments, etc.
3. GROUP BY โ Summarizing Data
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;
Used to get summaries by categories like sales per region or users by plan.
4. ORDER BY โ Sorting Results
SELECT name, salary
FROM employees
ORDER BY salary DESC;
Helps sort output for dashboards or reports.
5. Aggregations โ Simple But Powerful
Common functions: COUNT(), SUM(), AVG(), MIN(), MAX()
SELECT AVG(salary)
FROM employees
WHERE department = 'IT';
Gives quick insights like average deal size or total revenue.
6. ROW_NUMBER() โ Adding Row Logic
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY order_date DESC) as rn
FROM orders
) sub
WHERE rn = 1;
Used for deduplication, rankings, or selecting the latest record per group.
Credits: https://whatsapp.com/channel/0029VaGgzAk72WTmQFERKh02
React โค๏ธ for more
The Learning Trap: What Most Beginners Fall Into
When starting out, it's common to feel like you need to master every possible SQL concept. You binge YouTube videos, tutorials, and courses, yet still feel lost in interviews or when given a real dataset.
Common traps:
- Complex subqueries
- Advanced CTEs
- Recursive queries
- 100+ tutorials watched
- 0 practical experience
Reality Check: What You'll Actually Use 75% of the Time
Most data analytics roles (especially entry-level) require clarity, speed, and confidence with core SQL operations. Hereโs what covers most daily work:
1. SELECT, FROM, WHERE โ The Foundation
SELECT name, age
FROM employees
WHERE department = 'Finance';
This is how almost every query begins. Whether exploring a dataset or building a dashboard, these are always in use.
2. JOINs โ Combining Data From Multiple Tables
SELECT e.name, d.department_name
FROM employees e
JOIN departments d ON e.department_id = d.id;
Youโll often join tables like employee data with department, customer orders with payments, etc.
3. GROUP BY โ Summarizing Data
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;
Used to get summaries by categories like sales per region or users by plan.
4. ORDER BY โ Sorting Results
SELECT name, salary
FROM employees
ORDER BY salary DESC;
Helps sort output for dashboards or reports.
5. Aggregations โ Simple But Powerful
Common functions: COUNT(), SUM(), AVG(), MIN(), MAX()
SELECT AVG(salary)
FROM employees
WHERE department = 'IT';
Gives quick insights like average deal size or total revenue.
6. ROW_NUMBER() โ Adding Row Logic
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY order_date DESC) as rn
FROM orders
) sub
WHERE rn = 1;
Used for deduplication, rankings, or selecting the latest record per group.
Credits: https://whatsapp.com/channel/0029VaGgzAk72WTmQFERKh02
React โค๏ธ for more
โค4
๐ฆ๐ค๐ ๐ ๐๐๐-๐๐ป๐ผ๐ ๐๐ถ๐ณ๐ณ๐ฒ๐ฟ๐ฒ๐ป๐ฐ๐ฒ๐ ๐
Whether you're writing daily queries or preparing for interviews, understanding these subtle SQL differences can make a big impact on both performance and accuracy.
๐ง Hereโs a powerful visual that compares the most commonly misunderstood SQL concepts โ side by side.
๐ ๐๐ผ๐๐ฒ๐ฟ๐ฒ๐ฑ ๐ถ๐ป ๐๐ต๐ถ๐ ๐๐ป๐ฎ๐ฝ๐๐ต๐ผ๐:
๐น RANK() vs DENSE_RANK()
๐น HAVING vs WHERE
๐น UNION vs UNION ALL
๐น JOIN vs UNION
๐น CTE vs TEMP TABLE
๐น SUBQUERY vs CTE
๐น ISNULL vs COALESCE
๐น DELETE vs DROP
๐น INTERSECT vs INNER JOIN
๐น EXCEPT vs NOT IN
React โฅ๏ธ for detailed explanation
Whether you're writing daily queries or preparing for interviews, understanding these subtle SQL differences can make a big impact on both performance and accuracy.
๐ง Hereโs a powerful visual that compares the most commonly misunderstood SQL concepts โ side by side.
๐ ๐๐ผ๐๐ฒ๐ฟ๐ฒ๐ฑ ๐ถ๐ป ๐๐ต๐ถ๐ ๐๐ป๐ฎ๐ฝ๐๐ต๐ผ๐:
๐น RANK() vs DENSE_RANK()
๐น HAVING vs WHERE
๐น UNION vs UNION ALL
๐น JOIN vs UNION
๐น CTE vs TEMP TABLE
๐น SUBQUERY vs CTE
๐น ISNULL vs COALESCE
๐น DELETE vs DROP
๐น INTERSECT vs INNER JOIN
๐น EXCEPT vs NOT IN
React โฅ๏ธ for detailed explanation
โค11
โ
50 Must-Know SQL Concepts for Interviews ๐พ๐
๐ SQL Basics
1. What is SQL
2. Types of SQL commands (DDL, DML, DCL, TCL)
3. Database vs Table
4. Primary Key & Foreign Key
5. NULL vs NOT NULL
๐ Data Retrieval
6. SELECT statement
7. WHERE clause
8. DISTINCT keyword
9. ORDER BY clause
10. LIMIT / TOP
๐ Filtering & Conditions
11. LIKE, BETWEEN, IN
12. IS NULL & IS NOT NULL
13. AND, OR, NOT
14. CASE statements
15. Aliases using AS
๐ Joins (Very Important)
16. INNER JOIN
17. LEFT JOIN
18. RIGHT JOIN
19. FULL OUTER JOIN
20. SELF JOIN
๐ Aggregation & Grouping
21. COUNT(), SUM(), AVG()
22. MIN(), MAX()
23. GROUP BY clause
24. HAVING vs WHERE
25. GROUP BY with multiple columns
๐ Subqueries & Nested Queries
26. Scalar subqueries
27. Correlated subqueries
28. IN vs EXISTS
29. Using subqueries in SELECT
30. CTE (Common Table Expressions)
๐ Modifying Data
31. INSERT INTO
32. UPDATE
33. DELETE
34. UPSERT (MERGE)
35. TRUNCATE vs DELETE
๐ Constraints & Indexing
36. UNIQUE constraint
37. CHECK constraint
38. DEFAULT values
39. Indexes โ clustered vs non-clustered
40. AUTO_INCREMENT / SERIAL
๐ Views & Stored Procedures
41. Creating and using Views
42. Stored Procedures basics
43. Functions vs Procedures
44. Triggers
45. Transactions (COMMIT, ROLLBACK)
๐ Optimization & Tools
46. EXPLAIN or Query Plan
47. Avoiding SELECT *
48. Normalization
49. Denormalization
50. Popular SQL platforms (MySQL, PostgreSQL, MS SQL Server)
SQL Resources: https://whatsapp.com/channel/0029VanC5rODzgT6TiTGoa1v
๐ฌ Tap โค๏ธ if you found this helpful!
๐ SQL Basics
1. What is SQL
2. Types of SQL commands (DDL, DML, DCL, TCL)
3. Database vs Table
4. Primary Key & Foreign Key
5. NULL vs NOT NULL
๐ Data Retrieval
6. SELECT statement
7. WHERE clause
8. DISTINCT keyword
9. ORDER BY clause
10. LIMIT / TOP
๐ Filtering & Conditions
11. LIKE, BETWEEN, IN
12. IS NULL & IS NOT NULL
13. AND, OR, NOT
14. CASE statements
15. Aliases using AS
๐ Joins (Very Important)
16. INNER JOIN
17. LEFT JOIN
18. RIGHT JOIN
19. FULL OUTER JOIN
20. SELF JOIN
๐ Aggregation & Grouping
21. COUNT(), SUM(), AVG()
22. MIN(), MAX()
23. GROUP BY clause
24. HAVING vs WHERE
25. GROUP BY with multiple columns
๐ Subqueries & Nested Queries
26. Scalar subqueries
27. Correlated subqueries
28. IN vs EXISTS
29. Using subqueries in SELECT
30. CTE (Common Table Expressions)
๐ Modifying Data
31. INSERT INTO
32. UPDATE
33. DELETE
34. UPSERT (MERGE)
35. TRUNCATE vs DELETE
๐ Constraints & Indexing
36. UNIQUE constraint
37. CHECK constraint
38. DEFAULT values
39. Indexes โ clustered vs non-clustered
40. AUTO_INCREMENT / SERIAL
๐ Views & Stored Procedures
41. Creating and using Views
42. Stored Procedures basics
43. Functions vs Procedures
44. Triggers
45. Transactions (COMMIT, ROLLBACK)
๐ Optimization & Tools
46. EXPLAIN or Query Plan
47. Avoiding SELECT *
48. Normalization
49. Denormalization
50. Popular SQL platforms (MySQL, PostgreSQL, MS SQL Server)
SQL Resources: https://whatsapp.com/channel/0029VanC5rODzgT6TiTGoa1v
๐ฌ Tap โค๏ธ if you found this helpful!
โค10๐1
โ
Top 10 SQL Interview Questions
1๏ธโฃ What is SQL and its types?
SQL (Structured Query Language) is used to manage and manipulate databases.
Types: DDL, DML, DCL, TCL
Example:
2๏ธโฃ Explain SQL constraints.
Constraints ensure data integrity:
โฆ PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK
3๏ธโฃ What is normalization?
It's organizing data to reduce redundancy and improve integrity (1NF, 2NF, 3NFโฆ).
4๏ธโฃ Explain different types of JOINs with example.
โฆ INNER JOIN: Returns matching rows
โฆ LEFT JOIN: All from left + matching right rows
โฆ RIGHT JOIN: All from right + matching left rows
โฆ FULL JOIN: All rows from both tables
5๏ธโฃ What is a subquery? Give example.
A query inside another query:
6๏ธโฃ How to optimize slow queries?
Use indexes, avoid SELECT *, use joins wisely, reduce nested queries.
7๏ธโฃ What are aggregate functions? List examples.
Functions that perform a calculation on a set of values:
8๏ธโฃ Explain SQL injection and prevention.
A security vulnerability to manipulate queries. Prevent via parameterized queries, input validation.
9๏ธโฃ How to find Nth highest salary without TOP/LIMIT?
๐ What is a stored procedure?
A precompiled SQL program that can be executed to perform operations repeatedly.
๐ฅ React for more! โค๏ธ
1๏ธโฃ What is SQL and its types?
SQL (Structured Query Language) is used to manage and manipulate databases.
Types: DDL, DML, DCL, TCL
Example:
CREATE, SELECT, GRANT, COMMIT2๏ธโฃ Explain SQL constraints.
Constraints ensure data integrity:
โฆ PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK
3๏ธโฃ What is normalization?
It's organizing data to reduce redundancy and improve integrity (1NF, 2NF, 3NFโฆ).
4๏ธโฃ Explain different types of JOINs with example.
โฆ INNER JOIN: Returns matching rows
โฆ LEFT JOIN: All from left + matching right rows
โฆ RIGHT JOIN: All from right + matching left rows
โฆ FULL JOIN: All rows from both tables
5๏ธโฃ What is a subquery? Give example.
A query inside another query:
SELECT name FROM employees
WHERE department_id = (SELECT id FROM departments WHERE name='Sales');
6๏ธโฃ How to optimize slow queries?
Use indexes, avoid SELECT *, use joins wisely, reduce nested queries.
7๏ธโฃ What are aggregate functions? List examples.
Functions that perform a calculation on a set of values:
SUM(), COUNT(), AVG(), MIN(), MAX()8๏ธโฃ Explain SQL injection and prevention.
A security vulnerability to manipulate queries. Prevent via parameterized queries, input validation.
9๏ธโฃ How to find Nth highest salary without TOP/LIMIT?
SELECT DISTINCT salary FROM employees e1
WHERE N-1 = (SELECT COUNT(DISTINCT salary) FROM employees e2 WHERE e2.salary > e1.salary);
๐ What is a stored procedure?
A precompiled SQL program that can be executed to perform operations repeatedly.
๐ฅ React for more! โค๏ธ
โค7
SQL Cheatsheet ๐
This SQL cheatsheet is designed to be your quick reference guide for SQL programming. Whether youโre a beginner learning how to query databases or an experienced developer looking for a handy resource, this cheatsheet covers essential SQL topics.
1. Database Basics
-
-
2. Tables
- Create Table:
- Drop Table:
- Alter Table:
3. Insert Data
-
4. Select Queries
- Basic Select:
- Select Specific Columns:
- Select with Condition:
5. Update Data
-
6. Delete Data
-
7. Joins
- Inner Join:
- Left Join:
- Right Join:
8. Aggregations
- Count:
- Sum:
- Group By:
9. Sorting & Limiting
- Order By:
- Limit Results:
10. Indexes
- Create Index:
- Drop Index:
11. Subqueries
-
12. Views
- Create View:
- Drop View:
This SQL cheatsheet is designed to be your quick reference guide for SQL programming. Whether youโre a beginner learning how to query databases or an experienced developer looking for a handy resource, this cheatsheet covers essential SQL topics.
1. Database Basics
-
CREATE DATABASE db_name;-
USE db_name;2. Tables
- Create Table:
CREATE TABLE table_name (col1 datatype, col2 datatype);- Drop Table:
DROP TABLE table_name;- Alter Table:
ALTER TABLE table_name ADD column_name datatype;3. Insert Data
-
INSERT INTO table_name (col1, col2) VALUES (val1, val2);4. Select Queries
- Basic Select:
SELECT * FROM table_name;- Select Specific Columns:
SELECT col1, col2 FROM table_name;- Select with Condition:
SELECT * FROM table_name WHERE condition;5. Update Data
-
UPDATE table_name SET col1 = value1 WHERE condition;6. Delete Data
-
DELETE FROM table_name WHERE condition;7. Joins
- Inner Join:
SELECT * FROM table1 INNER JOIN table2 ON table1.col = table2.col;- Left Join:
SELECT * FROM table1 LEFT JOIN table2 ON table1.col = table2.col;- Right Join:
SELECT * FROM table1 RIGHT JOIN table2 ON table1.col = table2.col;8. Aggregations
- Count:
SELECT COUNT(*) FROM table_name;- Sum:
SELECT SUM(col) FROM table_name;- Group By:
SELECT col, COUNT(*) FROM table_name GROUP BY col;9. Sorting & Limiting
- Order By:
SELECT * FROM table_name ORDER BY col ASC|DESC;- Limit Results:
SELECT * FROM table_name LIMIT n;10. Indexes
- Create Index:
CREATE INDEX idx_name ON table_name (col);- Drop Index:
DROP INDEX idx_name;11. Subqueries
-
SELECT * FROM table_name WHERE col IN (SELECT col FROM other_table);12. Views
- Create View:
CREATE VIEW view_name AS SELECT * FROM table_name;- Drop View:
DROP VIEW view_name;โค9
โ
Top 10 SQL Interview Questions ๐ฅ
1๏ธโฃ What is a table and a field in SQL?
โฆ Table: Organized data in rows and columns
โฆ Field: A column representing data attribute
2๏ธโฃ Describe the SELECT statement.
โฆ Fetch data from one or more tables
โฆ Use WHERE to filter, ORDER BY to sort
3๏ธโฃ Explain SQL constraints.
โฆ Rules for data integrity: PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK
4๏ธโฃ What is normalization?
โฆ Process to reduce data redundancy & improve integrity (1NF, 2NF, 3NFโฆ)
5๏ธโฃ Explain different JOIN types with examples.
โฆ INNER, LEFT, RIGHT, FULL JOIN: Various ways to combine tables based on matching rows
6๏ธโฃ What is a subquery? Give example.
โฆ Query inside another query:
7๏ธโฃ How to optimize slow queries?
โฆ Use indexes, avoid SELECT *, simplify joins, reduce nested queries
8๏ธโฃ What are aggregate functions? Examples?
โฆ Perform calculations on sets: SUM(), COUNT(), AVG(), MIN(), MAX()
9๏ธโฃ What is SQL injection? How to prevent it?
โฆ Security risk manipulating queries
โฆ Prevent: parameterized queries, input validation
๐ How to find the Nth highest salary without TOP/LIMIT?
๐ฅ Double Tap โค๏ธ For More!
1๏ธโฃ What is a table and a field in SQL?
โฆ Table: Organized data in rows and columns
โฆ Field: A column representing data attribute
2๏ธโฃ Describe the SELECT statement.
โฆ Fetch data from one or more tables
โฆ Use WHERE to filter, ORDER BY to sort
3๏ธโฃ Explain SQL constraints.
โฆ Rules for data integrity: PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK
4๏ธโฃ What is normalization?
โฆ Process to reduce data redundancy & improve integrity (1NF, 2NF, 3NFโฆ)
5๏ธโฃ Explain different JOIN types with examples.
โฆ INNER, LEFT, RIGHT, FULL JOIN: Various ways to combine tables based on matching rows
6๏ธโฃ What is a subquery? Give example.
โฆ Query inside another query:
SELECT name FROM employees
WHERE department_id = (SELECT id FROM departments WHERE name='Sales');
7๏ธโฃ How to optimize slow queries?
โฆ Use indexes, avoid SELECT *, simplify joins, reduce nested queries
8๏ธโฃ What are aggregate functions? Examples?
โฆ Perform calculations on sets: SUM(), COUNT(), AVG(), MIN(), MAX()
9๏ธโฃ What is SQL injection? How to prevent it?
โฆ Security risk manipulating queries
โฆ Prevent: parameterized queries, input validation
๐ How to find the Nth highest salary without TOP/LIMIT?
SELECT DISTINCT salary FROM employees e1
WHERE N-1 = (SELECT COUNT(DISTINCT salary) FROM employees e2 WHERE e2.salary > e1.salary);
๐ฅ Double Tap โค๏ธ For More!
โค14
SQL From Basic to Advanced level
Basic SQL is ONLY 7 commands:
- SELECT
- FROM
- WHERE (also use SQL comparison operators such as =, <=, >=, <> etc.)
- ORDER BY
- Aggregate functions such as SUM, AVERAGE, COUNT etc.
- GROUP BY
- CREATE, INSERT, DELETE, etc.
You can do all this in just one morning.
Once you know these, take the next step and learn commands like:
- LEFT JOIN
- INNER JOIN
- LIKE
- IN
- CASE WHEN
- HAVING (undertstand how it's different from GROUP BY)
- UNION ALL
This should take another day.
Once both basic and intermediate are done, start learning more advanced SQL concepts such as:
- Subqueries (when to use subqueries vs CTE?)
- CTEs (WITH AS)
- Stored Procedures
- Triggers
- Window functions (LEAD, LAG, PARTITION BY, RANK, DENSE RANK)
These can be done in a couple of days.
Learning these concepts is NOT hard at all
- what takes time is practice and knowing what command to use when. How do you master that?
- First, create a basic SQL project
- Then, work on an intermediate SQL project (search online) -
Lastly, create something advanced on SQL with many CTEs, subqueries, stored procedures and triggers etc.
This is ALL you need to become a badass in SQL, and trust me when I say this, it is not rocket science. It's just logic.
Remember that practice is the key here. It will be more clear and perfect with the continous practice
Best telegram channel to learn SQL: https://t.iss.one/sqlanalyst
Data Analyst Jobs๐
https://t.iss.one/jobs_SQL
Join @free4unow_backup for more free resources.
Like this post if it helps ๐โค๏ธ
ENJOY LEARNING ๐๐
Basic SQL is ONLY 7 commands:
- SELECT
- FROM
- WHERE (also use SQL comparison operators such as =, <=, >=, <> etc.)
- ORDER BY
- Aggregate functions such as SUM, AVERAGE, COUNT etc.
- GROUP BY
- CREATE, INSERT, DELETE, etc.
You can do all this in just one morning.
Once you know these, take the next step and learn commands like:
- LEFT JOIN
- INNER JOIN
- LIKE
- IN
- CASE WHEN
- HAVING (undertstand how it's different from GROUP BY)
- UNION ALL
This should take another day.
Once both basic and intermediate are done, start learning more advanced SQL concepts such as:
- Subqueries (when to use subqueries vs CTE?)
- CTEs (WITH AS)
- Stored Procedures
- Triggers
- Window functions (LEAD, LAG, PARTITION BY, RANK, DENSE RANK)
These can be done in a couple of days.
Learning these concepts is NOT hard at all
- what takes time is practice and knowing what command to use when. How do you master that?
- First, create a basic SQL project
- Then, work on an intermediate SQL project (search online) -
Lastly, create something advanced on SQL with many CTEs, subqueries, stored procedures and triggers etc.
This is ALL you need to become a badass in SQL, and trust me when I say this, it is not rocket science. It's just logic.
Remember that practice is the key here. It will be more clear and perfect with the continous practice
Best telegram channel to learn SQL: https://t.iss.one/sqlanalyst
Data Analyst Jobs๐
https://t.iss.one/jobs_SQL
Join @free4unow_backup for more free resources.
Like this post if it helps ๐โค๏ธ
ENJOY LEARNING ๐๐
โค6
โ
Advanced SQL Interview Questions with Answers ๐ผ๐ง
1๏ธโฃ What are Window Functions in SQL?
Answer: They perform calculations across rows related to the current row without collapsing the result set.
Example:
2๏ธโฃ Difference between RANK(), DENSE_RANK(), and ROW_NUMBER()?
โ RANK(): skips numbers for ties
โ DENSE_RANK(): doesn't skip numbers
โ ROW_NUMBER(): gives unique numbers to each row
Use: Sorting, pagination, leaderboard design
3๏ธโฃ What is the use of COALESCE()?
Answer: Returns the first non-null value in a list.
Example:
4๏ธโฃ How does CASE work in SQL?
Answer: It's used for conditional logic.
Example:
5๏ธโฃ Explain CTE (Common Table Expression).
Answer: Temporary result set for readable and reusable queries.
Example:
6๏ธโฃ What is the difference between EXISTS and IN?
โ EXISTS: stops after finding the first match (more efficient)
โ IN: compares a list of values
Use EXISTS for subqueries when checking existence
7๏ธโฃ What are Indexes in SQL?
Answer: They improve read performance but slow down write operations.
โ Types: Single-column, Composite, Unique
8๏ธโฃ How to optimize SQL queries?
โ Use proper indexes
โ Avoid SELECT *
โ Use WHERE filters early
โ Analyze query plan
๐ฌ Double Tap โค๏ธ For More!
1๏ธโฃ What are Window Functions in SQL?
Answer: They perform calculations across rows related to the current row without collapsing the result set.
Example:
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) AS rank FROM employees;
2๏ธโฃ Difference between RANK(), DENSE_RANK(), and ROW_NUMBER()?
โ RANK(): skips numbers for ties
โ DENSE_RANK(): doesn't skip numbers
โ ROW_NUMBER(): gives unique numbers to each row
Use: Sorting, pagination, leaderboard design
3๏ธโฃ What is the use of COALESCE()?
Answer: Returns the first non-null value in a list.
Example:
SELECT name, COALESCE(nickname, 'No Nick') FROM users;
4๏ธโฃ How does CASE work in SQL?
Answer: It's used for conditional logic.
Example:
SELECT name,
CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 80 THEN 'B'
ELSE 'C'
END AS grade
FROM students;
5๏ธโฃ Explain CTE (Common Table Expression).
Answer: Temporary result set for readable and reusable queries.
Example:
WITH TopSales AS (
SELECT emp_id, SUM(sales) AS total_sales
FROM sales
GROUP BY emp_id
)
SELECT * FROM TopSales WHERE total_sales > 5000;
6๏ธโฃ What is the difference between EXISTS and IN?
โ EXISTS: stops after finding the first match (more efficient)
โ IN: compares a list of values
Use EXISTS for subqueries when checking existence
7๏ธโฃ What are Indexes in SQL?
Answer: They improve read performance but slow down write operations.
โ Types: Single-column, Composite, Unique
8๏ธโฃ How to optimize SQL queries?
โ Use proper indexes
โ Avoid SELECT *
โ Use WHERE filters early
โ Analyze query plan
๐ฌ Double Tap โค๏ธ For More!
โค15๐2
โ
Advanced SQL Practice Questions with Answers ๐ง ๐
1๏ธโฃ Get the second highest salary from the employees table.
2๏ธโฃ List employees who earn more than the average salary.
3๏ธโฃ Show department-wise highest paid employee.
4๏ธโฃ Display total sales made by each employee in 2023.
5๏ธโฃ Retrieve products with price above average in their category.
6๏ธโฃ Identify duplicate emails in the users table.
7๏ธโฃ Rank customers based on total purchase amount.
๐ฌ Double Tap โค๏ธ For More!
1๏ธโฃ Get the second highest salary from the employees table.
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
2๏ธโฃ List employees who earn more than the average salary.
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
3๏ธโฃ Show department-wise highest paid employee.
SELECT department, name, salary
FROM (
SELECT *,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk
FROM employees
) AS ranked
WHERE rnk = 1;
4๏ธโฃ Display total sales made by each employee in 2023.
SELECT emp_id, SUM(amount) AS total_sales
FROM sales
WHERE YEAR(sale_date) = 2023
GROUP BY emp_id;
5๏ธโฃ Retrieve products with price above average in their category.
SELECT p.name, p.category, p.price
FROM products p
WHERE price > (
SELECT AVG(price)
FROM products
WHERE category = p.category
);
6๏ธโฃ Identify duplicate emails in the users table.
SELECT email, COUNT(*)
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
7๏ธโฃ Rank customers based on total purchase amount.
SELECT customer_id,
SUM(amount) AS total_spent,
RANK() OVER (ORDER BY SUM(amount) DESC) AS rank
FROM orders
GROUP BY customer_id;
๐ฌ Double Tap โค๏ธ For More!
โค23๐1
๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ: You have 2 minutes to solve this SQL query.
Retrieve the department name and the highest salary in each department from the employees table, but only for departments where the highest salary is greater than $70,000.
๐ ๐ฒ: Challenge accepted!
SELECT department, MAX(salary) AS highest_salary
FROM employees
GROUP BY department
HAVING MAX(salary) > 70000;
I used GROUP BY to group employees by department, MAX() to get the highest salary, and HAVING to filter the result based on the condition that the highest salary exceeds $70,000. This solution effectively shows my understanding of aggregation functions and how to apply conditions on the result of those aggregations.
๐ง๐ถ๐ฝ ๐ณ๐ผ๐ฟ ๐ฆ๐ค๐ ๐๐ผ๐ฏ ๐ฆ๐ฒ๐ฒ๐ธ๐ฒ๐ฟ๐:
It's not about writing complex queries; it's about writing clean, efficient, and scalable code. Focus on mastering subqueries, joins, and aggregation functions to stand out!
React with โค๏ธ for more
Retrieve the department name and the highest salary in each department from the employees table, but only for departments where the highest salary is greater than $70,000.
๐ ๐ฒ: Challenge accepted!
SELECT department, MAX(salary) AS highest_salary
FROM employees
GROUP BY department
HAVING MAX(salary) > 70000;
I used GROUP BY to group employees by department, MAX() to get the highest salary, and HAVING to filter the result based on the condition that the highest salary exceeds $70,000. This solution effectively shows my understanding of aggregation functions and how to apply conditions on the result of those aggregations.
๐ง๐ถ๐ฝ ๐ณ๐ผ๐ฟ ๐ฆ๐ค๐ ๐๐ผ๐ฏ ๐ฆ๐ฒ๐ฒ๐ธ๐ฒ๐ฟ๐:
It's not about writing complex queries; it's about writing clean, efficient, and scalable code. Focus on mastering subqueries, joins, and aggregation functions to stand out!
React with โค๏ธ for more
โค14๐2๐1๐ค1
๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ: Write a query to get the names of all employees along with their department names. If an employee is not assigned to a department, still include them.
๐ ๐ฒ: Hereโs my SQL solution using a LEFT JOIN:
โ Why it works:
โ
โ It joins the
โ Clean, readable, and interview-ready!
๐ Bonus Insight:
Always understand the difference between
๐ฌ Tap โค๏ธ if this helped you!
๐ ๐ฒ: Hereโs my SQL solution using a LEFT JOIN:
SELECT e.name AS employee_name, d.name AS department_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.id;
โ Why it works:
โ
LEFT JOIN ensures all employees are shown, even those without departments. โ It joins the
employees and departments tables on department_id. โ Clean, readable, and interview-ready!
๐ Bonus Insight:
Always understand the difference between
INNER JOIN, LEFT JOIN, and RIGHT JOIN. In real-world databases, missing data is common โ use joins wisely to handle it.๐ฌ Tap โค๏ธ if this helped you!
โค10
โ
SQL Mini-Challenge! ๐๐ป
๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ: List all employees and their managers. If an employee doesnโt have a manager, still include them.
๐ ๐ฒ: Using a self-join with LEFT JOIN:
โ Why it works:
โ LEFT JOIN ensures employees without managers are still included.
โ Self-join allows referencing the same table for managers.
โ Simple and clean solution for interviews.
๐ Bonus Tip:
Always consider null values in joins; LEFT JOIN helps preserve the main table rows even if the related data is missing.
๐ฌ Tap โค๏ธ if this helped you!
๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ: List all employees and their managers. If an employee doesnโt have a manager, still include them.
๐ ๐ฒ: Using a self-join with LEFT JOIN:
SELECT e.name AS employee_name, m.name AS manager_name
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;
โ Why it works:
โ LEFT JOIN ensures employees without managers are still included.
โ Self-join allows referencing the same table for managers.
โ Simple and clean solution for interviews.
๐ Bonus Tip:
Always consider null values in joins; LEFT JOIN helps preserve the main table rows even if the related data is missing.
๐ฌ Tap โค๏ธ if this helped you!
โค18
โ
SQL Scenario-Based Question & Answer ๐ป๐
Scenario:
You have two tables:
Employees
Departments
Question:
Write a query to display all employees with their department name. If an employee doesn't belong to any department, show "Not Assigned" instead.
Answer:
Explanation:
โฆ LEFT JOIN ensures all employees are included, even those without a matching dept_id (like Mary).
โฆ COALESCE picks the first non-NULL value: dept_name if available, otherwise "Not Assigned".
โฆ This handles NULLs gracefully while keeping the full employee list intact.
Result:
๐ฌ Double Tap โค๏ธ if this helped you!
Scenario:
You have two tables:
Employees
| emp_id | name | dept_id | salary |
| ------ | ----- | ------- | ------ |
| 1 | John | 10 | 5000 |
| 2 | Alice | 20 | 6000 |
| 3 | Bob | 10 | 4500 |
| 4 | Mary | NULL | 7000 |
Departments
| dept_id | dept_name |
| ------- | --------- |
| 10 | Sales |
| 20 | Marketing |
| 30 | HR |
Question:
Write a query to display all employees with their department name. If an employee doesn't belong to any department, show "Not Assigned" instead.
Answer:
SELECT e.name AS employee_name,
COALESCE(d.dept_name, 'Not Assigned') AS department_name
FROM Employees e
LEFT JOIN Departments d
ON e.dept_id = d.dept_id;
Explanation:
โฆ LEFT JOIN ensures all employees are included, even those without a matching dept_id (like Mary).
โฆ COALESCE picks the first non-NULL value: dept_name if available, otherwise "Not Assigned".
โฆ This handles NULLs gracefully while keeping the full employee list intact.
Result:
| employee_name | department_name |
| ------------- | --------------- |
| John | Sales |
| Alice | Marketing |
| Bob | Sales |
| Mary | Not Assigned |
๐ฌ Double Tap โค๏ธ if this helped you!
โค24๐2
โ
SQL Interview Challenge! ๐ง ๐ป
๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ: Retrieve all employees along with their department names. Only include employees who belong to a department.
๐ ๐ฒ: Using INNER JOIN:
โ Why it works:
โ INNER JOIN returns only rows with matching values in both tables based on the ON condition, excluding employees without a dept_id match (or vice versa).
โ This ensures we get complete, valid pairsโperfect for reports focusing on assigned staff, and it's efficient for large datasets in 2025's analytics tools.
๐ฌ Tap โค๏ธ if this helped you!
๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ: Retrieve all employees along with their department names. Only include employees who belong to a department.
๐ ๐ฒ: Using INNER JOIN:
SELECT e.name AS employee_name,
d.dept_name AS department_name
FROM employees e
INNER JOIN departments d
ON e.dept_id = d.dept_id;
โ Why it works:
โ INNER JOIN returns only rows with matching values in both tables based on the ON condition, excluding employees without a dept_id match (or vice versa).
โ This ensures we get complete, valid pairsโperfect for reports focusing on assigned staff, and it's efficient for large datasets in 2025's analytics tools.
๐ฌ Tap โค๏ธ if this helped you!
โค6
โ
SQL Interview Challenge! ๐๐ง
๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ: Find the average salary of employees in each department.
๐ ๐ฒ: Using GROUP BY and AVG():
SELECT d.dept_name,
AVG(e.salary) AS avg_salary
FROM employees e
INNER JOIN departments d
ON e.dept_id = d.dept_id
GROUP BY d.dept_name;
โ Why it works:
โ AVG() computes the mean salary per group, handling decimals nicely.
โ GROUP BY clusters rows by department name for department-level aggregates.
โ INNER JOIN links employee salaries to department names only for matching recordsโadd ORDER BY avg_salary DESC for ranked insights!
๐ฌ Tap โค๏ธ for more!
๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ: Find the average salary of employees in each department.
๐ ๐ฒ: Using GROUP BY and AVG():
SELECT d.dept_name,
AVG(e.salary) AS avg_salary
FROM employees e
INNER JOIN departments d
ON e.dept_id = d.dept_id
GROUP BY d.dept_name;
โ Why it works:
โ AVG() computes the mean salary per group, handling decimals nicely.
โ GROUP BY clusters rows by department name for department-level aggregates.
โ INNER JOIN links employee salaries to department names only for matching recordsโadd ORDER BY avg_salary DESC for ranked insights!
๐ฌ Tap โค๏ธ for more!
โค9๐1
โ
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