π ππ»ππ²πΏππΆπ²ππ²πΏ: 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
π Roadmap to Master SQL in 30 Days! ποΈπ§
π Week 1: SQL Basics
πΉ Day 1β2: What is SQL? DBMS vs RDBMS
πΉ Day 3β5: SELECT, WHERE, ORDER BY, LIMIT
πΉ Day 6β7: Filtering with AND, OR, IN, NOT, BETWEEN
π Week 2: Intermediate SQL
πΉ Day 8β9: Functions (COUNT, SUM, AVG, MIN, MAX)
πΉ Day 10β11: GROUP BY, HAVING
πΉ Day 12β14: JOINS (INNER, LEFT, RIGHT, FULL)
π Week 3: Advanced SQL
πΉ Day 15β17: Subqueries Nested Queries
πΉ Day 18β20: CASE statements, COALESCE, NULL handling
πΉ Day 21β22: Window Functions (ROW_NUMBER, RANK, PARTITION BY)
π Week 4: Practical Use Projects
πΉ Day 23β25: Views, Indexes, Stored Procedures (basic)
πΉ Day 26β28: Real-world project (e.g., Sales dashboard with queries)
πΉ Day 29β30: Practice on platforms like LeetCode, HackerRank, Mode
π‘ Bonus Tools:
β’ MySQL / PostgreSQL / SQLite
β’ DB Fiddle / SQLZoo / W3Schools
β’ Power BI / Excel for data connection
π¬ Tap β€οΈ for more!
π Week 1: SQL Basics
πΉ Day 1β2: What is SQL? DBMS vs RDBMS
πΉ Day 3β5: SELECT, WHERE, ORDER BY, LIMIT
πΉ Day 6β7: Filtering with AND, OR, IN, NOT, BETWEEN
π Week 2: Intermediate SQL
πΉ Day 8β9: Functions (COUNT, SUM, AVG, MIN, MAX)
πΉ Day 10β11: GROUP BY, HAVING
πΉ Day 12β14: JOINS (INNER, LEFT, RIGHT, FULL)
π Week 3: Advanced SQL
πΉ Day 15β17: Subqueries Nested Queries
πΉ Day 18β20: CASE statements, COALESCE, NULL handling
πΉ Day 21β22: Window Functions (ROW_NUMBER, RANK, PARTITION BY)
π Week 4: Practical Use Projects
πΉ Day 23β25: Views, Indexes, Stored Procedures (basic)
πΉ Day 26β28: Real-world project (e.g., Sales dashboard with queries)
πΉ Day 29β30: Practice on platforms like LeetCode, HackerRank, Mode
π‘ Bonus Tools:
β’ MySQL / PostgreSQL / SQLite
β’ DB Fiddle / SQLZoo / W3Schools
β’ Power BI / Excel for data connection
π¬ Tap β€οΈ for more!
β€28π1
Today, let's start with the complete SQL series starting with the basics:
β SQL Basics: Part-1 π§ πΎ
SQL (Structured Query Language) is the standard language used to communicate with databases.
You use it to store, retrieve, update, and delete data in a structured format.
π οΈ Why Learn SQL?
β’ Itβs used in data analytics, development, and business intelligence.
β’ Works with tools like Power BI, Excel, Python, Tableau, etc.
β’ Helps in querying and analyzing large datasets efficiently.
π Key Concepts:
1οΈβ£ DBMS (Database Management System)
β’ A software to manage databases.
β’ Stores data in files or documents.
β’ Examples: Microsoft Access, MongoDB (non-relational).
β’ No strict structure or rules.
2οΈβ£ RDBMS (Relational Database Management System)
β’ Stores data in tables with rows and columns.
β’ Ensures data consistency using relationships.
β’ Follows ACID properties (Atomicity, Consistency, Isolation, Durability).
β’ Examples: MySQL, PostgreSQL, Oracle, SQL Server.
ποΈ Simple Table Example (in RDBMS):
Customers Table
β SQL Basics: Part-1 π§ πΎ
SQL (Structured Query Language) is the standard language used to communicate with databases.
You use it to store, retrieve, update, and delete data in a structured format.
π οΈ Why Learn SQL?
β’ Itβs used in data analytics, development, and business intelligence.
β’ Works with tools like Power BI, Excel, Python, Tableau, etc.
β’ Helps in querying and analyzing large datasets efficiently.
π Key Concepts:
1οΈβ£ DBMS (Database Management System)
β’ A software to manage databases.
β’ Stores data in files or documents.
β’ Examples: Microsoft Access, MongoDB (non-relational).
β’ No strict structure or rules.
2οΈβ£ RDBMS (Relational Database Management System)
β’ Stores data in tables with rows and columns.
β’ Ensures data consistency using relationships.
β’ Follows ACID properties (Atomicity, Consistency, Isolation, Durability).
β’ Examples: MySQL, PostgreSQL, Oracle, SQL Server.
ποΈ Simple Table Example (in RDBMS):
Customers Table
β€8π2
You can use SQL to:
β‘οΈ This returns all records from the table. (Note: The
π Real-life Analogy:
Think of RDBMS as Excel β rows are records, columns are fields.
SQL is the language to ask questions like:
- Who are my customers from Delhi?
- What is the total number of orders last month?
π― Task for You Today:
β Install MySQL or use an online SQL editor (like SQLFiddle)
β Learn basic syntax: SELECT, FROM
β Try creating a sample table and selecting data
π¬ Tap β€οΈ for Part-2
SELECT * FROM Customers; β‘οΈ This returns all records from the table. (Note: The
* here is a wildcard meaning "all columns").π Real-life Analogy:
Think of RDBMS as Excel β rows are records, columns are fields.
SQL is the language to ask questions like:
- Who are my customers from Delhi?
- What is the total number of orders last month?
π― Task for You Today:
β Install MySQL or use an online SQL editor (like SQLFiddle)
β Learn basic syntax: SELECT, FROM
β Try creating a sample table and selecting data
π¬ Tap β€οΈ for Part-2
β€19π1
β
SQL Basics: Part-2 (SQL Commands) π§ πΎ
1οΈβ£ SELECT β Pull data from a table
_Syntax:_
_Example:_
To get _everything_ use:
2οΈβ£ WHERE β Filter specific rows
_Syntax:_
_Example:_
_Operators you can use:_
β’ =, !=, >, <, >=, <=
β’ LIKE (pattern match)
β’ BETWEEN, IN, IS NULL
3οΈβ£ ORDER BY β Sort results
_Syntax:_
_Example:_
4οΈβ£ LIMIT β Restrict number of results
_Syntax:_
_Example:_
π₯ _Quick Practice Task:_
Write a query to:
β’ Get top 10 highest-paid employees in 'Marketing'
β’ Show name, salary, and department
β’ Sort salary high to low:
β SQL Interview QA πΌπ§
Q1. What does the SELECT statement do in SQL?
_Answer:_
It retrieves data from one or more columns in a table.
Q2. How would you fetch all the columns from a table?
_Answer:_
Use SELECT * to get every column.
Q3. Whatβs the difference between WHERE and HAVING?
_Answer:_
β’ WHERE filters rows _before_ grouping
β’ HAVING filters _after_ GROUP BY
You use WHERE with raw data, HAVING with aggregated data.
Q4. Write a query to find all products with price > 500.
_Answer:_
Q5. How do you sort data by two columns?
_Answer:_
Use ORDER BY col1, col2.
Q6. What does LIMIT 1 do in a query?
_Answer:_
It returns only the _first row_ of the result.
Q7. Write a query to get names of top 5 students by marks.
_Answer:_
Q8. Can you use ORDER BY without WHERE?
_Answer:_
Yes. ORDER BY works independently. It sorts all data unless filtered with WHERE.
π‘ _Pro Tip:_
In interviews, they may ask you to _write queries live_ or explain the _output_ of a query. Stay calm, read the structure carefully, and _think in steps_.
DOUBLE TAP β€οΈ FOR MORE
1οΈβ£ SELECT β Pull data from a table
_Syntax:_
SELECT column1, column2 FROM table_name;
_Example:_
SELECT name, city FROM customers;
To get _everything_ use:
SELECT * FROM customers;
2οΈβ£ WHERE β Filter specific rows
_Syntax:_
SELECT columns FROM table_name WHERE condition;
_Example:_
SELECT name FROM customers WHERE city = 'Delhi';
_Operators you can use:_
β’ =, !=, >, <, >=, <=
β’ LIKE (pattern match)
β’ BETWEEN, IN, IS NULL
3οΈβ£ ORDER BY β Sort results
_Syntax:_
SELECT columns FROM table_name ORDER BY column ASC|DESC;
_Example:_
SELECT name, age FROM employees ORDER BY age DESC;
4οΈβ£ LIMIT β Restrict number of results
_Syntax:_
SELECT columns FROM table_name LIMIT number;
_Example:_
SELECT * FROM products LIMIT 5;
π₯ _Quick Practice Task:_
Write a query to:
β’ Get top 10 highest-paid employees in 'Marketing'
β’ Show name, salary, and department
β’ Sort salary high to low:
SELECT name, salary, department
FROM employees
WHERE department = 'Marketing'
ORDER BY salary DESC
LIMIT 10;
β SQL Interview QA πΌπ§
Q1. What does the SELECT statement do in SQL?
_Answer:_
It retrieves data from one or more columns in a table.
SELECT name, city FROM customers;
Q2. How would you fetch all the columns from a table?
_Answer:_
Use SELECT * to get every column.
SELECT * FROM orders;
Q3. Whatβs the difference between WHERE and HAVING?
_Answer:_
β’ WHERE filters rows _before_ grouping
β’ HAVING filters _after_ GROUP BY
You use WHERE with raw data, HAVING with aggregated data.
Q4. Write a query to find all products with price > 500.
_Answer:_
SELECT * FROM products WHERE price > 500;
Q5. How do you sort data by two columns?
_Answer:_
Use ORDER BY col1, col2.
SELECT name, department FROM employees ORDER BY department ASC, name ASC;
Q6. What does LIMIT 1 do in a query?
_Answer:_
It returns only the _first row_ of the result.
SELECT * FROM customers ORDER BY created_at DESC LIMIT 1;
Q7. Write a query to get names of top 5 students by marks.
_Answer:_
SELECT name, marks
FROM students
ORDER BY marks DESC
LIMIT 5;
Q8. Can you use ORDER BY without WHERE?
_Answer:_
Yes. ORDER BY works independently. It sorts all data unless filtered with WHERE.
π‘ _Pro Tip:_
In interviews, they may ask you to _write queries live_ or explain the _output_ of a query. Stay calm, read the structure carefully, and _think in steps_.
DOUBLE TAP β€οΈ FOR MORE
β€14π1
β
SQL Basics: Part-3: Filtering with SQL Operators
Filtering helps you narrow down results based on specific conditions.
Letβs explore some powerful SQL operators:
1οΈβ£ IN β Match multiple values
Syntax:
Example:
Get customers from specific cities:
2οΈβ£ OR β Match any of multiple conditions
Syntax:
Example:
Get employees from HR or Finance:
3οΈβ£ AND β Match all conditions
Syntax:
Example:
Get Sales employees earning more than 60,000:
4οΈβ£ NOT β Exclude specific values or conditions
Syntax:
Example:
Get all products except Electronics:
5οΈβ£ BETWEEN β Match a range of values (inclusive)
Syntax:
Example:
Get employees with salary between 50,000 and 100,000:
π₯ Quick Practice Task:
Write a query to:
β’ Get all employees in 'IT' or 'HR'
β’ Who earn more than 50,000
β’ Show name, department, and salary:
β SQL Filtering Interview QA πΌπ§
Q1. Whatβs the difference between AND and OR?
A:
β’ AND requires all conditions to be true
β’ OR requires at least one condition to be true
Q2. Can you combine AND and OR in one query?
A: Yes, but use parentheses to control logic:
Q3. What does NOT IN do?
A: Excludes rows with values in the list:
Q4. Can BETWEEN be used with dates?
A: Absolutely!
Q5. Whatβs the difference between IN and multiple ORs?
A: IN is cleaner and more concise:
-- Instead of:
-- Use:
π‘ Pro Tip:
When combining multiple filters, always use parentheses to avoid unexpected results due to operator precedence.
SQL Roadmap
DOUBLE TAP β€οΈ FOR MORE
Filtering helps you narrow down results based on specific conditions.
Letβs explore some powerful SQL operators:
1οΈβ£ IN β Match multiple values
Syntax:
SELECT columns FROM table_name WHERE column IN (value1, value2,...);
Example:
Get customers from specific cities:
SELECT name, city FROM customers
WHERE city IN ('Delhi', 'Mumbai', 'Chennai');
2οΈβ£ OR β Match any of multiple conditions
Syntax:
SELECT columns FROM table_name WHERE condition1 OR condition2;
Example:
Get employees from HR or Finance:
SELECT name FROM employees
WHERE department = 'HR' OR department = 'Finance';
3οΈβ£ AND β Match all conditions
Syntax:
SELECT columns FROM table_name WHERE condition1 AND condition2;
Example:
Get Sales employees earning more than 60,000:
SELECT name FROM employees
WHERE department = 'Sales' AND salary > 60000;
4οΈβ£ NOT β Exclude specific values or conditions
Syntax:
SELECT columns FROM table_name WHERE NOT condition;
Example:
Get all products except Electronics:
SELECT * FROM products
WHERE NOT category = 'Electronics';
5οΈβ£ BETWEEN β Match a range of values (inclusive)
Syntax:
SELECT columns FROM table_name WHERE column BETWEEN value1 AND value2;
Example:
Get employees with salary between 50,000 and 100,000:
SELECT name, salary FROM employees
WHERE salary BETWEEN 50000 AND 100000;
π₯ Quick Practice Task:
Write a query to:
β’ Get all employees in 'IT' or 'HR'
β’ Who earn more than 50,000
β’ Show name, department, and salary:
SELECT name, department, salary
FROM employees
WHERE department IN ('IT', 'HR')
AND salary > 50000;
β SQL Filtering Interview QA πΌπ§
Q1. Whatβs the difference between AND and OR?
A:
β’ AND requires all conditions to be true
β’ OR requires at least one condition to be true
Q2. Can you combine AND and OR in one query?
A: Yes, but use parentheses to control logic:
SELECT * FROM employees
WHERE (department = 'Sales' OR department = 'Marketing')
AND salary > 60000;
Q3. What does NOT IN do?
A: Excludes rows with values in the list:
SELECT * FROM customers
WHERE city NOT IN ('Delhi', 'Mumbai');
Q4. Can BETWEEN be used with dates?
A: Absolutely!
SELECT * FROM orders
WHERE order_date BETWEEN '2025-01-01' AND '2025-01-31';
Q5. Whatβs the difference between IN and multiple ORs?
A: IN is cleaner and more concise:
-- Instead of:
WHERE city = 'A' OR city = 'B' OR city = 'C';
-- Use:
WHERE city IN ('A', 'B', 'C');π‘ Pro Tip:
When combining multiple filters, always use parentheses to avoid unexpected results due to operator precedence.
SQL Roadmap
DOUBLE TAP β€οΈ FOR MORE
β€11
β
SQL Functions ππ§
SQL functions are built-in operations used to manipulate, calculate, and transform data. They help in summarizing results, formatting values, and applying logic in queries.
1οΈβ£ Aggregate Functions
These return a single result from a group of rows.
β’ COUNT() β Counts rows
β’ SUM() β Adds values
β’ AVG() β Returns average
β’ MAX() / MIN() β Highest or lowest value
2οΈβ£ String Functions
β’ UPPER() / LOWER() β Change case
β’ CONCAT() β Join strings
β’ SUBSTRING() β Extract part of a string
β’ LENGTH() β Length of string
3οΈβ£ Date Functions
β’ CURRENT_DATE / NOW() β Current date/time
β’ DATE_ADD() / DATE_SUB() β Add or subtract days
β’ DATEDIFF() β Difference between dates
β’ YEAR() / MONTH() / DAY() β Extract parts
4οΈβ£ Mathematical Functions
β’ ROUND() β Round decimals
β’ CEIL() / FLOOR() β Round up/down
β’ ABS() β Absolute value
5οΈβ£ Conditional Function
β’ COALESCE() β Returns first non-null value
β’ CASE β If/else logic in SQL
π― Use These Functions To:
β’ Summarize data
β’ Clean and format strings
β’ Handle nulls
β’ Calculate time differences
β’ Add logic into queries
π¬ Tap β€οΈ for more!
SQL functions are built-in operations used to manipulate, calculate, and transform data. They help in summarizing results, formatting values, and applying logic in queries.
1οΈβ£ Aggregate Functions
These return a single result from a group of rows.
β’ COUNT() β Counts rows
SELECT COUNT(*) FROM employees;β’ SUM() β Adds values
SELECT SUM(salary) FROM employees WHERE department = 'IT';β’ AVG() β Returns average
SELECT AVG(age) FROM customers;β’ MAX() / MIN() β Highest or lowest value
SELECT MAX(salary), MIN(salary) FROM employees;2οΈβ£ String Functions
β’ UPPER() / LOWER() β Change case
SELECT UPPER(name), LOWER(city) FROM customers;β’ CONCAT() β Join strings
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;β’ SUBSTRING() β Extract part of a string
SELECT SUBSTRING(name, 1, 3) FROM products;β’ LENGTH() β Length of string
SELECT LENGTH(description) FROM products;3οΈβ£ Date Functions
β’ CURRENT_DATE / NOW() β Current date/time
SELECT CURRENT_DATE, NOW();β’ DATE_ADD() / DATE_SUB() β Add or subtract days
SELECT DATE_ADD(hire_date, INTERVAL 30 DAY) FROM employees;β’ DATEDIFF() β Difference between dates
SELECT DATEDIFF(end_date, start_date) FROM projects;β’ YEAR() / MONTH() / DAY() β Extract parts
SELECT YEAR(order_date), MONTH(order_date) FROM orders;4οΈβ£ Mathematical Functions
β’ ROUND() β Round decimals
SELECT ROUND(price, 2) FROM products;β’ CEIL() / FLOOR() β Round up/down
SELECT CEIL(4.2), FLOOR(4.8);β’ ABS() β Absolute value
SELECT ABS(balance) FROM accounts;5οΈβ£ Conditional Function
β’ COALESCE() β Returns first non-null value
SELECT COALESCE(phone, 'Not Provided') FROM customers;β’ CASE β If/else logic in SQL
SELECT name,
CASE
WHEN salary > 50000 THEN 'High'
WHEN salary BETWEEN 30000 AND 50000 THEN 'Medium'
ELSE 'Low'
END AS salary_band
FROM employees;
π― Use These Functions To:
β’ Summarize data
β’ Clean and format strings
β’ Handle nulls
β’ Calculate time differences
β’ Add logic into queries
π¬ Tap β€οΈ for more!
β€10π2
β
SQL GROUP BY HAVING π
What is GROUP BY?
GROUP BY is used to group rows that have the same values in one or more columns. Itβs mostly used with aggregate functions like SUM(), COUNT(), AVG() to get summarized results.
What is HAVING?
HAVING is like WHERE, but it works after grouping. It filters the grouped results. You canβt use aggregate functions in WHERE, so we use HAVING instead.
π Problem 1:
You want to find total sales made in each city.
β This groups the sales by city and shows total per group.
π Problem 2:
Now, show only those cities where total sales are above βΉ50,000.
β `HAVING filters the result after grouping.
π Problem 3:
Find departments with more than 10 active employees.
β First, we filter rows using
π‘ Use
Double Tap β₯οΈ For More
What is GROUP BY?
GROUP BY is used to group rows that have the same values in one or more columns. Itβs mostly used with aggregate functions like SUM(), COUNT(), AVG() to get summarized results.
What is HAVING?
HAVING is like WHERE, but it works after grouping. It filters the grouped results. You canβt use aggregate functions in WHERE, so we use HAVING instead.
π Problem 1:
You want to find total sales made in each city.
SELECT city, SUM(sales) AS total_sales
FROM customers
GROUP BY city;
β This groups the sales by city and shows total per group.
π Problem 2:
Now, show only those cities where total sales are above βΉ50,000.
SELECT city, SUM(sales) AS total_sales
FROM customers
GROUP BY city
HAVING total_sales > 50000;
β `HAVING filters the result after grouping.
π Problem 3:
Find departments with more than 10 active employees.
SELECT department, COUNT(*) AS emp_count
FROM employees
WHERE active = 1
GROUP BY department
HAVING emp_count > 10;
β First, we filter rows using
WHERE. Then group, then filter groups with HAVING.π‘ Use
GROUP BY to summarize, HAVING to filter those summaries.Double Tap β₯οΈ For More
β€8
β
SQL JOINS ππ
JOINS let you combine data from two or more tables based on related columns.
1οΈβ£ INNER JOIN
Returns only matching rows from both tables.
Problem: Get customers with their orders.
β Only shows customers who have orders.
2οΈβ£ LEFT JOIN (or LEFT OUTER JOIN)
Returns all rows from the left table + matching rows from the right table. If no match, fills with NULL.
Problem: Show all customers, even if they didnβt order.
β Includes customers without orders.
3οΈβ£ RIGHT JOIN
Opposite of LEFT JOIN: keeps all rows from the right table.
4οΈβ£ FULL OUTER JOIN
Returns all rows from both tables. Where thereβs no match, it shows NULL.
β Includes customers with or without orders and orders with or without customers.
5οΈβ£ SELF JOIN
Table joins with itself.
Problem: Show employees and their managers.
β Links each employee to their manager using a self join.
π‘ Quick Summary:
β’ INNER JOIN β Only matches
β’ LEFT JOIN β All from left + matches
β’ RIGHT JOIN β All from right + matches
β’ FULL OUTER JOIN β Everything
β’ SELF JOIN β Table joins itself
π¬ Tap β€οΈ for more!
JOINS let you combine data from two or more tables based on related columns.
1οΈβ£ INNER JOIN
Returns only matching rows from both tables.
Problem: Get customers with their orders.
SELECT c.name, o.order_id
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id;
β Only shows customers who have orders.
2οΈβ£ LEFT JOIN (or LEFT OUTER JOIN)
Returns all rows from the left table + matching rows from the right table. If no match, fills with NULL.
Problem: Show all customers, even if they didnβt order.
SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id;
β Includes customers without orders.
3οΈβ£ RIGHT JOIN
Opposite of LEFT JOIN: keeps all rows from the right table.
4οΈβ£ FULL OUTER JOIN
Returns all rows from both tables. Where thereβs no match, it shows NULL.
SELECT c.name, o.order_id
FROM customers c
FULL OUTER JOIN orders o ON c.id = o.customer_id;
β Includes customers with or without orders and orders with or without customers.
5οΈβ£ SELF JOIN
Table joins with itself.
Problem: Show employees and their managers.
SELECT e.name AS employee, m.name AS manager
FROM employees e
JOIN employees m ON e.manager_id = m.id;
β Links each employee to their manager using a self join.
π‘ Quick Summary:
β’ INNER JOIN β Only matches
β’ LEFT JOIN β All from left + matches
β’ RIGHT JOIN β All from right + matches
β’ FULL OUTER JOIN β Everything
β’ SELF JOIN β Table joins itself
π¬ Tap β€οΈ for more!
β€7