TGViewer
Data Science & Machine Learning Data Science & Machine Learning @datasciencefun ยท 77.8K subscribers
Post #4282 4.13K
โœ… Advanced SQL (Subqueries & CTEs) ๐Ÿ—„๏ธ๐Ÿ”ฅ

๐Ÿ‘‰ Now we move to advanced SQL concepts heavily used in:
โœ” Data Analysis
โœ” Reporting
โœ” Dashboards
โœ” Interviews

๐Ÿ”น 1. What is a Subquery?
A subquery is a query written inside another query.

๐Ÿ‘‰ Also called:
โœ… Nested Query

๐Ÿ”ฅ 2. Example of Subquery
๐Ÿ‘‰ Find employees earning above average salary.

SELECT name, salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);

How it works:
1๏ธโƒฃ Inner query calculates average salary
2๏ธโƒฃ Outer query filters employees

๐Ÿ”น 3. Types of Subqueries
โœ” Single-row subquery
โœ” Multiple-row subquery
โœ” Correlated subquery

๐Ÿ”น 4. Correlated Subquery โญ
๐Ÿ‘‰ Inner query depends on outer query.

SELECT e1.name
FROM employees e1
WHERE salary > (
SELECT AVG(salary)
FROM employees e2
WHERE e1.department = e2.department
);

๐Ÿ”ฅ 5. What is a CTE?
CTE = Common Table Expression

๐Ÿ‘‰ Temporary result set used inside a query.

Defined using:
WITH

๐Ÿ”น 6. Example of CTE โญ
WITH avg_salary AS (
SELECT AVG(salary) AS avg_sal
FROM employees
)

SELECT *
FROM employees
WHERE salary > (
SELECT avg_sal FROM avg_salary
);

๐Ÿ”น 7. Why Use CTEs?
โœ” Makes queries readable
โœ” Simplifies complex logic
โœ” Easier debugging

๐Ÿ”น 8. Difference Between Subquery & CTE
Subquery : Nested inside query
CTE : Defined separately

Subquery : Harder to read
CTE : More readable

Subquery : Repeated logic possible
CTE : Reusable

๐Ÿ”น 9. Why This is Important?
โœ” Frequently asked in interviews
โœ” Used in dashboards & analytics
โœ” Important for real-world SQL projects

๐ŸŽฏ Todayโ€™s Goal
โœ” Understand subqueries
โœ” Learn correlated subqueries
โœ” Understand CTEs
โœ” Write cleaner SQL queries

๐Ÿ‘‰ SQL Notes: https://whatsapp.com/channel/0029VbCyzS02ZjCwoShXXc2j

๐Ÿ’ฌ Tap โค๏ธ for more!
  • โค 12
More from @datasciencefun
  1. Oct 9, 2026Post #4657
  2. Oct 9, 2026๐Ÿ‡ฎ๐Ÿ‡ณ ๐—š๐—ข๐—ฉ๐—˜๐—ฅ๐—ก๐— ๐—˜๐—ก๐—ง ๐—ข๐—™ ๐—œ๐—ก๐——๐—œ๐—” โ€” ๐—”๐—œ๐—–๐—ง๐—˜ ๐—œ๐—ก๐—ง๐—˜๐—ฅ๐—ก๐—ฆ๐—›๐—œ๐—ฃ๐—ฆ ๐Ÿฎ๐Ÿฌ๐Ÿฎ๐Ÿฒ ๐Ÿš€โ€ฆ
  3. Oct 8, 2026๐Ÿ”ฌ Kandinsky 6.0 Video: Training Details and Architecture The new Kandinsky 6.0 Video lineโ€ฆ
  4. Oct 8, 2026๐ŸŽ“ ๐— ๐—ถ๐—ฐ๐—ฟ๐—ผ๐˜€๐—ผ๐—ณ๐˜ ๐—™๐—ฅ๐—˜๐—˜ ๐—–๐—ผ๐˜‚๐—ฟ๐˜€๐—ฒ๐˜€ ๐˜„๐—ถ๐˜๐—ต ๐—–๐—ฒ๐—ฟ๐˜๐—ถ๐—ณ๐—ถ๐—ฐ๐—ฎ๐˜๐—ฒ๐˜€! ๐Ÿš€๐Ÿ”ฅ Upgrโ€ฆ
  5. Oct 7, 2026ORDER BY salary DESC LIMIT 5; Mistake 3 โ€” Forgetting that LIMIT applies after sorting Forโ€ฆ
  6. Oct 7, 2026๐Ÿš€ Data Science Roadmap 2026 ๐Ÿ“ Phase 3: SQL for Data Science ๐Ÿ“– Topic 4 โ€” LIMIT LIMIT isโ€ฆ
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook โ†’Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 โ†’