🚀 𝗦𝗤𝗟 𝗝𝗼𝘂𝗿𝗻𝗲𝘆 – 𝗗𝗮𝘆 𝟮𝟲: 𝗜𝗻𝘁𝗿𝗼𝗱𝘂𝗰𝘁𝗶𝗼𝗻 𝘁𝗼 𝗦𝘂𝗯𝗾𝘂𝗲𝗿𝗶𝗲𝘀 Today I explored one of the most powerful concepts in SQL — Subqueries 🔍 🔹 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗮 𝗦𝘂𝗯𝗾𝘂𝗲𝗿𝘆? A subquery is a query inside another query used to perform intermediate calculations and filter results. 💼 𝗥𝗲𝗮𝗹-𝘄𝗼𝗿𝗹𝗱 𝗽𝗲𝗿𝘀𝗽𝗲𝗰𝘁𝗶𝘃𝗲 (𝗠𝗮𝗻𝗮𝗴𝗲𝗿’𝘀 𝗾𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀): Which product performs well? Which store performs well? Which customers perform well? 👉 These types of questions are easily solved using subqueries by comparing individual performance with averages or totals. 🔹 𝗖𝗼𝗿𝗿𝗲𝗹𝗮𝘁𝗲𝗱 𝗦𝘂𝗯𝗾𝘂𝗲𝗿𝘆 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: SELECT cid, cname, category, amt FROM cust c1 WHERE amt > ( SELECT AVG(amt) FROM cust c2 WHERE c2.category = c1.category ); ✔ Here, the inner query depends on the outer query ✔ It runs for each row → making it a correlated subquery 🔹 𝗧𝘆𝗽𝗲𝘀 𝗼𝗳 𝗦𝘂𝗯𝗾𝘂𝗲𝗿𝗶𝗲𝘀 (𝗢𝘃𝗲𝗿𝘃𝗶𝗲𝘄): 📌 𝗕𝗮𝘀𝗲𝗱 𝗼𝗻 𝗥𝗲𝘀𝘂𝗹𝘁 𝗧𝘆𝗽𝗲: Scalar Subquery (single value) Row Subquery Table Subquery 📌 𝗕𝗮𝘀𝗲𝗱 𝗼𝗻 𝗗𝗲𝗽𝗲𝗻𝗱𝗲𝗻𝗰𝘆: Correlated Subquery Non-Correlated Subquery 📌 𝗕𝗮𝘀𝗲𝗱 𝗼𝗻 𝗟𝗼𝗰𝗮𝘁𝗶𝗼𝗻: SELECT clause FROM clause WHERE clause 📌 𝗕𝗮𝘀𝗲𝗱 𝗼𝗻 𝗞𝗲𝘆𝘄𝗼𝗿𝗱𝘀 𝗨𝘀𝗲𝗱: IN EXISTS ANY / ALL 💡 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Subqueries help in breaking complex problems into simpler parts and are widely used in real-world data analysis. 🔥 Day by day, getting closer to mastering SQL! #SQL #LearningJourney #DataAnalytics #Subqueries #Coding #PlacementPreparation #40DaysOfCode
Savvana Lohitha’s Post
More Relevant Posts
-
𝗗𝗮𝘆 𝟮𝟵 – 𝗦𝘂𝗯𝗾𝘂𝗲𝗿𝗶𝗲𝘀 (𝗕𝗮𝘀𝗲𝗱 𝗢𝗻 𝗟𝗼𝗰𝗮𝘁𝗶𝗼𝗻) Today, I explored how subqueries can be used based on where they are placed in a SQL query. This helped me understand that subqueries are not only about what they do, but also about where they are used. And that placement can completely change the logic of a query. 🔹 𝗪𝗵𝗮𝘁 𝗜 𝗟𝗲𝗮𝗿𝗻𝗲𝗱 • 𝗦𝘂𝗯𝗾𝘂𝗲𝗿𝘆 𝗶𝗻 𝗦𝗘𝗟𝗘𝗖𝗧 Used to add calculated values to each row Example: showing overall average along with each record • 𝗦𝘂𝗯𝗾𝘂𝗲𝗿𝘆 𝗶𝗻 𝗪𝗛𝗘𝗥𝗘 Used for dynamic filtering Example: finding second highest values or conditional matches • 𝗦𝘂𝗯𝗾𝘂𝗲𝗿𝘆 𝗶𝗻 𝗙𝗥𝗢𝗠 (𝗗𝗲𝗿𝗶𝘃𝗲𝗱 𝗧𝗮𝗯𝗹𝗲) Treats the subquery as a temporary table Useful for reusing complex calculations • 𝗦𝘂𝗯𝗾𝘂𝗲𝗿𝘆 𝗶𝗻 𝗛𝗔𝗩𝗜𝗡𝗚 Used to filter grouped data after aggregation Helpful for comparing group-level results 💡 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆 Subqueries are not just about logic — they are about placing logic in the right place. That’s what makes SQL queries cleaner, smarter, and more efficient. Step by step, moving toward writing better SQL🚀 #𝗦𝗤𝗟 #𝗦𝘂𝗯𝗾𝘂𝗲𝗿𝗶𝗲𝘀 #𝗗𝗮𝘁𝗮𝗔𝗻𝗮𝗹𝘆𝘁𝗶𝗰𝘀 #𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴𝗝𝗼𝘂𝗿𝗻𝗲𝘆
To view or add a comment, sign in
-
-
🚀𝗗𝗮𝘆 𝟮𝟵 – 𝗦𝗤𝗟 𝗝𝗼𝘂𝗿𝗻𝗲𝘆 Today, I focused on how subqueries can be used 𝙗𝙖𝙨𝙚𝙙 𝙤𝙣 𝙩𝙝𝙚𝙞𝙧 𝙡𝙤𝙘𝙖𝙩𝙞𝙤𝙣 in SQL queries Instead of just learning types, I explored how placing subqueries in different clauses changes the logic. 🔹 𝙐𝙨𝙞𝙣𝙜 𝙎𝙪𝙗𝙦𝙪𝙚𝙧𝙮 𝙞𝙣 𝙎𝙀𝙇𝙀𝘾𝙏 • Helps add extra calculated values to each row • Example: Showing overall average along with each record 🔹 𝙐𝙨𝙞𝙣𝙜 𝙎𝙪𝙗𝙦𝙪𝙚𝙧𝙮 𝙞𝙣 𝙒𝙃𝙀𝙍𝙀 • Helps filter data dynamically • Example: Finding second highest values or conditional matches 🔹 𝙐𝙨𝙞𝙣𝙜 𝙎𝙪𝙗𝙦𝙪𝙚𝙧𝙮 𝙞𝙣 𝙁𝙍𝙊𝙈 (𝘿𝙚𝙧𝙞𝙫𝙚𝙙 𝙏𝙖𝙗𝙡𝙚) • Treats subquery as a temporary table • Makes complex calculations easier to reuse 🔹 𝙐𝙨𝙞𝙣𝙜 𝙎𝙪𝙗𝙦𝙪𝙚𝙧𝙮 𝙞𝙣 𝙃𝘼𝙑𝙄𝙉𝙂 • Filters grouped data after aggregation • Useful for comparing group-level results 💡 𝙒𝙝𝙖𝙩 𝙄 𝙪𝙣𝙙𝙚𝙧𝙨𝙩𝙤𝙤𝙙 𝙩𝙤𝙙𝙖𝙮 Subqueries are not just about logic… They are about 𝙥𝙡𝙖𝙘𝙞𝙣𝙜 𝙩𝙝𝙚 𝙡𝙤𝙜𝙞𝙘 𝙞𝙣 𝙩𝙝𝙚 𝙧𝙞𝙜𝙝𝙩 𝙥𝙡𝙖𝙘𝙚. That’s what makes queries cleaner and more efficient. 📈 Step by step, moving towards writing smarter SQL 🚀 #SQL #LearningJourney #Day29 #Subqueries
To view or add a comment, sign in
-
-
🚀 𝗗𝗮𝘆 𝟮𝟳 – 𝗦𝗤𝗟 𝗝𝗼𝘂𝗿𝗻𝗲𝘆: 𝗦𝘂𝗯𝗾𝘂𝗲𝗿𝗶𝗲𝘀 𝗗𝗲𝗲𝗽 𝗗𝗶𝘃𝗲 Today I focused on understanding how subqueries actually work internally and how to use them effectively in real-world scenarios. This wasn’t just theory — I practiced multiple cases to improve execution flow thinking and logical problem-solving. 🔍 𝗪𝗵𝗮𝘁 𝗜 𝘄𝗼𝗿𝗸𝗲𝗱 𝗼𝗻: Subqueries in SELECT and WHERE Fetching intermediate results using nested queries Writing dynamic conditions based on subquery outputs 📌 𝗧𝘆𝗽𝗲𝘀 𝗼𝗳 𝗦𝘂𝗯𝗾𝘂𝗲𝗿𝗶𝗲𝘀 𝗜 𝗽𝗿𝗮𝗰𝘁𝗶𝗰𝗲𝗱: ✔️ Single Row Subquery → Returns one value → Used with operators like =, >, < ✔️ Multi Row Subquery → Returns multiple values → Used with IN, ANY, ALL ✔️ Correlated Subquery → Depends on outer query → Executes row-by-row (powerful but costly) 🧠 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀: Subqueries execute inside → outside Outer query depends on inner query results Data type compatibility is critical Can be nested at multiple levels ⚡ 𝗥𝗲𝗮𝗹𝗶𝘇𝗮𝘁𝗶𝗼𝗻𝘀: Correlated subqueries are powerful but can hurt performance Poor usage = slow queries Sometimes JOINS are a smarter alternative 💡 𝗙𝗶𝗻𝗮𝗹 𝗧𝗵𝗼𝘂𝗴𝗵𝘁: Subqueries are not just syntax — they’re a thinking pattern. They help break complex problems into smaller logical steps. Mastering them means writing smarter SQL, not longer SQL. #𝗦𝗤𝗟 #𝗦𝘂𝗯𝗾𝘂𝗲𝗿𝗶𝗲𝘀 #𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝘀𝗾𝗹 #𝗗𝗮𝘁𝗮𝗔𝗻𝗮𝗹𝘆𝘁𝗶𝗰𝘀 #𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴𝗝𝗼𝘂𝗿𝗻𝗲𝘆
To view or add a comment, sign in
-
SQL Inrerview questions: 1. Explain INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN with real-world examples. 2. Write a query to find duplicate records in a table. 3. Write SQL to select the 2nd highest salary (even when duplicates exist), e.g., in the engineering department. 4. Use window functions: compare `ROW_NUMBER()`, `RANK()`, and `DENSE_RANK()`. 5. Write a query to get the last transaction each day (with id, datetime, amount). 6. Write a query to list neighborhoods having zero users (across two related tables). 7. How would you debug and optimize a slow SQL query? (Use EXPLAIN plan, indexing, avoid `SELECT `, use partitions.) 8. Explain the difference between OLTP and OLAP and when each is used. 9. What are the differences between WHERE and HAVING clauses with grouping? 10. Define primary key vs. foreign key. What are SQL triggers? What’s a cursor and when is it used? #SQL #SQLInterviewQuestions #DataEngineering #Database #SQLJoins #INNERJOIN #LEFTJOIN #RIGHTJOIN #FULLJOIN #WindowFunctions #ROW_NUMBER #RANK #DENSE_RANK #QueryOptimization #OLTP #OLAP #DataModeling #PrimaryKey #ForeignKey #SQLTriggers #SQLCursor #WHEREvsHAVING #DataAnalytics #BigData #ETL #DataWarehouse #PerformanceTuning #Indexing #QueryExecutionPlan
To view or add a comment, sign in
-
CTE vs Subquery in SQL — It’s not just about syntax, it’s about performance and readability. Most SQL professionals know both Common Table Expressions (CTEs) and Subqueries. But in real-world environments — especially where millions of rows are processed — choosing the right approach can significantly impact maintainability and, in some cases, performance. ✅ When to use CTE - Breaking complex logic into readable steps - Reusing the same intermediate result multiple times - Recursive queries - Improving query structure for debugging and collaboration ✅ When to use Subquery - Simple filters or one-time nested logic - EXISTS / IN conditions - Quick aggregations inside a main query - Cases where compact logic is enough ⚡ Important Note: CTEs are not always automatically faster than subqueries. Performance depends on: - Query optimizer behavior - Indexing - Database engine - Data volume - Execution plan That’s why experienced SQL work is not only about writing queries — it’s about understanding how queries execute. Learning SQL syntax is step one. Knowing where and when to use each approach is what creates impact. #sql #dataengineering #analytics #database #performance #learning
To view or add a comment, sign in
-
STOP writing subqueries just to use ROW_NUMBER(). There’s a much cleaner way. QUALIFY ▶️ If you’ve ever written SQL like this: rank rows wrap it in a subquery then filter WHERE rn = 1 …you were doing extra work. QUALIFY lets you filter the result of a window function directly. Example: Want the latest order per customer? Instead of: 🔹 CTE 🔹subquery 🔹extra nesting You can do it in one clean query. With QUALIFY, SQL reads the way your brain thinks. You calculate the window function… and filter it right there. Perfect for: ✅ deduplication ✅ latest record per ID ✅ top N per group ✅ ranking logic ✅ interview questions ✅ Cleaner SQL. ✅ Less nesting. ✅ Less pain. It honestly feels illegal the first time you use it. 💾 Save this for your next SQL debugging spiral. #SQL #DataEngineering #AnalyticsEngineering #Snowflake #BigQuery #Databricks #DataAnalytics #DataEngineer #TechCareers #LearnSQL
To view or add a comment, sign in
-
-
🗓️ SQL Challenge Day #28: Customers Who Bought All Products 🔹 Find customers who purchased every single product! 🛒 🔹 Problem: Report customers who bought ALL products: ✅ Handle duplicate purchases gracefully ✅ Match total distinct products 🔹 Solution: SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product); ✅ Result: Accepted 💡 Key Takeaway: **COUNT(DISTINCT) + scalar subquery** is the gold standard for "bought all" problems! ⚠️ Why DISTINCT? Customer might buy same product multiple times – we only care about unique products owned. ✅ Subquery `(SELECT COUNT(*) FROM Product)` gives total product universe – clean and maintainable. 👇 Your turn: Have you used this pattern for "completed all courses" or "visited all locations" type problems? Share your use case! #SQL #LeetCode #DataEngineering #ProblemSolving #Coding #LearningInPublic #Database #DataAnalytics
To view or add a comment, sign in
-
-
𝐖𝐫𝐢𝐭𝐢𝐧𝐠 𝐒𝐐𝐋 𝐢𝐬 𝐞𝐚𝐬𝐲. 𝐖𝐫𝐢𝐭𝐢𝐧𝐠 𝐞𝐟𝐟𝐢𝐜𝐢𝐞𝐧𝐭 𝐒𝐐𝐋 𝐢𝐬 𝐰𝐡𝐞𝐫𝐞 𝐭𝐡𝐞 𝐩𝐫𝐨𝐬 𝐬𝐭𝐚𝐧𝐝 𝐨𝐮𝐭. 🔰 RANK vs DENSE_RANK: RANK: Provides a ranking with gaps if there are ties. DENSE_RANK: Provides a ranking without gaps, even in the case of ties. 🔰 HAVING vs WHERE Clause: WHERE: Filters rows before grouping. HAVING: Filters groups after the GROUP BY clause. 🔰 UNION vs UNION ALL: UNION: Removes duplicates and combines results. UNION ALL: Combines results without removing duplicates. 🔰 JOIN vs UNION: JOIN: Combines columns from multiple tables. UNION: Combines rows from multiple tables with similar structure. 🔰 DELETE vs DROP vs TRUNCATE: DELETE: Removes rows, with the option to filter. DROP: Removes the entire table or database. TRUNCATE: Deletes all rows but keeps the table structure. 🔰 CTE vs TEMP TABLE: CTE: Temporary result set used within a single query. TEMP TABLE: Physical temporary table that persists for the session. 🔰 SUBQUERIES vs CTE: SUBQUERIES: Nested queries inside the main query. CTE: Can be more readable and used multiple times in a query. 🔰 ISNULL vs COALESCE: ISNULL: Replaces NULL with a specified value, accepts two parameters. COALESCE: Returns the first non-NULL value from a list of expressions, accepting multiple parameters. 🔰 INTERSECT vs INNER JOIN: INTERSECT: Returns common rows from two queries. INNER JOIN: Combines matching rows from two tables based on a condition. 🔰 EXCEPT vs NOT IN: EXCEPT: Returns rows in the first query but not in the second. NOT IN: Filters rows where a column's value is not in a given list. #Data #SQL #Fabric #DataEngineering #DataAnalyst #Datascience
To view or add a comment, sign in
-
-
Stop writing SQL "Inception." Use CTEs instead. 🛑📖 We’ve all been there: opening a query only to find a subquery, inside a subquery, inside another subquery. It’s hard to read, impossible to debug, and a nightmare for your future self. If you want to move from a "Junior" to a "Senior" SQL mindset, you need to master CTEs (Common Table Expressions). Why CTEs are a game-changer: Readability: They allow you to read code from top to bottom, like a story, rather than from the inside out. Reusability: You can reference the same CTE multiple times in one query. No more copy-pasting the same subquery logic! Debugging: You can test each "layer" of your data transformation individually before joining them all together. The Golden Rule: If your logic has more than two levels of nesting, it’s time for a WITH clause. #SQL #DataEngineering #Database #CodingTips #CleanCode #DataAnalytics #CareerGrowth
To view or add a comment, sign in
-
-
📌CTE vs Subquery in SQL I used to think this was just about syntax. But the more I worked with real queries, the more I realized… > it's about how you approach a problem. Both help you break down logic. But they guide your thinking differently. ✏️ Subquery Use it when your thinking is: Let me first get exactly what I need… then use it. 📌 Common use cases: • Filtering data before a join • Getting latest records (e.g., max date per user) • Removing duplicates early • Applying conditions inside another query ✏️ CTE (WITH clause) Use it when your thinking is: "Let me build this step by step…" 📌 Common use cases: • Breaking complex queries into readable steps • Creating intermediate datasets • Reusing the same logic multiple times • Making debugging easier 💡 Example difference in thinking: > Subquery approach (reduce early) "Get only active users first, then join with orders" > CTE approach (structure steps) Step 1: get users Step 2: get orders Step 3: combine and filter Now something I recently noticed : While going through queries written by experienced professionals, I saw subqueries being used very intentionally. Especially when they wanted to: • Reduce rows early • Avoid unnecessary joins • Prevent duplicate results That changed how I think: It's not about CTE vs Subquery. It's about: ▪️ When do you filter? ▪️ How do you structure the logic? Because that decision impacts: • Performance • Readability • Output accuracy #linkedinforcreators #linkedincreators
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development