โ
SQL Window Functions โ Part 1: ๐ง
What Are Window Functions?
They perform calculations across rows related to the current row without reducing the result set. Common for rankings, comparisons, and totals.
1. RANK()
Assigns a rank based on order. Ties get the same rank, but next rank is skipped.
Syntax:
RANK() OVER (
PARTITION BY column
ORDER BY column
)
Example Table: Sales
| Employee | Region | Sales |
|----------|--------|-------|
| A | East | 500 |
| B | East | 600 |
| C | East | 600 |
| D | East | 400 |
Query:
SELECT Employee, Sales,
RANK() OVER (PARTITION BY Region ORDER BY Sales DESC) AS Rank
FROM Sales;
Result:
| Employee | Sales | Rank |
|----------|-------|------|
| B | 600 | 1 |
| C | 600 | 1 |
| A | 500 | 3 |
| D | 400 | 4 |
2. DENSE_RANK()
Same logic as RANK but does not skip ranks.
Query:
SELECT Employee, Sales,
DENSE_RANK() OVER (PARTITION BY Region ORDER BY Sales DESC) AS DenseRank
FROM Sales;
Result:
| Employee | Sales | DenseRank |
|----------|-------|-----------|
| B | 600 | 1 |
| C | 600 | 1 |
| A | 500 | 2 |
| D | 400 | 3 |
RANK vs DENSE_RANK
- RANK skips ranks after ties. Tie at 1 means next is 3
- DENSE_RANK does not skip. Tie at 1 means next is 2
๐ก Use RANK when position gaps matter
๐ก Use DENSE_RANK for continuous ranking
Double Tap โฅ๏ธ For More
What Are Window Functions?
They perform calculations across rows related to the current row without reducing the result set. Common for rankings, comparisons, and totals.
1. RANK()
Assigns a rank based on order. Ties get the same rank, but next rank is skipped.
Syntax:
RANK() OVER (
PARTITION BY column
ORDER BY column
)
Example Table: Sales
| Employee | Region | Sales |
|----------|--------|-------|
| A | East | 500 |
| B | East | 600 |
| C | East | 600 |
| D | East | 400 |
Query:
SELECT Employee, Sales,
RANK() OVER (PARTITION BY Region ORDER BY Sales DESC) AS Rank
FROM Sales;
Result:
| Employee | Sales | Rank |
|----------|-------|------|
| B | 600 | 1 |
| C | 600 | 1 |
| A | 500 | 3 |
| D | 400 | 4 |
2. DENSE_RANK()
Same logic as RANK but does not skip ranks.
Query:
SELECT Employee, Sales,
DENSE_RANK() OVER (PARTITION BY Region ORDER BY Sales DESC) AS DenseRank
FROM Sales;
Result:
| Employee | Sales | DenseRank |
|----------|-------|-----------|
| B | 600 | 1 |
| C | 600 | 1 |
| A | 500 | 2 |
| D | 400 | 3 |
RANK vs DENSE_RANK
- RANK skips ranks after ties. Tie at 1 means next is 3
- DENSE_RANK does not skip. Tie at 1 means next is 2
๐ก Use RANK when position gaps matter
๐ก Use DENSE_RANK for continuous ranking
Double Tap โฅ๏ธ For More
โค26๐4
๐ Data Analytics Tools & Their Use Cases ๐๐
๐น Excel โ Spreadsheet analysis, pivot tables, and basic data visualization
๐น SQL โ Querying databases for data extraction and relational analysis
๐น Tableau โ Interactive dashboards and storytelling with visual analytics
๐น Power BI โ Business intelligence reporting and real-time data insights
๐น Google Analytics โ Web traffic analysis and user behavior tracking
๐น Python (with Pandas) โ Data manipulation, cleaning, and exploratory analysis
๐น R โ Statistical computing and advanced graphical visualizations
๐น Apache Spark โ Big data processing for distributed analytics workloads
๐น Looker โ Semantic modeling and embedded analytics for teams
๐น Alteryx โ Data blending, predictive modeling, and workflow automation
๐น Knime โ Visual data pipelines for no-code analytics and ML
๐น Splunk โ Log analysis and real-time operational intelligence
๐ฌ Tap โค๏ธ if this helped!
๐น Excel โ Spreadsheet analysis, pivot tables, and basic data visualization
๐น SQL โ Querying databases for data extraction and relational analysis
๐น Tableau โ Interactive dashboards and storytelling with visual analytics
๐น Power BI โ Business intelligence reporting and real-time data insights
๐น Google Analytics โ Web traffic analysis and user behavior tracking
๐น Python (with Pandas) โ Data manipulation, cleaning, and exploratory analysis
๐น R โ Statistical computing and advanced graphical visualizations
๐น Apache Spark โ Big data processing for distributed analytics workloads
๐น Looker โ Semantic modeling and embedded analytics for teams
๐น Alteryx โ Data blending, predictive modeling, and workflow automation
๐น Knime โ Visual data pipelines for no-code analytics and ML
๐น Splunk โ Log analysis and real-time operational intelligence
๐ฌ Tap โค๏ธ if this helped!
โค29
๐ ๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ: How do you create a running total in SQL?
๐ ๐ ๐ฒ Use the
๐ง Logic Breakdown:
-
-
- No GROUP BY needed
โ Use Case: Track cumulative revenue, expenses, or orders by date
๐ก SQL Tip:
Add
๐ฌ Tap โค๏ธ for more!
๐ ๐ ๐ฒ Use the
WINDOW FUNCTION with OVER() clause:Date,
Amount,
SUM(Amount) OVER (ORDER BY Date) AS RunningTotal
FROM Sales;
๐ง Logic Breakdown:
-
SUM(Amount) โ Aggregates the values -
OVER(ORDER BY Date) โ Maintains order for accumulation - No GROUP BY needed
โ Use Case: Track cumulative revenue, expenses, or orders by date
๐ก SQL Tip:
Add
PARTITION BY in OVER() if you want running totals by category or region.๐ฌ Tap โค๏ธ for more!
โค27
๐ ๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ: How do you get the 2nd highest salary in SQL?
๐ ๐ ๐ฒ: Use
MySQL / PostgreSQL (with LIMIT & OFFSET):
Using Subquery (Works on most databases):
๐ง Logic Breakdown:
- First method sorts and skips the top result
- Second method finds the highest salary below the max
๐ก Tip: Use DENSE_RANK() if multiple employees share the same salary rank
๐ฌ Tap โค๏ธ for more!
๐ ๐ ๐ฒ: Use
ORDER BY with LIMIT or OFFSET, or a subquery.MySQL / PostgreSQL (with LIMIT & OFFSET):
SELECT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
Using Subquery (Works on most databases):
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
๐ง Logic Breakdown:
- First method sorts and skips the top result
- Second method finds the highest salary below the max
๐ก Tip: Use DENSE_RANK() if multiple employees share the same salary rank
๐ฌ Tap โค๏ธ for more!
โค28๐2
โ
SQL Checklist for Data Analysts ๐ง ๐ป
๐ 1. Understand SQL Basics
โ What is SQL and how databases work
โ Relational vs non-relational databases
โ Table structure: rows, columns, keys
๐งฉ 2. Core SQL Queries
โ SELECT, FROM, WHERE
โ ORDER BY, LIMIT
โ DISTINCT, BETWEEN, IN, LIKE
๐ 3. Master Joins
โ INNER JOIN
โ LEFT JOIN / RIGHT JOIN
โ FULL OUTER JOIN
โ Practice combining data from multiple tables
๐ 4. Aggregation & Grouping
โ COUNT, SUM, AVG, MIN, MAX
โ GROUP BY & HAVING
โ Aggregate filtering
๐ 5. Subqueries & CTEs
โ Use subqueries inside SELECT/WHERE
โ WITH clause for common table expressions
โ Nested queries and optimization basics
๐งฎ 6. Window Functions
โ RANK(), ROW_NUMBER(), DENSE_RANK()
โ PARTITION BY & ORDER BY
โ LEAD(), LAG(), SUM() OVER
๐งน 7. Data Cleaning with SQL
โ Remove duplicates (DISTINCT, ROW_NUMBER)
โ Handle NULLs
โ Use CASE WHEN for conditional logic
๐ ๏ธ 8. Practice & Real Tasks
โ Write queries from real datasets
โ Analyze sales, customers, transactions
โ Build reports with JOINs and aggregations
๐ 9. Tools to Use
โ PostgreSQL / MySQL / SQL Server
โ db-fiddle, Mode Analytics, DataCamp, StrataScratch
โ VS Code + SQL extensions
๐ 10. Interview Prep
โ Practice 50+ SQL questions
โ Solve problems on LeetCode, HackerRank
โ Explain query logic clearly in mock interviews
๐ฌ Tap โค๏ธ if this was helpful!
๐ 1. Understand SQL Basics
โ What is SQL and how databases work
โ Relational vs non-relational databases
โ Table structure: rows, columns, keys
๐งฉ 2. Core SQL Queries
โ SELECT, FROM, WHERE
โ ORDER BY, LIMIT
โ DISTINCT, BETWEEN, IN, LIKE
๐ 3. Master Joins
โ INNER JOIN
โ LEFT JOIN / RIGHT JOIN
โ FULL OUTER JOIN
โ Practice combining data from multiple tables
๐ 4. Aggregation & Grouping
โ COUNT, SUM, AVG, MIN, MAX
โ GROUP BY & HAVING
โ Aggregate filtering
๐ 5. Subqueries & CTEs
โ Use subqueries inside SELECT/WHERE
โ WITH clause for common table expressions
โ Nested queries and optimization basics
๐งฎ 6. Window Functions
โ RANK(), ROW_NUMBER(), DENSE_RANK()
โ PARTITION BY & ORDER BY
โ LEAD(), LAG(), SUM() OVER
๐งน 7. Data Cleaning with SQL
โ Remove duplicates (DISTINCT, ROW_NUMBER)
โ Handle NULLs
โ Use CASE WHEN for conditional logic
๐ ๏ธ 8. Practice & Real Tasks
โ Write queries from real datasets
โ Analyze sales, customers, transactions
โ Build reports with JOINs and aggregations
๐ 9. Tools to Use
โ PostgreSQL / MySQL / SQL Server
โ db-fiddle, Mode Analytics, DataCamp, StrataScratch
โ VS Code + SQL extensions
๐ 10. Interview Prep
โ Practice 50+ SQL questions
โ Solve problems on LeetCode, HackerRank
โ Explain query logic clearly in mock interviews
๐ฌ Tap โค๏ธ if this was helpful!
โค35๐5
โ
Core SQL Queries You Should Know ๐๐ก
1๏ธโฃ SELECT, FROM, WHERE
This is how you tell SQL what data you want, where to get it from, and how to filter it.
๐ SELECT = what columns
๐ FROM = which table
๐ WHERE = which rows
Example:
This shows names and ages of employees older than 30.
2๏ธโฃ ORDER BY, LIMIT
Use when you want sorted results or only a few records.
๐ ORDER BY sorts data
๐ LIMIT reduces how many rows you get
Example:
Shows top 3 highest paid employees.
3๏ธโฃ DISTINCT
Removes duplicate values from a column.
Example:
Lists all unique departments from the employees table.
4๏ธโฃ BETWEEN
Used for filtering within a range (numbers, dates, etc).
Example:
Shows names of employees aged 25 to 35.
5๏ธโฃ IN
Use IN to match against multiple values in one go.
Example:
Shows names of people working in HR or Sales.
6๏ธโฃ LIKE
Used to match text patterns.
๐ % = wildcard (any text)
Example:
Finds names starting with A.
๐ฌ Double Tap โค๏ธ if this helped you!
1๏ธโฃ SELECT, FROM, WHERE
This is how you tell SQL what data you want, where to get it from, and how to filter it.
๐ SELECT = what columns
๐ FROM = which table
๐ WHERE = which rows
Example:
SELECT name, age FROM employees WHERE age > 30; This shows names and ages of employees older than 30.
2๏ธโฃ ORDER BY, LIMIT
Use when you want sorted results or only a few records.
๐ ORDER BY sorts data
๐ LIMIT reduces how many rows you get
Example:
SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 3; Shows top 3 highest paid employees.
3๏ธโฃ DISTINCT
Removes duplicate values from a column.
Example:
SELECT DISTINCT department FROM employees; Lists all unique departments from the employees table.
4๏ธโฃ BETWEEN
Used for filtering within a range (numbers, dates, etc).
Example:
SELECT name FROM employees WHERE age BETWEEN 25 AND 35; Shows names of employees aged 25 to 35.
5๏ธโฃ IN
Use IN to match against multiple values in one go.
Example:
SELECT name FROM employees WHERE department IN ('HR', 'Sales'); Shows names of people working in HR or Sales.
6๏ธโฃ LIKE
Used to match text patterns.
๐ % = wildcard (any text)
Example:
SELECT name FROM employees WHERE name LIKE 'A%'; Finds names starting with A.
๐ฌ Double Tap โค๏ธ if this helped you!
โค29๐2
โ
SQL Joins with Interview Q&A ๐๐ป
Joins combine data from multiple tables via common columnsโessential for relational databases and analytics in 2025.
1๏ธโฃ INNER JOIN
Only matching records from both tables.
Use: Employee names with their departments.
2๏ธโฃ LEFT JOIN (LEFT OUTER JOIN)
All left table rows + matching right; NULLs for no match.
Use: All employees, even without departments.
3๏ธโฃ RIGHT JOIN (RIGHT OUTER JOIN)
All right table rows + matching left.
Use: All departments, even empty ones.
4๏ธโฃ FULL OUTER JOIN
All rows from both; NULLs where no match (PostgreSQL/MySQL supports).
Use: Spot unmatched records.
5๏ธโฃ SELF JOIN
Table joins itself.
Use: Employee-manager hierarchy.
Real-World Interview Questions + Answers
Q1: What is the difference between INNER and OUTER JOIN?
A: INNER returns only matches; OUTER includes unmatched from one/both tables.
Q2: When would you use LEFT JOIN instead of INNER JOIN?
A: To keep all left table rows, even without right matches.
Q3: How can you find employees who donโt belong to any department?
A: LEFT JOIN + IS NULL filter.
Q4: How would you find mismatched data between two tables?
A: FULL OUTER JOIN + IS NULL on either side.
Q5: Can you join more than two tables?
A: Yes, chain JOINs: FROM A JOIN B ON... JOIN C ON...
๐ฌ Tap โค๏ธ for more!
Joins combine data from multiple tables via common columnsโessential for relational databases and analytics in 2025.
1๏ธโฃ INNER JOIN
Only matching records from both tables.
SELECT e.name, d.department_name
FROM employees e
INNER JOIN departments d ON e.dept_id = d.id;
Use: Employee names with their departments.
2๏ธโฃ LEFT JOIN (LEFT OUTER JOIN)
All left table rows + matching right; NULLs for no match.
SELECT e.name, d.department_name
FROM employees e
LEFT JOIN departments d ON e.dept_id = d.id;
Use: All employees, even without departments.
3๏ธโฃ RIGHT JOIN (RIGHT OUTER JOIN)
All right table rows + matching left.
SELECT e.name, d.department_name
FROM employees e
RIGHT JOIN departments d ON e.dept_id = d.id;
Use: All departments, even empty ones.
4๏ธโฃ FULL OUTER JOIN
All rows from both; NULLs where no match (PostgreSQL/MySQL supports).
SELECT e.name, d.department_name
FROM employees e
FULL OUTER JOIN departments d ON e.dept_id = d.id;
Use: Spot unmatched records.
5๏ธโฃ SELF JOIN
Table joins itself.
SELECT a.name AS Employee, b.name AS Manager
FROM employees a
JOIN employees b ON a.manager_id = b.id;
Use: Employee-manager hierarchy.
Real-World Interview Questions + Answers
Q1: What is the difference between INNER and OUTER JOIN?
A: INNER returns only matches; OUTER includes unmatched from one/both tables.
Q2: When would you use LEFT JOIN instead of INNER JOIN?
A: To keep all left table rows, even without right matches.
Q3: How can you find employees who donโt belong to any department?
A: LEFT JOIN + IS NULL filter.
SELECT e.name
FROM employees e
LEFT JOIN departments d ON e.dept_id = d.id
WHERE d.department_name IS NULL;
Q4: How would you find mismatched data between two tables?
A: FULL OUTER JOIN + IS NULL on either side.
Q5: Can you join more than two tables?
A: Yes, chain JOINs: FROM A JOIN B ON... JOIN C ON...
๐ฌ Tap โค๏ธ for more!
โค25
โ
How to Learn Data Analytics Step-by-Step ๐๐
1๏ธโฃ Understand the Basics
โฆ Learn what data analytics is & key roles (analyst, scientist, engineer)
โฆ Know the types: descriptive, diagnostic, predictive, prescriptive
โฆ Explore the data analytics lifecycle
2๏ธโฃ Learn Excel / Google Sheets
โฆ Master formulas, pivot tables, VLOOKUP/XLOOKUP
โฆ Clean data, create charts & dashboards
โฆ Automate with basic macros
3๏ธโฃ Learn SQL
โฆ Understand SELECT, WHERE, GROUP BY, JOINs
โฆ Practice window functions (RANK, LAG, LEAD)
โฆ Use platforms like PostgreSQL or MySQL
4๏ธโฃ Learn Python (for Analytics)
โฆ Use Pandas for data manipulation
โฆ Use NumPy, Matplotlib, Seaborn for analysis & viz
โฆ Load, clean, and explore datasets
5๏ธโฃ Master Data Visualization Tools
โฆ Learn Power BI or Tableau
โฆ Build dashboards, use filters, slicers, DAX/calculated fields
โฆ Tell data stories visually
6๏ธโฃ Work on Real Projects
โฆ Sales analysis
โฆ Customer churn prediction
โฆ Marketing campaign analysis
โฆ EDA on public datasets
7๏ธโฃ Learn Basic Stats & Business Math
โฆ Mean, median, standard deviation, distributions
โฆ Correlation, regression, hypothesis testing
โฆ A/B testing, ROI, KPIs
8๏ธโฃ Version Control & Portfolio
โฆ Use Git/GitHub to share your projects
โฆ Document with Jupyter Notebooks or Markdown
โฆ Create a portfolio site or Notion page
9๏ธโฃ Learn Dashboarding & Reporting
โฆ Automate reports with Python, SQL jobs
โฆ Build scheduled dashboards with Power BI / Looker Studio
๐ Apply for Jobs / Freelance Gigs
โฆ Analyst roles, internships, freelance projects
โฆ Tailor your resume to highlight tools & projects
๐ฌ React โค๏ธ for more!
1๏ธโฃ Understand the Basics
โฆ Learn what data analytics is & key roles (analyst, scientist, engineer)
โฆ Know the types: descriptive, diagnostic, predictive, prescriptive
โฆ Explore the data analytics lifecycle
2๏ธโฃ Learn Excel / Google Sheets
โฆ Master formulas, pivot tables, VLOOKUP/XLOOKUP
โฆ Clean data, create charts & dashboards
โฆ Automate with basic macros
3๏ธโฃ Learn SQL
โฆ Understand SELECT, WHERE, GROUP BY, JOINs
โฆ Practice window functions (RANK, LAG, LEAD)
โฆ Use platforms like PostgreSQL or MySQL
4๏ธโฃ Learn Python (for Analytics)
โฆ Use Pandas for data manipulation
โฆ Use NumPy, Matplotlib, Seaborn for analysis & viz
โฆ Load, clean, and explore datasets
5๏ธโฃ Master Data Visualization Tools
โฆ Learn Power BI or Tableau
โฆ Build dashboards, use filters, slicers, DAX/calculated fields
โฆ Tell data stories visually
6๏ธโฃ Work on Real Projects
โฆ Sales analysis
โฆ Customer churn prediction
โฆ Marketing campaign analysis
โฆ EDA on public datasets
7๏ธโฃ Learn Basic Stats & Business Math
โฆ Mean, median, standard deviation, distributions
โฆ Correlation, regression, hypothesis testing
โฆ A/B testing, ROI, KPIs
8๏ธโฃ Version Control & Portfolio
โฆ Use Git/GitHub to share your projects
โฆ Document with Jupyter Notebooks or Markdown
โฆ Create a portfolio site or Notion page
9๏ธโฃ Learn Dashboarding & Reporting
โฆ Automate reports with Python, SQL jobs
โฆ Build scheduled dashboards with Power BI / Looker Studio
๐ Apply for Jobs / Freelance Gigs
โฆ Analyst roles, internships, freelance projects
โฆ Tailor your resume to highlight tools & projects
๐ฌ React โค๏ธ for more!
โค29
โ
Data Analytics Basics You Must Know ๐๐ง
1๏ธโฃ What is Data Analytics?
โก๏ธ The process of extracting insights from data to support decision-making.
2๏ธโฃ 4 Types of Data Analytics
โฆ Descriptive: What happened?
โฆ Diagnostic: Why did it happen?
โฆ Predictive: What could happen?
โฆ Prescriptive: What should we do?
3๏ธโฃ Common Data Types
โฆ Structured: Tables, rows, columns
โฆ Unstructured: Text, images, audio
โฆ Semi-structured: JSON, XML
4๏ธโฃ Key Tools Youโll Use
โฆ Excel/Google Sheets
โฆ SQL (PostgreSQL, MySQL)
โฆ Python (Pandas, Matplotlib)
โฆ Tableau / Power BI
5๏ธโฃ Common Tasks
โฆ Cleaning messy data
โฆ Creating visualizations
โฆ Running SQL queries
โฆ Finding trends & patterns
โฆ Communicating insights clearly
6๏ธโฃ Top Skills Needed
โฆ Critical thinking
โฆ Business understanding
โฆ Data storytelling
โฆ Attention to detail
๐ฌ Tap โค๏ธ for more!
1๏ธโฃ What is Data Analytics?
โก๏ธ The process of extracting insights from data to support decision-making.
2๏ธโฃ 4 Types of Data Analytics
โฆ Descriptive: What happened?
โฆ Diagnostic: Why did it happen?
โฆ Predictive: What could happen?
โฆ Prescriptive: What should we do?
3๏ธโฃ Common Data Types
โฆ Structured: Tables, rows, columns
โฆ Unstructured: Text, images, audio
โฆ Semi-structured: JSON, XML
4๏ธโฃ Key Tools Youโll Use
โฆ Excel/Google Sheets
โฆ SQL (PostgreSQL, MySQL)
โฆ Python (Pandas, Matplotlib)
โฆ Tableau / Power BI
5๏ธโฃ Common Tasks
โฆ Cleaning messy data
โฆ Creating visualizations
โฆ Running SQL queries
โฆ Finding trends & patterns
โฆ Communicating insights clearly
6๏ธโฃ Top Skills Needed
โฆ Critical thinking
โฆ Business understanding
โฆ Data storytelling
โฆ Attention to detail
๐ฌ Tap โค๏ธ for more!
โค31
โ
SQL Aggregations with Interview Q&A ๐๐งฎ
Aggregation functions help summarize large datasets. Combine them with GROUP BY to analyze grouped data.
1๏ธโฃ COUNT()
Returns the number of records.
2๏ธโฃ SUM()
Adds up values in a column.
3๏ธโฃ AVG()
Returns the average of values.
4๏ธโฃ MAX() / MIN()
Returns the highest/lowest value.
5๏ธโฃ GROUP BY
Groups rows that have the same values in specified columns.
6๏ธโฃ HAVING
Filters groups after aggregation (unlike WHERE which filters rows).
โโโโโโโโ
Real-World Interview Questions + Answers
Q1: Whatโs the difference between WHERE and HAVING?
A: WHERE filters rows before grouping. HAVING filters after aggregation.
Q2: Can you use aggregate functions without GROUP BY?
A: Yes. Without GROUP BY, the function applies to the entire table.
Q3: How do you find departments with more than 5 employees?
Q4: Can you group by multiple columns?
A: Yes.
Q5: How do you calculate total and average salary per department?
๐ฌ Tap โค๏ธ for more!
Aggregation functions help summarize large datasets. Combine them with GROUP BY to analyze grouped data.
1๏ธโฃ COUNT()
Returns the number of records.
SELECT COUNT(*) FROM employees;
2๏ธโฃ SUM()
Adds up values in a column.
SELECT dept_id, SUM(salary)
FROM employees
GROUP BY dept_id;
3๏ธโฃ AVG()
Returns the average of values.
SELECT AVG(salary) FROM employees;
4๏ธโฃ MAX() / MIN()
Returns the highest/lowest value.
SELECT MAX(salary), MIN(salary) FROM employees;
5๏ธโฃ GROUP BY
Groups rows that have the same values in specified columns.
SELECT dept_id, COUNT(*)
FROM employees
GROUP BY dept_id;
6๏ธโฃ HAVING
Filters groups after aggregation (unlike WHERE which filters rows).
SELECT dept_id, AVG(salary)
FROM employees
GROUP BY dept_id
HAVING AVG(salary) > 50000;
โโโโโโโโ
Real-World Interview Questions + Answers
Q1: Whatโs the difference between WHERE and HAVING?
A: WHERE filters rows before grouping. HAVING filters after aggregation.
Q2: Can you use aggregate functions without GROUP BY?
A: Yes. Without GROUP BY, the function applies to the entire table.
Q3: How do you find departments with more than 5 employees?
SELECT dept_id, COUNT(*)
FROM employees
GROUP BY dept_id
HAVING COUNT(*) > 5;
Q4: Can you group by multiple columns?
A: Yes.
GROUP BY dept_id, job_title
Q5: How do you calculate total and average salary per department?
SELECT dept_id, SUM(salary), AVG(salary)
FROM employees
GROUP BY dept_id;
๐ฌ Tap โค๏ธ for more!
โค17๐5
โ
SQL Subqueries with Interview Q&A ๐๐ง
Subqueries and CTEs help you write cleaner, modular, and more powerful SQL queries. They're often asked in interviews!
1๏ธโฃ Subqueries (Nested Queries)
A query inside another query.
Example:
๐ Use case: Find employees earning above average.
Types:
โฆ In SELECT
โฆ In WHERE
โฆ In FROM (Inline Views)
2๏ธโฃ Correlated Subqueries
Inner query depends on outer query.
Example:
๐ Use case: Find employees earning above average in their department.
3๏ธโฃ Common Table Expressions (CTE)
Temporary result set using WITH. Improves readability.
Example:
๐ Use case: Simplify complex queries, recursive queries.
4๏ธโฃ Recursive CTE
Used for hierarchical data (e.g. org charts, folders).
Example:
๐ง Interview Questions
Q1: When should you use a subquery vs JOIN?
A: Use subquery when working with aggregates or filtering logic. JOINs are better for combining related data.
Q2: What's the difference between subquery and CTE?
A: Subquery is inline; CTE improves readability and can be reused in the query.
Q3: What is a correlated subquery?
A: It depends on data from the outer query. Runs row by row.
Q4: When do you use recursive CTEs?
A: For hierarchical/parent-child relationships like org charts, file systems.
Q5: Can subqueries be used in the FROM clause?
A: Yes, they're called derived tables or inline views.
๐ฌ Double Tap โค๏ธ for more!
Subqueries and CTEs help you write cleaner, modular, and more powerful SQL queries. They're often asked in interviews!
1๏ธโฃ Subqueries (Nested Queries)
A query inside another query.
Example:
SELECT name
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
๐ Use case: Find employees earning above average.
Types:
โฆ In SELECT
โฆ In WHERE
โฆ In FROM (Inline Views)
2๏ธโฃ Correlated Subqueries
Inner query depends on outer query.
Example:
SELECT name
FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept_id = e.dept_id);
๐ Use case: Find employees earning above average in their department.
3๏ธโฃ Common Table Expressions (CTE)
Temporary result set using WITH. Improves readability.
Example:
WITH high_paid AS (
SELECT name, salary FROM employees WHERE salary > 100000
)
SELECT * FROM high_paid;
๐ Use case: Simplify complex queries, recursive queries.
4๏ธโฃ Recursive CTE
Used for hierarchical data (e.g. org charts, folders).
Example:
WITH RECURSIVE emp_tree AS (
SELECT id, name, manager_id FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id
FROM employees e
JOIN emp_tree et ON e.manager_id = et.id
)
SELECT * FROM emp_tree;
๐ง Interview Questions
Q1: When should you use a subquery vs JOIN?
A: Use subquery when working with aggregates or filtering logic. JOINs are better for combining related data.
Q2: What's the difference between subquery and CTE?
A: Subquery is inline; CTE improves readability and can be reused in the query.
Q3: What is a correlated subquery?
A: It depends on data from the outer query. Runs row by row.
Q4: When do you use recursive CTEs?
A: For hierarchical/parent-child relationships like org charts, file systems.
Q5: Can subqueries be used in the FROM clause?
A: Yes, they're called derived tables or inline views.
๐ฌ Double Tap โค๏ธ for more!
โค13
โ
SQL Window Functions ๐ช๐
Window functions perform calculations across rows related to the current row without collapsing them like
1๏ธโฃ ROW_NUMBER()
Gives a unique number to each row in a partition.
๐ Use case: Rank employees by salary within each department.
2๏ธโฃ RANK() vs DENSE_RANK()
โฆ
โฆ
3๏ธโฃ LAG() and LEAD()
Access previous/next row values.
๐ Use case: Compare current row to previous/next (e.g., salary or stock change).
4๏ธโฃ NTILE(n)
Divides rows into
๐ Use case: Quartiles/percentile-style grouping.
5๏ธโฃ SUM(), AVG(), COUNT() with OVER()
Running totals, partition-wise aggregates, moving stats.
๐ง Interview Q&A
Q1: Difference between GROUP BY and OVER()?
โฆ
โฆ
Q2: When would you use LAG()?
To compare current row values with previous ones (e.g., dayโtoโday revenue change, previous monthโs balance).
Q3: What happens if no PARTITION BY is used?
The function runs over the entire result set as a single partition.
Q4: Can you sort inside OVER()?
Yes,
๐ฌ Double Tap โค๏ธ for more!
Window functions perform calculations across rows related to the current row without collapsing them like
GROUP BY does.1๏ธโฃ ROW_NUMBER()
Gives a unique number to each row in 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() and LEAD()
Access previous/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 row to previous/next (e.g., salary or stock change).
4๏ธโฃ NTILE(n)
Divides rows into
n buckets.SELECT name,
NTILE(4) OVER (ORDER BY salary DESC) AS quartile
FROM employees;
๐ Use case: Quartiles/percentile-style grouping.
5๏ธโฃ SUM(), AVG(), COUNT() with OVER()
Running totals, partition-wise aggregates, moving stats.
SELECT name, dept_id, salary,
SUM(salary) OVER (PARTITION BY dept_id) AS dept_total
FROM employees;
๐ง Interview Q&A
Q1: Difference between GROUP BY and OVER()?
โฆ
GROUP BY โ Collapses rows into groups; one row per group.โฆ
OVER() โ Keeps all rows; adds an extra column with the aggregate.Q2: When would you use LAG()?
To compare current row values with previous ones (e.g., dayโtoโday revenue change, previous monthโs balance).
Q3: What happens if no PARTITION BY is used?
The function runs over the entire result set as a single partition.
Q4: Can you sort inside OVER()?
Yes,
ORDER BY inside OVER() defines the calculation order (needed for ranking, LAG/LEAD, running totals).๐ฌ Double Tap โค๏ธ for more!
โค15๐3๐1
โ
Top 50 SQL Interview Questions
1. What is SQL and why is it used?
2. Difference between SQL and MySQL
3. What are primary keys and foreign keys?
4. What is a unique constraint?
5. Difference between WHERE and HAVING
6. What are joins? Types of joins?
7. Difference between INNER JOIN and LEFT JOIN
8. What is a subquery?
9. What are CTEs (Common Table Expressions)?
10. What is a view in SQL?
11. How do you remove duplicate records?
12. What is normalization? Explain its types
13. What is denormalization?
14. What is a stored procedure?
15. What are indexes and why are they used?
16. What is the difference between clustered and non-clustered index?
17. What is a transaction?
18. ACID properties in SQL
19. Difference between DELETE, TRUNCATE, and DROP
20. What is a NULL value in SQL?
21. How do you handle NULLs in queries?
22. What is COALESCE() in SQL?
23. What are aggregate functions?
24. What is GROUP BY and how does it work?
25. What is the difference between COUNT(*) and COUNT(column)?
26. What are window functions?
27. Difference between RANK(), DENSE_RANK(), and ROW_NUMBER()
28. What is the use of LAG() and LEAD()?
29. What is a CASE statement?
30. What is the difference between CHAR and VARCHAR?
31. What are constraints in SQL?
32. What is a composite key?
33. What are scalar vs table-valued functions?
34. How does indexing affect performance?
35. What is data integrity?
36. What are triggers in SQL?
37. What is a correlated subquery?
38. What is a cross join?
39. What is UNION vs UNION ALL?
40. Difference between EXISTS and IN
41. What are set operations in SQL?
42. What is a materialized view?
43. Explain the BETWEEN operator
44. What is a pivot table in SQL?
45. How do you optimize SQL queries?
46. How do you handle slow queries?
47. What is execution plan in SQL?
48. Whatโs the use of LIMIT / OFFSET?
49. How do you import/export data in SQL?
50. How would you clean messy data using SQL?
๐ฌ Tap โค๏ธ for the detailed answers!
1. What is SQL and why is it used?
2. Difference between SQL and MySQL
3. What are primary keys and foreign keys?
4. What is a unique constraint?
5. Difference between WHERE and HAVING
6. What are joins? Types of joins?
7. Difference between INNER JOIN and LEFT JOIN
8. What is a subquery?
9. What are CTEs (Common Table Expressions)?
10. What is a view in SQL?
11. How do you remove duplicate records?
12. What is normalization? Explain its types
13. What is denormalization?
14. What is a stored procedure?
15. What are indexes and why are they used?
16. What is the difference between clustered and non-clustered index?
17. What is a transaction?
18. ACID properties in SQL
19. Difference between DELETE, TRUNCATE, and DROP
20. What is a NULL value in SQL?
21. How do you handle NULLs in queries?
22. What is COALESCE() in SQL?
23. What are aggregate functions?
24. What is GROUP BY and how does it work?
25. What is the difference between COUNT(*) and COUNT(column)?
26. What are window functions?
27. Difference between RANK(), DENSE_RANK(), and ROW_NUMBER()
28. What is the use of LAG() and LEAD()?
29. What is a CASE statement?
30. What is the difference between CHAR and VARCHAR?
31. What are constraints in SQL?
32. What is a composite key?
33. What are scalar vs table-valued functions?
34. How does indexing affect performance?
35. What is data integrity?
36. What are triggers in SQL?
37. What is a correlated subquery?
38. What is a cross join?
39. What is UNION vs UNION ALL?
40. Difference between EXISTS and IN
41. What are set operations in SQL?
42. What is a materialized view?
43. Explain the BETWEEN operator
44. What is a pivot table in SQL?
45. How do you optimize SQL queries?
46. How do you handle slow queries?
47. What is execution plan in SQL?
48. Whatโs the use of LIMIT / OFFSET?
49. How do you import/export data in SQL?
50. How would you clean messy data using SQL?
๐ฌ Tap โค๏ธ for the detailed answers!
โค47
โ
Top SQL Interview Questions with Answers: Part-1 ๐ง
1. What is SQL and why is it used?
SQL (Structured Query Language) is used to manage and manipulate relational databases. It allows users to retrieve, insert, update, and delete data efficiently.
2. Difference between SQL and MySQL
- SQL is a language used to interact with databases.
- MySQL is a relational database management system (RDBMS) that uses SQL.
Think of SQL as the language, and MySQL as the software that understands and processes it.
3. What are primary keys and foreign keys? ๐
- Primary Key uniquely identifies each row in a table. It must be unique and not null.
- Foreign Key links one table to another. It references the primary key of another table to maintain referential integrity.
4. What is a unique constraint?
It ensures that all values in a column (or combination of columns) are unique across the table. Unlike primary keys, columns with a unique constraint can accept one NULL.
5. Difference between WHERE and HAVING
- WHERE filters rows before aggregation.
- HAVING filters groups after aggregation.
Example: Use WHERE for filtering raw data, HAVING for filtering GROUP BY results.
6. What are joins? Types of joins? ๐ค
Joins combine data from multiple tables based on related columns.
Types:
- INNER JOIN โ Returns matching rows
- LEFT JOIN โ All rows from left table + matched rows from right
- RIGHT JOIN โ All rows from right table + matched from left
- FULL JOIN โ All rows from both tables
- CROSS JOIN โ Cartesian product
7. Difference between INNER JOIN and LEFT JOIN
- INNER JOIN only returns rows with matching keys in both tables.
- LEFT JOIN returns all rows from the left table, plus matching rows from the right table (NULLs if no match).
8. What is a subquery?
A subquery is a query nested inside another SQL query. It can be used in SELECT, FROM, or WHERE clauses to fetch intermediate results.
9. What are CTEs (Common Table Expressions)?
CTEs are temporary named result sets that make queries more readable and reusable.
Syntax:
10. What is a view in SQL?
A view is a virtual table based on a SQL query. It doesn't store data itself but provides a way to simplify complex queries, improve security, and reuse logic.
Double Tap โค๏ธ For Part-2
1. What is SQL and why is it used?
SQL (Structured Query Language) is used to manage and manipulate relational databases. It allows users to retrieve, insert, update, and delete data efficiently.
2. Difference between SQL and MySQL
- SQL is a language used to interact with databases.
- MySQL is a relational database management system (RDBMS) that uses SQL.
Think of SQL as the language, and MySQL as the software that understands and processes it.
3. What are primary keys and foreign keys? ๐
- Primary Key uniquely identifies each row in a table. It must be unique and not null.
- Foreign Key links one table to another. It references the primary key of another table to maintain referential integrity.
4. What is a unique constraint?
It ensures that all values in a column (or combination of columns) are unique across the table. Unlike primary keys, columns with a unique constraint can accept one NULL.
5. Difference between WHERE and HAVING
- WHERE filters rows before aggregation.
- HAVING filters groups after aggregation.
Example: Use WHERE for filtering raw data, HAVING for filtering GROUP BY results.
6. What are joins? Types of joins? ๐ค
Joins combine data from multiple tables based on related columns.
Types:
- INNER JOIN โ Returns matching rows
- LEFT JOIN โ All rows from left table + matched rows from right
- RIGHT JOIN โ All rows from right table + matched from left
- FULL JOIN โ All rows from both tables
- CROSS JOIN โ Cartesian product
7. Difference between INNER JOIN and LEFT JOIN
- INNER JOIN only returns rows with matching keys in both tables.
- LEFT JOIN returns all rows from the left table, plus matching rows from the right table (NULLs if no match).
8. What is a subquery?
A subquery is a query nested inside another SQL query. It can be used in SELECT, FROM, or WHERE clauses to fetch intermediate results.
9. What are CTEs (Common Table Expressions)?
CTEs are temporary named result sets that make queries more readable and reusable.
Syntax:
WITH cte_name AS (
SELECT ...
)
SELECT * FROM cte_name;
10. What is a view in SQL?
A view is a virtual table based on a SQL query. It doesn't store data itself but provides a way to simplify complex queries, improve security, and reuse logic.
Double Tap โค๏ธ For Part-2
โค55
Top SQL Interview Questions with Answers: Part-2 ๐ง
11. How do you remove duplicate records? ๐๏ธ
Use DISTINCT or ROW_NUMBER() with a CTE to delete duplicates.
12. What is normalization? Explain its types. ๐งฑ
Normalization reduces redundancy and improves data integrity.
- 1NF: Atomic columns (no repeating groups)
- 2NF: 1NF + no partial dependency
- 3NF: 2NF + no transitive dependency
- BCNF: Advanced version of 3NF
13. What is denormalization?
The process of combining tables to improve read speed by introducing redundancy. Used for reporting and faster queries. โก
14. What is a stored procedure?
A saved set of SQL statements that can be reused. ๐พ
15. What are indexes and why are they used?
Indexes speed up query performance by allowing quick data lookup. Useful on columns used in WHERE or JOIN clauses. ๐๏ธ
16. What is the difference between clustered and non-clustered index?
- Clustered: Sorts actual table data. Only one per table. (Physical Order)
- Non-clustered: Separate structure that references data. Can have many. (Logical Order)
17. What is a transaction?
A group of operations treated as a single unit. It follows ACID principles to maintain data integrity.
18. ACID properties in SQL
- Atomicity: All or none of the operations run (All-or-Nothing)
- Consistency: Data stays valid before/after transaction โ๏ธ
- Isolation: Transactions donโt interfere ๐ง
- Durability: Changes remain after success โ
19. Difference between DELETE, TRUNCATE, and DROP
- DELETE: Removes rows, can be rolled back (logged). โช
- TRUNCATE: Removes all rows, faster, less logging. ๐๏ธ
- DROP: Deletes table structure and data entirely. ๐ฅ
20. What is a NULL value in SQL?
NULL represents missing or unknown data. It's different from 0 or an empty string. (Unknown, not Zero.)
๐ฌ Double Tap โค๏ธ For Part-3
11. How do you remove duplicate records? ๐๏ธ
Use DISTINCT or ROW_NUMBER() with a CTE to delete duplicates.
SELECT DISTINCT * FROM table_name;
Or:sql
WITH Ranked AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY id) AS rn
FROM table_name
)
DELETE FROM Ranked WHERE rn > 1;
12. What is normalization? Explain its types. ๐งฑ
Normalization reduces redundancy and improves data integrity.
- 1NF: Atomic columns (no repeating groups)
- 2NF: 1NF + no partial dependency
- 3NF: 2NF + no transitive dependency
- BCNF: Advanced version of 3NF
13. What is denormalization?
The process of combining tables to improve read speed by introducing redundancy. Used for reporting and faster queries. โก
14. What is a stored procedure?
A saved set of SQL statements that can be reused. ๐พ
CREATE PROCEDURE GetUsers AS
BEGIN
SELECT * FROM users;
END;
15. What are indexes and why are they used?
Indexes speed up query performance by allowing quick data lookup. Useful on columns used in WHERE or JOIN clauses. ๐๏ธ
16. What is the difference between clustered and non-clustered index?
- Clustered: Sorts actual table data. Only one per table. (Physical Order)
- Non-clustered: Separate structure that references data. Can have many. (Logical Order)
17. What is a transaction?
A group of operations treated as a single unit. It follows ACID principles to maintain data integrity.
18. ACID properties in SQL
- Atomicity: All or none of the operations run (All-or-Nothing)
- Consistency: Data stays valid before/after transaction โ๏ธ
- Isolation: Transactions donโt interfere ๐ง
- Durability: Changes remain after success โ
19. Difference between DELETE, TRUNCATE, and DROP
- DELETE: Removes rows, can be rolled back (logged). โช
- TRUNCATE: Removes all rows, faster, less logging. ๐๏ธ
- DROP: Deletes table structure and data entirely. ๐ฅ
20. What is a NULL value in SQL?
NULL represents missing or unknown data. It's different from 0 or an empty string. (Unknown, not Zero.)
๐ฌ Double Tap โค๏ธ For Part-3
โค35
โ
Top SQL Interview Questions with Answers: Part-3 ๐ง
21. How do you handle NULLs in queries?
Use IS NULL, IS NOT NULL, COALESCE(), or IFNULL() to manage NULLs.
Example:
22. What is COALESCE() in SQL?
It returns the first non-NULL value from a list.
23. What are aggregate functions? ๐
Functions that perform calculations on multiple rows:
- COUNT()
- SUM()
- AVG()
- MAX()
- MIN()
24. What is GROUP BY and how does it work?
It groups rows that have the same values and is used with aggregate functions.
25. What is the difference between COUNT(\*) and COUNT(column)?
- COUNT(\*): Counts all rows, including those with NULLs.
- COUNT(column): Counts non-NULL values in that column.
26. What are window functions? ๐ช
They perform calculations across rows related to the current row without collapsing results.
Examples:
27. Difference between RANK(), DENSE_RANK(), and ROW_NUMBER()
- RANK(): Skips ranks on ties (1, 1, 3)
- DENSE_RANK(): No gaps in ranking (1, 1, 2)
- ROW_NUMBER(): Unique sequence for each row (1, 2, 3)
28. What is the use of LAG() and LEAD()?
They access previous (LAG) or next (LEAD) row values in the result set.
29. What is a CASE statement?
It's used for conditional logic in queries.
30. What is the difference between CHAR and VARCHAR?
- CHAR(n): Fixed-length, always reserves
- VARCHAR(n): Variable-length, uses space based on actual content. (More efficient for varying lengths)
๐ฌ Double Tap โค๏ธ For Part-4
21. How do you handle NULLs in queries?
Use IS NULL, IS NOT NULL, COALESCE(), or IFNULL() to manage NULLs.
Example:
SELECT name FROM users WHERE email IS NULL;
22. What is COALESCE() in SQL?
It returns the first non-NULL value from a list.
SELECT COALESCE(phone, 'Not Provided') FROM customers;
23. What are aggregate functions? ๐
Functions that perform calculations on multiple rows:
- COUNT()
- SUM()
- AVG()
- MAX()
- MIN()
24. What is GROUP BY and how does it work?
It groups rows that have the same values and is used with aggregate functions.
SELECT department, COUNT(*) FROM employees GROUP BY department;
25. What is the difference between COUNT(\*) and COUNT(column)?
- COUNT(\*): Counts all rows, including those with NULLs.
- COUNT(column): Counts non-NULL values in that column.
26. What are window functions? ๐ช
They perform calculations across rows related to the current row without collapsing results.
Examples:
ROW_NUMBER(), RANK(), SUM() OVER()27. Difference between RANK(), DENSE_RANK(), and ROW_NUMBER()
- RANK(): Skips ranks on ties (1, 1, 3)
- DENSE_RANK(): No gaps in ranking (1, 1, 2)
- ROW_NUMBER(): Unique sequence for each row (1, 2, 3)
28. What is the use of LAG() and LEAD()?
They access previous (LAG) or next (LEAD) row values in the result set.
SELECT name, salary, LAG(salary) OVER (ORDER BY id) AS prev_salary FROM employees;
29. What is a CASE statement?
It's used for conditional logic in queries.
SELECT name,
CASE
WHEN salary > 5000 THEN 'High'
ELSE 'Low'
END AS salary_level
FROM employees;
30. What is the difference between CHAR and VARCHAR?
- CHAR(n): Fixed-length, always reserves
n characters. (Padding with spaces if shorter)- VARCHAR(n): Variable-length, uses space based on actual content. (More efficient for varying lengths)
๐ฌ Double Tap โค๏ธ For Part-4
โค27
โ
Top SQL Interview Questions with Answers: Part-4 ๐ง
31. What are constraints in SQL?
Constraints are rules applied to columns to enforce data integrity:
โข PRIMARY KEY โ Uniquely identifies each record
โข FOREIGN KEY โ Ensures referential integrity
โข UNIQUE โ Ensures all values are different
โข NOT NULL โ Prevents null values
โข CHECK โ Restricts values based on condition
โข DEFAULT โ Assigns a default value
32. What is a composite key?
A composite key is a combination of two or more columns that together uniquely identify a row.
Example: (StudentID, CourseID) in an enrollment table.
33. What are scalar vs table-valued functions?
โข Scalar function: Returns a single value (e.g., LEN(), GETDATE())
โข Table-valued function: Returns a table/data set and can be used in FROM clause
34. How does indexing affect performance?
Indexes improve read performance (SELECT) by allowing faster searches.
Downsides:
โข Slower write operations (INSERT, UPDATE, DELETE)
โข Takes additional storage
35. What is data integrity?
Ensures the accuracy, consistency, and reliability of data throughout its lifecycle.
Maintained using constraints, transactions, and normalization.
36. What are triggers in SQL?
Triggers are automatic actions executed in response to certain events on a table (e.g., INSERT, UPDATE, DELETE).
Used for auditing, enforcing rules, or updating related tables.
37. What is a correlated subquery?
A subquery that depends on the outer query for its values. Itโs evaluated once for each row of the outer query.
Example:
SELECT name FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept_id = e.dept_id);
38. What is a cross join?
Combines each row from one table with every row from another โ produces Cartesian product.
Used rarely, typically when all combinations are needed.
39. What is UNION vs UNION ALL?
โข UNION: Combines two queries, removes duplicates
โข UNION ALL: Combines all rows, keeps duplicates
Both require same number and type of columns.
40. Difference between EXISTS and IN
โข IN: Checks if a value exists in a list
โข EXISTS: Checks if subquery returns any rows
EXISTS is often faster with large subqueries or joins.
๐ฌ Double Tap โค๏ธ For Part-5
31. What are constraints in SQL?
Constraints are rules applied to columns to enforce data integrity:
โข PRIMARY KEY โ Uniquely identifies each record
โข FOREIGN KEY โ Ensures referential integrity
โข UNIQUE โ Ensures all values are different
โข NOT NULL โ Prevents null values
โข CHECK โ Restricts values based on condition
โข DEFAULT โ Assigns a default value
32. What is a composite key?
A composite key is a combination of two or more columns that together uniquely identify a row.
Example: (StudentID, CourseID) in an enrollment table.
33. What are scalar vs table-valued functions?
โข Scalar function: Returns a single value (e.g., LEN(), GETDATE())
โข Table-valued function: Returns a table/data set and can be used in FROM clause
34. How does indexing affect performance?
Indexes improve read performance (SELECT) by allowing faster searches.
Downsides:
โข Slower write operations (INSERT, UPDATE, DELETE)
โข Takes additional storage
35. What is data integrity?
Ensures the accuracy, consistency, and reliability of data throughout its lifecycle.
Maintained using constraints, transactions, and normalization.
36. What are triggers in SQL?
Triggers are automatic actions executed in response to certain events on a table (e.g., INSERT, UPDATE, DELETE).
Used for auditing, enforcing rules, or updating related tables.
37. What is a correlated subquery?
A subquery that depends on the outer query for its values. Itโs evaluated once for each row of the outer query.
Example:
SELECT name FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept_id = e.dept_id);
38. What is a cross join?
Combines each row from one table with every row from another โ produces Cartesian product.
Used rarely, typically when all combinations are needed.
39. What is UNION vs UNION ALL?
โข UNION: Combines two queries, removes duplicates
โข UNION ALL: Combines all rows, keeps duplicates
Both require same number and type of columns.
40. Difference between EXISTS and IN
โข IN: Checks if a value exists in a list
โข EXISTS: Checks if subquery returns any rows
EXISTS is often faster with large subqueries or joins.
๐ฌ Double Tap โค๏ธ For Part-5
โค23๐2
โ
Top SQL Interview Questions with Answers: Part-5 ๐ง
41. What are set operations in SQL?
Set operations combine results from multiple SELECT queries:
โข UNION: Combines results and removes duplicates.
โข UNION ALL: Combines all results, including duplicates.
โข INTERSECT: Returns only the common records between two queries.
โข EXCEPT / MINUS: Returns records from the first query that are not in the second.
42. What is a materialized view?
Unlike a normal view (which is virtual), a materialized view stores actual data physically on disk.
It improves performance for complex queries by pre-computing and storing the results, and it can be refreshed manually or automatically to reflect changes in the underlying data.
43. Explain the BETWEEN operator.
The BETWEEN operator is used to filter data within a specified range, including both endpoints.
Example:
44. What is a pivot table in SQL?
A pivot table transforms rows into columns, which is helpful for summarizing data.
It can be created using GROUP BY, CASE statements, or database-specific PIVOT keywords.
Example: Monthly sales data pivoted by region.
45. How do you optimize SQL queries?
To optimize SQL queries, consider the following strategies:
โข Use indexes effectively on frequently queried columns.
โข Avoid using
โข Use WHERE clauses to filter data as early as possible.
โข Prefer EXISTS over IN for subqueries to improve performance.
โข Analyze execution plans to identify bottlenecks.
โข Avoid unnecessary joins or deeply nested subqueries.
46. How do you handle slow queries?
To address slow queries, you can:
โข Check and optimize indexes on columns used in filters.
โข Break large queries into smaller, more manageable parts.
โข Implement caching strategies to reduce load times.
โข Limit the number of returned rows using LIMIT or TOP clauses.
โข Use EXPLAIN or QUERY PLAN to analyze and diagnose performance issues.
47. Whatโs the use of execution plan in SQL?
An execution plan illustrates how the database engine will execute a given query.
It helps identify slow operations (like full table scans) and suggests areas for optimization.
You can view execution plans using EXPLAIN in MySQL/PostgreSQL or SET SHOWPLAN_ALL in SQL Server.
48. Whatโs the use of LIMIT / OFFSET?
โข LIMIT: Restricts the number of rows returned by a query.
โข OFFSET: Skips a specified number of rows before starting to return results.
Example:
This is particularly useful for implementing pagination.
49. How do you import/export data in SQL?
โข Importing Data: Use commands like LOAD DATA INFILE, BULK INSERT, or utilize import tools provided by database management systems.
โข Exporting Data: Use SELECT INTO OUTFILE, mysqldump, pg_dump, or export data to CSV from GUI tools.
50. How would you clean messy data using SQL?
To clean messy data, you can apply several functions:
โข Use
โข Use
โข Handle NULL values with
โข Use
โข Utilize subqueries or Common Table Expressions (CTEs) to identify and remove duplicates or invalid entries.
๐ก Double Tap โฅ๏ธ For More
41. What are set operations in SQL?
Set operations combine results from multiple SELECT queries:
โข UNION: Combines results and removes duplicates.
โข UNION ALL: Combines all results, including duplicates.
โข INTERSECT: Returns only the common records between two queries.
โข EXCEPT / MINUS: Returns records from the first query that are not in the second.
42. What is a materialized view?
Unlike a normal view (which is virtual), a materialized view stores actual data physically on disk.
It improves performance for complex queries by pre-computing and storing the results, and it can be refreshed manually or automatically to reflect changes in the underlying data.
43. Explain the BETWEEN operator.
The BETWEEN operator is used to filter data within a specified range, including both endpoints.
Example:
SELECT * FROM products WHERE price BETWEEN 100 AND 500;
44. What is a pivot table in SQL?
A pivot table transforms rows into columns, which is helpful for summarizing data.
It can be created using GROUP BY, CASE statements, or database-specific PIVOT keywords.
Example: Monthly sales data pivoted by region.
45. How do you optimize SQL queries?
To optimize SQL queries, consider the following strategies:
โข Use indexes effectively on frequently queried columns.
โข Avoid using
SELECT *; specify only the needed columns.โข Use WHERE clauses to filter data as early as possible.
โข Prefer EXISTS over IN for subqueries to improve performance.
โข Analyze execution plans to identify bottlenecks.
โข Avoid unnecessary joins or deeply nested subqueries.
46. How do you handle slow queries?
To address slow queries, you can:
โข Check and optimize indexes on columns used in filters.
โข Break large queries into smaller, more manageable parts.
โข Implement caching strategies to reduce load times.
โข Limit the number of returned rows using LIMIT or TOP clauses.
โข Use EXPLAIN or QUERY PLAN to analyze and diagnose performance issues.
47. Whatโs the use of execution plan in SQL?
An execution plan illustrates how the database engine will execute a given query.
It helps identify slow operations (like full table scans) and suggests areas for optimization.
You can view execution plans using EXPLAIN in MySQL/PostgreSQL or SET SHOWPLAN_ALL in SQL Server.
48. Whatโs the use of LIMIT / OFFSET?
โข LIMIT: Restricts the number of rows returned by a query.
โข OFFSET: Skips a specified number of rows before starting to return results.
Example:
SELECT * FROM users LIMIT 10 OFFSET 20;
This is particularly useful for implementing pagination.
49. How do you import/export data in SQL?
โข Importing Data: Use commands like LOAD DATA INFILE, BULK INSERT, or utilize import tools provided by database management systems.
โข Exporting Data: Use SELECT INTO OUTFILE, mysqldump, pg_dump, or export data to CSV from GUI tools.
50. How would you clean messy data using SQL?
To clean messy data, you can apply several functions:
โข Use
TRIM() to remove leading and trailing spaces.โข Use
REPLACE() to eliminate unwanted characters or strings.โข Handle NULL values with
COALESCE() to provide default values.โข Use
CASE statements for conditional transformations of data.โข Utilize subqueries or Common Table Expressions (CTEs) to identify and remove duplicates or invalid entries.
๐ก Double Tap โฅ๏ธ For More
โค29๐1
โ
Must-Know Data Abbreviations & Terms ๐๐ง
SQL โ Structured Query Language
CSV โ Comma-Separated Values
ETL โ Extract, Transform, Load
KPI โ Key Performance Indicator
EDA โ Exploratory Data Analysis
BI โ Business Intelligence
DBMS โ Database Management System
API โ Application Programming Interface
JSON โ JavaScript Object Notation
ML โ Machine Learning
NoSQL โ Non-relational Database
RDBMS โ Relational Database Management System
ROC โ Receiver Operating Characteristic
AUC โ Area Under Curve
RMSE โ Root Mean Square Error
๐ฌ Double Tap โค๏ธ for more!
SQL โ Structured Query Language
CSV โ Comma-Separated Values
ETL โ Extract, Transform, Load
KPI โ Key Performance Indicator
EDA โ Exploratory Data Analysis
BI โ Business Intelligence
DBMS โ Database Management System
API โ Application Programming Interface
JSON โ JavaScript Object Notation
ML โ Machine Learning
NoSQL โ Non-relational Database
RDBMS โ Relational Database Management System
ROC โ Receiver Operating Characteristic
AUC โ Area Under Curve
RMSE โ Root Mean Square Error
๐ฌ Double Tap โค๏ธ for more!
โค66
Data Analyst Interview Questions with Answers: Part-1 ๐ง
1๏ธโฃ What is the role of a data analyst?
A data analyst collects, processes, and analyzes data to help businesses make data-driven decisions. They use tools like SQL, Excel, and visualization software (Power BI, Tableau) to identify trends, patterns, and insights.
2๏ธโฃ Difference between data analyst and data scientist
โข Data Analyst: Focuses on descriptive analysis, reporting, and visualization using structured data.
โข Data Scientist: Works on predictive modeling, machine learning, and advanced statistics using both structured and unstructured data.
3๏ธโฃ What are the steps in the data analysis process?
1. Define the problem
2. Collect data
3. Clean and preprocess data
4. Analyze data
5. Visualize and interpret results
6. Communicate insights to stakeholders
4๏ธโฃ What is data cleaning and why is it important?
Data cleaning is the process of fixing or removing incorrect, incomplete, or duplicate data. Clean data ensures accurate analysis, improves model performance, and reduces misleading insights.
5๏ธโฃ Explain types of data: structured vs unstructured
โข Structured: Organized data (e.g., tables in SQL, Excel).
โข Unstructured: Text, images, audio, video โ data that doesnโt fit neatly into tables.
6๏ธโฃ What are primary and foreign keys in databases?
โข Primary key: Unique identifier for a table row (e.g., Employee_ID).
โข Foreign key: A reference to the primary key in another table to establish a relationship.
7๏ธโฃ Explain normalization and denormalization
โข Normalization: Organizing data to reduce redundancy and improve integrity (usually via multiple related tables).
โข Denormalization: Combining tables for performance gains, often in reporting or analytics.
8๏ธโฃ What is a JOIN in SQL? Types of joins?
A JOIN combines rows from two or more tables based on related columns.
Types:
โข INNER JOIN
โข LEFT JOIN
โข RIGHT JOIN
โข FULL OUTER JOIN
โข CROSS JOIN
9๏ธโฃ Difference between INNER JOIN and LEFT JOIN
โข INNER JOIN: Returns only matching rows in both tables.
โข LEFT JOIN: Returns all rows from the left table and matching rows from the right; unmatched right-side values become NULL.
๐ Write a SQL query to find duplicate rows
This identifies values that appear more than once in the specified column.
๐ฌ Double Tap โฅ๏ธ For Part-2
1๏ธโฃ What is the role of a data analyst?
A data analyst collects, processes, and analyzes data to help businesses make data-driven decisions. They use tools like SQL, Excel, and visualization software (Power BI, Tableau) to identify trends, patterns, and insights.
2๏ธโฃ Difference between data analyst and data scientist
โข Data Analyst: Focuses on descriptive analysis, reporting, and visualization using structured data.
โข Data Scientist: Works on predictive modeling, machine learning, and advanced statistics using both structured and unstructured data.
3๏ธโฃ What are the steps in the data analysis process?
1. Define the problem
2. Collect data
3. Clean and preprocess data
4. Analyze data
5. Visualize and interpret results
6. Communicate insights to stakeholders
4๏ธโฃ What is data cleaning and why is it important?
Data cleaning is the process of fixing or removing incorrect, incomplete, or duplicate data. Clean data ensures accurate analysis, improves model performance, and reduces misleading insights.
5๏ธโฃ Explain types of data: structured vs unstructured
โข Structured: Organized data (e.g., tables in SQL, Excel).
โข Unstructured: Text, images, audio, video โ data that doesnโt fit neatly into tables.
6๏ธโฃ What are primary and foreign keys in databases?
โข Primary key: Unique identifier for a table row (e.g., Employee_ID).
โข Foreign key: A reference to the primary key in another table to establish a relationship.
7๏ธโฃ Explain normalization and denormalization
โข Normalization: Organizing data to reduce redundancy and improve integrity (usually via multiple related tables).
โข Denormalization: Combining tables for performance gains, often in reporting or analytics.
8๏ธโฃ What is a JOIN in SQL? Types of joins?
A JOIN combines rows from two or more tables based on related columns.
Types:
โข INNER JOIN
โข LEFT JOIN
โข RIGHT JOIN
โข FULL OUTER JOIN
โข CROSS JOIN
9๏ธโฃ Difference between INNER JOIN and LEFT JOIN
โข INNER JOIN: Returns only matching rows in both tables.
โข LEFT JOIN: Returns all rows from the left table and matching rows from the right; unmatched right-side values become NULL.
๐ Write a SQL query to find duplicate rows
SELECT column_name, COUNT(*)
FROM table_name
GROUP BY column_name
HAVING COUNT(*) > 1;
This identifies values that appear more than once in the specified column.
๐ฌ Double Tap โฅ๏ธ For Part-2
โค37๐1๐ฅ1
Data Analyst Interview Questions with Answers: Part-2 ๐ง
11. What is a subquery?
A subquery is a query nested inside another SQL query (like SELECT, INSERT, UPDATE, DELETE). It returns data used by the outer query.
Example:
SELECT name FROM students WHERE marks > (SELECT AVG(marks) FROM students);
12. Explain GROUP BY and HAVING clause
โข GROUP BY: Groups rows by a column's values for aggregation (SUM(), COUNT(), etc.)
โข HAVING: Filters aggregated results (like WHERE for groups)
Example:
SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5;
13. What are window functions in SQL?
Window functions perform calculations across a set of rows related to the current row without collapsing rows.
Example: ROW_NUMBER(), RANK(), LEAD(), LAG()
SELECT name, department, RANK() OVER(PARTITION BY department ORDER BY salary DESC) FROM employees;
14. Difference between RANK(), DENSE_RANK(), ROW_NUMBER()
โข ROW_NUMBER(): Unique rank even if values are the same
โข RANK(): Skips ranks for ties
โข DENSE_RANK(): No rank gaps for ties
Example: If two people tie at 2nd place:
โข RANK: 1, 2, 2, 4
โข DENSE_RANK: 1, 2, 2, 3
โข ROW_NUMBER: 1, 2, 3, 4
15. What is a CTE in SQL?
CTE (Common Table Expression) is a temporary result set defined with WITH for better readability and reuse in a query.
Example:
WITH HighEarners AS (
SELECT name, salary FROM employees WHERE salary > 100000
)
SELECT * FROM HighEarners;
16. What is the difference between WHERE and HAVING?
โข WHERE: Filters before grouping (on individual rows)
โข HAVING: Filters after grouping (on aggregates)
Example:
SELECT department, COUNT(*) FROM employees
WHERE active = 1
GROUP BY department
HAVING COUNT(*) > 10;
17. Explain data types in SQL
Data types define the kind of data a column can store:
โข INT, FLOAT โ Numeric
โข VARCHAR, TEXT โ Strings
โข DATE, DATETIME โ Time values
โข BOOLEAN โ True/False values
18. How do you handle NULL values in SQL?
โข Use IS NULL or IS NOT NULL
โข Use functions like COALESCE() to replace NULLs
Example:
SELECT COALESCE(phone, 'Not Provided') FROM customers;
19. What are common data visualization tools?
โข Power BI
โข Tableau
โข Google Data Studio
โข Excel
โข Python libraries: Matplotlib, Seaborn, Plotly
20. When would you use a bar chart vs pie chart?
โข Bar chart: Compare multiple categories clearly
โข Pie chart: Show proportions of a whole (best for 2โ5 categories)
Bar charts are generally more accurate and readable.
๐ฌ Double Tap โฅ๏ธ For Part-3
11. What is a subquery?
A subquery is a query nested inside another SQL query (like SELECT, INSERT, UPDATE, DELETE). It returns data used by the outer query.
Example:
SELECT name FROM students WHERE marks > (SELECT AVG(marks) FROM students);
12. Explain GROUP BY and HAVING clause
โข GROUP BY: Groups rows by a column's values for aggregation (SUM(), COUNT(), etc.)
โข HAVING: Filters aggregated results (like WHERE for groups)
Example:
SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5;
13. What are window functions in SQL?
Window functions perform calculations across a set of rows related to the current row without collapsing rows.
Example: ROW_NUMBER(), RANK(), LEAD(), LAG()
SELECT name, department, RANK() OVER(PARTITION BY department ORDER BY salary DESC) FROM employees;
14. Difference between RANK(), DENSE_RANK(), ROW_NUMBER()
โข ROW_NUMBER(): Unique rank even if values are the same
โข RANK(): Skips ranks for ties
โข DENSE_RANK(): No rank gaps for ties
Example: If two people tie at 2nd place:
โข RANK: 1, 2, 2, 4
โข DENSE_RANK: 1, 2, 2, 3
โข ROW_NUMBER: 1, 2, 3, 4
15. What is a CTE in SQL?
CTE (Common Table Expression) is a temporary result set defined with WITH for better readability and reuse in a query.
Example:
WITH HighEarners AS (
SELECT name, salary FROM employees WHERE salary > 100000
)
SELECT * FROM HighEarners;
16. What is the difference between WHERE and HAVING?
โข WHERE: Filters before grouping (on individual rows)
โข HAVING: Filters after grouping (on aggregates)
Example:
SELECT department, COUNT(*) FROM employees
WHERE active = 1
GROUP BY department
HAVING COUNT(*) > 10;
17. Explain data types in SQL
Data types define the kind of data a column can store:
โข INT, FLOAT โ Numeric
โข VARCHAR, TEXT โ Strings
โข DATE, DATETIME โ Time values
โข BOOLEAN โ True/False values
18. How do you handle NULL values in SQL?
โข Use IS NULL or IS NOT NULL
โข Use functions like COALESCE() to replace NULLs
Example:
SELECT COALESCE(phone, 'Not Provided') FROM customers;
19. What are common data visualization tools?
โข Power BI
โข Tableau
โข Google Data Studio
โข Excel
โข Python libraries: Matplotlib, Seaborn, Plotly
20. When would you use a bar chart vs pie chart?
โข Bar chart: Compare multiple categories clearly
โข Pie chart: Show proportions of a whole (best for 2โ5 categories)
Bar charts are generally more accurate and readable.
๐ฌ Double Tap โฅ๏ธ For Part-3
โค20๐ฅ2๐1๐1