SQL Programming Resources
74.9K subscribers
499 photos
13 files
443 links
Find top SQL resources from global universities, cool projects, and learning materials for data analytics.

Admin: @coderfun

Useful links: heylink.me/DataAnalytics

Promotions: @love_data
Download Telegram
โœ… 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!
โค19๐Ÿ˜2
โœ… 20 Medium-Level SQL Interview Questions (with Detailed Answers)

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! ๐Ÿ˜‰
โค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!
โค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
โค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
โค11
๐Ÿ“‰ 20 High-Income Skills to Learn...
โค5
โœ… 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!
โค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: CREATE, SELECT, GRANT, COMMIT

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:
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
- 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:
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 ๐Ÿ‘๐Ÿ‘
โค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:
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.
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
โค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:

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:

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
| 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:
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!
โค9๐Ÿ‘1
โœ… Interviewer: Count the number of employees in each department. ๐Ÿ“Š

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