Recently ran through LeetCode’s SQL 50 to rigorously brush up on my database logic. It’s one thing to write a query that returns the right answer; it’s another to write one that scales efficiently under the hood. Here are a few core technical insights and optimizations I found most valuable to revisit: ⚡ EXECUTION & OPTIMIZATION • Favor GROUP BY over Window Functions: Window functions compute values per row without collapsing the dataset, leading to massive memory duplication in large tables. GROUP BY efficiently compresses data into unique combinations first. • Eliminate Multi-Pass Scans: Relying on nested IN and MAX() subqueries forces the database engine to evaluate and scan the same table multiple times. • The "Aggregate-Sort-Limit" Pattern: The most computationally efficient way to find a top record is often to compute the metric, sort it, and slice the top off (GROUP BY ... ORDER BY ... LIMIT 1). You can also leverage your ORDER BY clause to handle secondary tie-breakers natively in a single pass. 🧠 LOGIC & EDGE CASES • The "Aggregate Hack" for NULLs: An empty set is not the same as a NULL value. If an API requires a 1-row NULL result instead of an empty table, wrapping the target in an aggregate function like MAX() or MIN() forces the database to return a single NULL row even if no matches are found. • Rate = Average: Calculating a binary success rate is mathematically identical to taking the average of 1s and 0s. There's rarely a need to count the numerator and denominator separately. • Know Your Ranking Functions: DENSE_RANK() is crucial when finding top unique values (like salaries) because it assigns the same rank to ties without skipping subsequent numbers (1, 1, 2). Using RANK() (1, 1, 3) or ROW_NUMBER() will break your logic on ties. A great exercise in writing cleaner, more highly optimized SQL. Next up: tackling the Advanced SQL 50 track. 📊 #SQL #DataScience #DataEngineering #LeetCode #DatabaseOptimization #PostgreSQL #SQL50
Optimizing SQL Queries with LeetCode's SQL 50
More Relevant Posts
-
🚀 Day 5 – SQL Learning Journey | Indexes & Optimization Today I explored one of the most powerful concepts in SQL — Indexes, which play a key role in improving query performance. 📚 What I learned today: 📌 Indexes & Types – Improve data retrieval speed – Clustered vs Non-Clustered indexes ⚖️ Clustered vs Non-Clustered – Clustered → Physical order of data – Non-Clustered → Logical structure (separate from table) 🛠️ Index Commands – CREATE INDEX – DROP INDEX – REBUILD INDEX 🎯 Index Strategy – Use indexes on frequently filtered columns – Covering Index for better performance – Smart index selection is important 🔑 Index Types – Unique Index – Composite Index – Filtered / Partial Index 💡 Key Takeaway: A well-designed index can turn a slow query into a fast one 🚀 But over-indexing can also hurt performance — balance is key! Learning not just SQL, but how to write optimized and scalable queries 💪 Code pushed to GitHub 📂 🔗 GitHub Repository: https://lnkd.in/gm8Mw8CE #SQL #Database #Performance #LearningJourney #AspNetDeveloper #TechGrowth #InterviewPreparation
To view or add a comment, sign in
-
-
SQL Journey – Day 27: Subqueries Deep Dive (Advanced Practice) Today’s focus: Understanding how subqueries work internally and how to use them effectively for real-world problem solving. This was not just theory — practiced multiple scenarios to understand execution flow and logic building. ⸻ 🔹 What I Explored Subqueries inside SELECT, WHERE: • Using subqueries to fetch intermediate results • Comparing values using nested queries • Writing conditions based on dynamic results ⸻ 🔹 Types of Subqueries Practiced ✅ Single Row Subquery • Returns one value • Used with operators (=, >, <, etc.) ✅ Multi Row Subquery • Returns multiple values • Used with IN, ANY, ALL • Executes row by row ✅ Correlated Subquery • Depends on outer query • Executes row by row ⸻ 🔹 Key Concepts Understood • Subqueries execute inside → outside • Outer query depends on inner query results • Must maintain data type compatibility • Can be nested multiple levels ⸻ 🔹 Real Practice Scenarios • Example: Finding average value using subquery • Correlated subqueries are powerful but expensive • Poor usage can impact performance • Sometimes JOINs are a better alternative ⸻ 💡 Day 27 Realization • Subqueries are not just a concept — they are a thinking pattern • They help break complex problems into smaller logical steps • Mastering them = writing smarter SQL, not longer SQL ⸻ 🔖 Hashtags #SQL #Subqueries #AdvancedSQL #DataAnalytics #LearningJourney #RDBMS #TechCSE
To view or add a comment, sign in
-
-
You've been writing SQL queries wrong this whole time. Not the logic. The performance. Here's what most data engineers don't realise until it's too late 👇 A poorly written query on a 10M row table can take 40 seconds. The same query, rewritten properly? 0.3 seconds. That's not an exaggeration. That's production data I've seen with my own eyes. Here's where most of the waste hides: → SELECT * pulling 50 columns when you need 4 → No partition pruning scanning the whole table every single time → Correlated subqueries running once per row instead of once total → Missing indexes on join keys full table scans disguised as "fast queries" → Joining before filtering instead of filtering before joining The worst part? These queries run every hour on a schedule. Nobody notices. The BI dashboard just feels "a bit slow." And the cloud bill quietly grows. Query optimisation isn't a nice-to-have skill. It's how you save your company thousands of dollars a month without writing a single new feature. Start with EXPLAIN ANALYZE. It tells you exactly where the database is struggling. Read more on this: https://lnkd.in/ePTFGj3t 💬 What's the worst query performance issue you've ever inherited from someone else? #DataEngineering #SQL #QueryOptimisation #DataOps #CloudCosts
To view or add a comment, sign in
-
Hello Everyone, At first, SQL felt simple—just SELECT, WHERE, GROUP BY… But then I hit a wall: 👉 What if the logic itself depends on another query? That’s when I discovered advanced SQL concepts—and everything changed. In this part, I explored: 🔥 Subqueries → Query inside a query (mind = blown 🤯) 🔥 CTEs (WITH clause) → Cleaner, more readable logic 🔥 Views → Save and reuse complex queries like tables 🔥 Breaking complex problems into smaller, manageable steps The biggest shift for me: 👉 Good analysts don’t write complex queries… they write clear ones. Now SQL feels less like coding… and more like structured thinking 🧠 💬 What confused you more—Subqueries or CTEs? #PostgreSQL #SQL #DataAnalytics #DataAnalysis #BusinessIntelligence #LearningJourney #Upskilling #DataScience #CareerGrowth #TechLearning
To view or add a comment, sign in
-
You do not need to memorise every SQL function. You need to know where to find them when you need them. 📌 So I built a complete SQL reference guide 115 functions and clauses across 10 categories, every one with syntax, plain English explanation and a real copy-paste example. Here is everything inside 👇 📐Data Retrieval: SELECT, DISTINCT, ORDER BY, LIMIT, UNION, INTERSECT 🔗Joins: INNER, LEFT, RIGHT, FULL OUTER, CROSS, SELF JOIN 📊Aggregation: COUNT, SUM, AVG, GROUP BY, HAVING, ROLLUP 🔀Filtering and Logic: IN, BETWEEN, LIKE, EXISTS, CASE WHEN, NULLIF 📝String Functions: CONCAT, TRIM, SUBSTRING, REPLACE, STRING_AGG 📅Date and Time: YEAR, MONTH, DATE_TRUNC, DATEDIFF, EOMONTH 🔢Math and Numeric: ROUND, FLOOR, CAST, NULLIF, GREATEST, LEAST ⚡Window Functions: ROW_NUMBER, RANK, LAG, LEAD PERCENT_RANK 🏗️Table Operations: CREATE, INSERT, UPDATE, DELETE, ALTER, INDEX, VIEW 🧠 Advanced SQL: CTEs, Subqueries, PIVOT, EXPLAIN, Recursive CTEs 115 functions. 10 categories. Real examples for every single one. 🎯 Which SQL function do you use most in your daily work? 👇 #SQL #DataAnalyst #SQLReference #DataAnalytics #SQLServer #MySQL #PostgreSQL #DataScience #Analytics #FreeResource #SaveThis #BusinessIntelligence #DataDriven #CareerGrowth #Upskilling #TechSkills #DataEngineering #WindowFunctions #DataCommunity #DataVisualization
To view or add a comment, sign in
-
Day 26 & 27 – SQL Learning Journey Subqueries — a concept that looks difficult at first but becomes very straightforward once you understand the logic behind it. A subquery is simply a query inside another query. Instead of solving everything in one complex statement, you break the problem into smaller steps and let SQL handle it cleanly. Here are the core types I learned: • Single-row subquery Returns one value and is used with operators like =, <, > • Multiple-row subquery Returns multiple values and works with IN, ANY, ALL • Correlated subquery Runs for each row of the outer query and depends on it What I realized : The problem is not subqueries — it’s how we approach them. Once the thinking is clear, they become one of the most useful tools in SQL. 1) Independent (non-correlated) → runs once 2) Dependent (correlated) → runs per row “Only correlated subqueries depend on the outer query.” They help simplify logic, improve readability, and handle real-world use cases more effectively. #SQL #LearningJourney #DataAnalytics #SQLDeveloper #TechSkills
To view or add a comment, sign in
-
-
🚀 𝗗𝗮𝘆 𝟯𝟮 & 𝗗𝗮𝘆 𝟯𝟯 𝗼𝗳 𝗠𝘆 𝗦𝗤𝗟 𝗝𝗼𝘂𝗿𝗻𝗲𝘆 These two days were packed with some powerful SQL concepts — from recursion to performance optimization! 💡 🔍 𝗗𝗮𝘆 𝟯𝟮 – 𝗥𝗲𝗰𝘂𝗿𝘀𝗶𝘃𝗲 𝗖𝗧𝗘𝘀 & 𝗛𝗶𝗲𝗿𝗮𝗿𝗰𝗵𝗶𝗰𝗮𝗹 𝗤𝘂𝗲𝗿𝗶𝗲𝘀 Dived into how recursion works in SQL by splitting problems into base case + recursive step. 📌 𝗘𝘅𝗽𝗹𝗼𝗿𝗲𝗱 𝗵𝗶𝗲𝗿𝗮𝗿𝗰𝗵𝘆-𝗿𝗲𝗹𝗮𝘁𝗲𝗱 𝗰𝗼𝗻𝗰𝗲𝗽𝘁𝘀 𝗹𝗶𝗸𝗲: • START WITH • CONNECT BY PRIOR • LEVEL • SYS_CONNECT_BY_PATH • CONNECT_BY_ROOT 🧠 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗲𝗱 𝗽𝗿𝗼𝗯𝗹𝗲𝗺𝘀: 1️⃣ Generated numbers from 1 to N using recursion 2️⃣ Identified multiple missing values in a sequence This really helped me understand how SQL can handle tree-like and hierarchical data structures efficiently 🌳 ⚡ 𝗗𝗮𝘆 𝟯𝟯 – 𝗜𝗻𝗱𝗲𝘅𝗶𝗻𝗴, 𝗢𝗟𝗔𝗣 𝘃𝘀 𝗢𝗟𝗧𝗣 & 𝗜𝗻𝗱𝘂𝘀𝘁𝗿𝘆 𝗜𝗻𝘀𝗶𝗴𝗵𝘁𝘀 📌 𝗜𝗻𝗱𝗲𝘅𝗶𝗻𝗴 (𝗜𝗻𝘁𝗿𝗼): Indexes improve query performance by reducing the time needed to fetch data — like a shortcut to locate records quickly. 📊 𝗢𝗟𝗧𝗣 𝘃𝘀 𝗢𝗟𝗔𝗣: • 𝗢𝗟𝗧𝗣 (𝗢𝗻𝗹𝗶𝗻𝗲 𝗧𝗿𝗮𝗻𝘀𝗮𝗰𝘁𝗶𝗼𝗻 𝗣𝗿𝗼𝗰𝗲𝘀𝘀𝗶𝗻𝗴): – Handles real-time operations (insert/update/delete) – Fast and optimized for transactions • 𝗢𝗟𝗔𝗣 (𝗢𝗻𝗹𝗶𝗻𝗲 𝗔𝗻𝗮𝗹𝘆𝘁𝗶𝗰𝗮𝗹 𝗣𝗿𝗼𝗰𝗲𝘀𝘀𝗶𝗻𝗴): – Used for analysis and reporting – Works on large datasets with complex queries 🏢 𝗜𝗻𝗱𝘂𝘀𝘁𝗿𝘆 𝗣𝗲𝗿𝘀𝗽𝗲𝗰𝘁𝗶𝘃𝗲: 🚀 𝗦𝘁𝗮𝗿𝘁𝘂𝗽 𝗖𝗼𝗺𝗽𝗮𝗻𝗶𝗲𝘀: • Cost: High • Time: Less • Efficiency: High • Tools: BigQuery, Snowflake 🏢 𝗣𝗿𝗼𝗱𝘂𝗰𝘁-𝗯𝗮𝘀𝗲𝗱 𝗠𝗡𝗖𝘀: • Cost: Medium • Time: Medium • Efficiency: Medium • Tools: PostgreSQL, DB Query tools 🏢 𝗦𝗲𝗿𝘃𝗶𝗰𝗲-𝗯𝗮𝘀𝗲𝗱 𝗠𝗡𝗖𝘀: • Cost: Low • Time: More • Tools: Oracle 📌 𝗩𝗶𝗲𝘄𝘀 (𝗜𝗻𝘁𝗿𝗼): A view is a virtual table created using a query — it helps simplify complex queries and improves reusability. 💪 Slowly building a strong foundation in SQL, one concept at a time! #SQL #LearningJourney #Day32 #Day33 #RecursiveCTE #Indexing #OLAPvsOLTP #Database #Coding
To view or add a comment, sign in
-
-
𝗚𝗼𝗼𝗱 𝗦𝗤𝗟 𝘄𝗼𝗿𝗸𝘀. 𝗖𝗹𝗲𝗮𝗻 𝗦𝗤𝗟 𝗶𝘀 𝗲𝗮𝘀𝘆 𝘁𝗼 𝗿𝗲𝗮𝗱, 𝗱𝗲𝗯𝘂𝗴, 𝗮𝗻𝗱 𝘀𝗰𝗮𝗹𝗲. When you start learning SQL, the main focus is usually getting the correct result. But in real-world projects, writing clean and readable SQL is just as important. Because your queries will be read by: • teammates • analysts • engineers • your future self Here are 4 simple practices that instantly improve your SQL quality 👇 1️⃣ Use aliases for readability Aliases make queries shorter and easier to understand. Instead of repeating long table names, use meaningful aliases. Example: SELECT u.id, u.name, SUM(o.amount) AS total_spent FROM users AS u JOIN orders AS o ON u.id = o.user_id GROUP BY u.id, u.name; 2️⃣ Format queries properly Well-formatted SQL is much easier to debug and maintain. Best practices: • Use uppercase for SQL keywords • Place each clause on a new line • Align JOIN conditions 3️⃣ Follow naming conventions Consistent naming makes databases easier to navigate. Common convention: • snake_case for tables and columns • descriptive column names Example: customer_id order_date total_amount 4️⃣ Avoid SELECT * It might feel convenient, but it can: • slow down queries • retrieve unnecessary data • break code when schema changes Better approach: SELECT order_id, order_date, total_amount FROM orders; 💡 Key takeaway Clean SQL isn't just about style — It makes your queries faster to understand, easier to maintain, and more production-ready. Small habits like these make a big difference in real data projects. Curious to know 👇 What’s one SQL habit that improved your queries the most? #SQL #DataAnalytics #LearningInPublic #SQLTips #DataAnalyticsJourney
To view or add a comment, sign in
-
-
SQL Looked Easy at First. Then Came Joins. The class that almost broke me and the lesson that came out of it. I will be honest with you. There was a moment in my last class where I genuinely considered whether this was for me. SQL started simple enough. Selecting columns, pulling records - manageable. Then the complexity arrived, fast and unannounced. SELECT, FROM - "This is fine." Extracting columns and records. Straightforward. I was feeling confident. WHERE, ORDER BY, GROUP BY, HAVING - "Okay, I am still here." Filtering and sorting data. It was getting tougher but I was keeping up. JOINS and Subqueries - "Wait. What?" Combining tables. Nesting queries inside queries. My brain had to work in ways it had never worked before. "Imagine writing a full query, staring at the screen and being too scared to hit Run."😅 That was me. More than once. And somehow that made me laugh and push through. 💡 What SQL Taught Me The biggest shift was learning to slow down before I type a single line. Understanding what the result should look like before writing the query is everything. Because in SQL, you can run a query, get a result that looks perfectly fine and still be completely wrong. That is the part nobody warns you about. Break the question down. Picture the output. Then query. Stressful? Absolutely. Worth it? Without a doubt. Every tool in this training has pushed me past a wall I did not know I had. SQL just happened to build the tallest one yet. Still standing. Still going. 🚀 Where did SQL start to click for you? You can share below Pushed through with the guidance of Obumneme Udeinya #SQL #DataAnalysis #LearningInPublic #SQLJoins #DataAnalyst #LearningInPublic #GrowthMindset #BeginnersJourney #LMTechHub #Cohort6
To view or add a comment, sign in
-
-
SQL Optimization isn't about writing less code. It's about understanding what happens AFTER you hit run. Most engineers I know can write SQL. Very few understand what it costs. Here's everything that actually matters: 1. The Query Optimizer isn't magic It builds an execution plan based on statistics. Old or missing statistics = bad plan = slow query. Update your stats. Trust the plan less. 2. SARGability is everything SARG = Search ARGument Able. If your filter can't use an index, it scans the whole table. This breaks SARGability: WHERE YEAR(created_at) = 2024 This doesn't: WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01' Same result. Completely different cost. 3. Implicit conversions are silent killers ISNULL(Amount, 0) when Amount is decimal? The engine converts everything to int quietly. Your index? Ignored. 4. Execution Plans > Gut Feeling Before optimizing anything read the plan. Look for: Table Scans, Key Lookups, Sort operators. These are your cost red flags. 5. Indexes aren't free Every index you add speeds up reads. But slows down writes. Design for your actual workload. The real lesson? Writing SQL is a skill. Understanding SQL cost is a discipline. One gets the query working. The other keeps the system alive at 3AM. Which of these did nobody teach you formally?👇 Found Insightful? ♻️ Repost in your network and follow Sahil Alam for more. #SQL #DataEngineering #Analytics #Debugging #DataQuality #Learning
To view or add a comment, sign in
Explore related topics
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
👏🏻👏🏻