r/learnSQL • • Jul 06 '25

My version of an SQL Roadmap

Post image
627 Upvotes

1: Basic

-> What Is SQL

-> Databases & Tables

-> Data Types

-> CRUD (Create, Read, Update, Delete)

2: Queries

-> SELECT Statements

-> WHERE Clauses

-> ORDER BY, GROUP BY

-> LIMIT, DISTINCT

3: Functions X

-> Aggregate: COUNT(), SUM(), AVG()

-> String: UPPER(), LOWER(), CONCAT()

-> Date: NOW(), DATE(), DATEDIFF()

4: Joins

-> INNER JOIN

-> LEFT JOIN

-> RIGHT JOIN

-> FULL JOIN

-> SELF JOIN

5: Subqueries

-> In SELECT, FROM, WHERE

-> Correlated Subqueries

6: Constraints

-> PRIMARY KEY

-> FOREIGN KEY

-> UNIQUE, NOT NULL, CHECK

7: Indexes & Views

-> Indexing For Speed

-> Creating & Using Views

8: Transactions

-> BEGIN, COMMIT, ROLLBACK

-> ACID Properties

9: Normalization

-> 1NF, 2NF, 3NF

-> Avoiding Redundancy

10: Advanced

-> Stored Procedures

-> Triggers

-> Window Functions

-> CTEs (WITH Clause)

11: Comment 'SQL'

-> Get Roadmap

-> Projects

-> Resources


r/learnSQL • • May 04 '26 Bravo Heartwarming

Best way to learn SQL – From someone who’s used it daily for 6+ years in product analytics

481 Upvotes

Most people learning SQL are doing it wrong. Not because they’re not smart — but because they’re solving the wrong problem first.
They open a tutorial, memorize SELECT, FROM, WHERE, JOIN, and then freeze when faced with a real business question. Sound familiar?
Here’s what actually changes things.

SQL is technically a programming language — a declarative one. But stop treating it like the ones you're used to.

Programming languages are about how to do something — loops, logic, conditionals, state. SQL is about what you want. It’s declarative. You describe the result, and the engine figures out how to get there.
This distinction sounds small. It isn’t. The moment you stop trying to “code” in SQL and start trying to describe your desired output, everything clicks.

The framework I use before writing a single line

Step 1 — Nail the business question first
Not the data question. The business question.
“What’s our DAU trend?” is a data question. “Are users actually finding value in the feature we shipped last month?” is a business question. One has a predefined answer. The other requires you to think about what signal actually reflects value — retention? depth of engagement? repeat actions?
Write the question in plain English. If it’s fuzzy on paper, it’ll be even fuzzier in a query.

Step 2 — Define the rules and edge cases before opening your editor
Every business question has hidden complexity. New users vs. returning users? Do you include churned accounts? What counts as an “active” user — any login, or a meaningful action?
Analysts who skip this step write queries fast and fix them for hours. Analysts who do this step write queries slower and ship them right.

Step 3 — Work backwards from the output
Picture the table you want to hand to a stakeholder. What columns are in it? What’s one row? Once you can visualize the output, the query almost writes itself — because now you’re just reverse-engineering it.

Step 4 — Think in granularity, not tables
This is the unlock most beginners miss. Before writing a JOIN, ask: what is the grain of my data?
• Am I working at the user level?
• The session level?
• The event level?
• The day-user level?
Mismatched granularity is the root cause of most wrong answers that look right. A JOIN between a user-level table and an event-level table without handling this will silently inflate your numbers — and stakeholders will trust the wrong insight.
Once you’ve nailed the grain, GROUP BY, aggregations, and window functions stop feeling like syntax to memorize. They become the natural mechanical expression of logic you’ve already worked out.

The meta-lesson
The SQL itself — the syntax, the functions, the query structure — is genuinely the easy part. It’s learnable in weeks.
What takes years to develop is the habit of thinking before you query. Of questioning whether the data you’re reaching for actually answers the question you were asked. Of noticing when an output looks plausible but is subtly wrong.
That’s the gap between someone who can write SQL and someone who does analytics.
Start there.

Happy to answer questions or go deeper on any of this — grain/granularity especially trips people up and I could write a separate post on that alone.


r/learnSQL • • Oct 08 '21

SQL Cheatsheet (Basics)

Post image
422 Upvotes

r/learnSQL • • Dec 29 '22

2023 Update: The Best Resources for Learning SQL

371 Upvotes

As an experienced software engineer with over 7 years of experience, I want to share with you the list of resources I used to learn SQL. I have found these resources to be extremely helpful in my own learning journey and they can be of great value to others as well. Whether you are a beginner looking to get started with SQL or an experienced developer looking to refresh your knowledge, these resources will provide you with the necessary foundation and skills to become proficient in SQL. So, without further ado, here is my list of top resources for learning SQL:

  1. The SQL courses offered by Standford on EDX and instructed by Jennifer Widom are suitable for both beginners and experienced software engineers looking to refresh their knowledge. These courses are free and provide a comprehensive education in SQL, covering a wide range of topics from the fundamentals to advanced concepts such as introduction to relational databases, advanced topics in SQL, Modeling and theory and Semistructured Data. Through interactive quizzes, hands-on exercises, and real-world examples, these courses provide valuable insights and practical skills for anyone looking to learn or improve their SQL skills.

  2. Database Systems The Complete Book is an excellent resource for advanced topics in database systems, including database system implementation, data mining, concurrency control, transaction management, and parallel and distributed databases. While the first part of the book serves as a good foundation, the advanced topics covered in the later sections are particularly noteworthy. I have had this book for several years and continue to refer back to it on a regular basis. If you are looking to master advanced concepts related to RDBMS and SQL in particular, I highly recommend adding this book to your library. It will be a valuable resource in your journey towards expertise in database systems.

  3. The sixth edition of Database System Concepts is a widely respected text in database education. It introduces basic and fundamental concepts in a straightforward manner and aims to help students start working with databases as soon as possible. The book is divided into ten sections, covering topics such as relational databases, system architecture, speciality databases, and transaction management. It also includes chapters on object-relational mapping, relevance ranking using terms, and distributed data storage. This edition includes revised coverage of SQL, with a focus on the variations of SQL used in actual systems and SQL features. It also introduces new material on support vector machines and the validation of classifiers. The text emphasizes practical applications and implementation, while also providing comprehensive coverage of key theoretical concepts. Algorithms and concepts are presented in a general setting, with annotations and variations specific to particular database systems also included. The only prerequisites for understanding the book are familiarity with computer organization, basic data structures, and a high-level programming language. This edition, published by Tata McGraw-Hill Education in 2013, features a new running example of a university database and more complex design tradeoffs in the database design chapters.

  4. The 3rd edition of Learning SQL: Generate, Manipulate, and Retrieve Data is a useful resource for those new to SQL. In comparison to other books on the subject, this one is relatively easy to read and has some helpful content. While it may not be my go-to resource for advanced concepts, it could be a useful starting point for those just getting started with SQL. It's always helpful to have multiple resources at one's disposal when learning a new skill, and this book could definitely be a useful addition to a beginner's toolkit.

  5. I highly recommend the Fundamentals of Data Engineering: Plan and Build Robust Data Systems book to anyone interested in data engineering. Although the book is not directly about SQL, it covers a wide range of topics that are essential for building robust data systems. The book is structured around the "Data Engineering Lifecycle," with chapters devoted to ingestion, storage, transformation, serving, cloud economics, data models, schema, security, and more. Each chapter includes best practices and potential pitfalls, making it an invaluable resource for anyone looking to learn about data engineering. In my experience, this book has been an absolute game-changer. It is very clearly laid out and covers all the key concepts in great detail. Whether you are a beginner looking to get started with data engineering or an experienced developer looking to expand your knowledge, this book is a must-read. I have no doubt that it will become an invaluable resource for anyone who picks it up.

In conclusion, the books mentioned in this post are all excellent resources for learning SQL and data engineering. Whether you are a beginner looking to get started with these important programming languages or an experienced developer looking to refresh your knowledge and skills, these books will provide you with the foundation and guidance you need to succeed. It's important to remember that not all resources are created equal, and it's important to choose ones that align with your learning style and goals. Avoid wasting time on resources that are not helpful or that don't provide the depth of knowledge you need. Each book has its own unique strengths and approaches, so be sure to consider which one aligns best with your needs. And remember, it's always a good idea to have multiple resources at your disposal, so don't be afraid to supplement your learning with online courses, tutorials, and other materials as well.

Happy learning!


r/learnSQL • • Mar 09 '26

If you have an SQL interview soon, don’t ignore these small things!!!!

360 Upvotes

I’ve noticed something about SQL interviews.

Most people don’t fail because they don’t know SQL.
They fail because they forget tiny things while typing under pressure. It's pressure!!!

Few examples I’ve seen in real interviews:

1. COUNT(column) vs COUNT(*)

If the column contains NULL values:

  • COUNT(column) → ignores NULLs

  • COUNT(*) → counts every row

So if someone asks “how many rows are there?”, COUNT(column) can give the wrong number!

2. LEFT JOIN + WHERE trap

Example:

SELECT *
FROM orders o
LEFT JOIN payments p
ON o.id = p.order_id
WHERE p.status = 'success'

The WHERE condition removes rows where p.status is NULL.

So the LEFT JOIN effectively behaves like an INNER JOIN.

To keep the LEFT JOIN behavior, the condition usually goes in the ON clause.

3. Using DISTINCT to hide join problems

Sometimes joins create duplicates because the relationship isn’t 1-to-1.

A lot of people just do:

SELECT DISTINCT ...

But interviewers usually want you to explain why duplicates appeared in the first place.

4. WHERE vs HAVING

WHERE filters rows before grouping.

HAVING filters after GROUP BY.

So something like this won’t work:

WHERE COUNT(*) > 5

It needs to be:

HAVING COUNT(*) > 5

These are all very small things and basics, but they come up surprisingly often in interviews.

Curious what others have seen.

What’s a small SQL thing people still mess up in interviews even though they know it?

Always interesting to hear these and your interview experiences.


r/learnSQL • • Jul 20 '26

Anyone Want to Learn SQL for Free?

298 Upvotes

I was thinking about this today...

Back in college, I used to teach quite a bit. Later, as I progressed in my IT career, I ended up mentoring a few people in my company who were just getting started. Watching someone go from "I have no idea what's happening" to confidently writing queries on their own was always incredibly rewarding.

It's been years since I've done that, and I genuinely miss it.

So, I'm thinking of starting a few free live SQL sessions for complete beginners or anyone who wants to strengthen their fundamentals.

The goal isn't to memorize syntax—it's to understand how to think in SQL. We'll cover the basics from scratch, work through practical examples, solve real SQL problems together, and do interview-style questions with plenty of Q&A.

I'm not looking to make money from this. If, after a few sessions, you think it was genuinely helpful, buying me a coffee would be more than enough. 😄

If this sounds interesting, send me a DM or leave a comment. If enough people are interested, I'll organize a small group and we'll get started.

Just looking to give back to the community

Note: This is not an advanced SQL course.

It's meant for people who have little to no SQL experience—whether you're a student, switching careers, or someone whose job occasionally requires SQL but you've never really learned it.

We'll start from absolute scratch: what databases are, how SQL works, and gradually build up to writing queries confidently. By the end, my goal is that you'll be comfortable handling the kind of basic to intermediate SQL tasks that come up in many office and analyst roles.

If you're already comfortable with SQL, writing complex queries, optimizing performance, or preparing for senior-level interviews, this probably isn't the right fit..

EDIT :

Hey everyone! 😊

First of all, thank you so much for the amazing response. I honestly did not expect this much interest. I posted this before going to bed, and waking up to 100+ notifications and DMs genuinely made my day. It feels great to see so many people excited to learn SQL.

I need a little time to organize everything properly. I don't want to just share random material—I want to prepare sessions where you actually understand how SQL works, how to think while solving problems, and build a strong foundation.

Since I'm working full-time, I won't be able to start all batches together. Also, having 100+ people in one session would make it difficult for everyone to interact and ask questions. I’ll create smaller batches based on time zones and availability (I'm based in Europe/CEST) and run them in phases.

Please fill out this short form so I can understand your background, SQL level, location, and availability:

Form: https://forms.gle/WAmmDgTnHJY51spm7

If you are not in the first batch, please don't worry. I'll try my best to include everyone over time. Thank you again for your patience and support ❤️


r/learnSQL • • Jun 11 '25

Good SQL cheat Sheet

Post image
279 Upvotes

r/learnSQL • • Apr 04 '26

5 SQL patterns that made my queries 10x cleaner (with examples)

264 Upvotes

Been using SQL for data analysis for a while and wanted to share the patterns that genuinely leveled up my workflow:

  1. CTEs over nested subqueries

Instead of: SELECT * FROM (SELECT * FROM (SELECT ...) a) b

Use: WITH cte AS (SELECT ...) SELECT * FROM cte

Much more readable and reusable.

2. ROW_NUMBER() for deduplication

ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC)

Filter WHERE rn = 1 to get the most recent record per user. Clean and reliable.

3. Conditional aggregation with CASE WHEN

SUM(CASE WHEN status = 'completed' THEN revenue ELSE 0 END) AS completed_revenue

Get multiple slices of data in a single query pass — no need for multiple JOINs.

4. NULLIF to prevent division by zero

revenue / NULLIF(quantity, 0)

Returns NULL instead of throwing an error. Simple but saves a lot of headaches.

5. DATE_TRUNC for clean time grouping

DATE_TRUNC('month', order_date) gives you month-level grouping without string conversions.

Hope this helps anyone who's still getting comfortable with SQL. What patterns do you find yourself using most often?


r/learnSQL • • Dec 08 '20

Best SQL Books (see comments for the list)

Post image
229 Upvotes

r/learnSQL • • Mar 21 '25

What’s a SQL tip or trick you wish you learned earlier?

222 Upvotes

For me, it was discovering that you can use FILTER (WHERE condition) with aggregate functions like COUNT, SUM, and AVG.

It keeps the query cleaner than using CASE WHEN inside an aggregate and just looks way more readable:

SELECT
  COUNT(*) AS total_orders,
  COUNT(*) FILTER (WHERE status = 'delivered') AS delivered_orders
FROM orders;

That one change made a huge difference for me.

What’s your favorite "wish-I-knew-that-earlier" moment in SQL? I’d love to hear it!


r/learnSQL • • Sep 10 '26

If you have SQL interviews, do not ignore these small things! (Part 8)

219 Upvotes

Some SQL interview questions look too easy and that's exactly why people get them wrong by overlook.

  1. COUNT() can give you 0… but SUM() can give you NULL:

Suppose there are no employees age more than 70

SELECT
    COUNT(*) AS employees,
    SUM(salary) AS total_salary
FROM employees
WHERE age > 70;

You might expect:

employees = 0
total_salary = 0

But we will get:

employees = 0
total_salary = NULL

Why?

Because COUNT() is basically asking: “How many rows did I find?” --> answer 0

But SUM() is asking: “What values should I add?” --> no values to add --> NULL

2. AVG() can silently become wrong when NULL enters the picture:

Lets take salary of employees to be:

50000
60000
NULL
90000

A lot of people mentally calculate:

(50000 + 60000 + 90000) / 4 = 50000.0

But actual SQL gives 66666.67. WHy?

Because AVG() ignores NULLs.

It is actually doing:

(50000 + 60000 + 90000) / 3

3. DISTINCT doesn't mean “remove duplicate data”

Lets take one example data for this:

IT    50000
IT    50000
IT    70000
HR    50000

SELECT DISTINCT department, salary
FROM employees;

people sometimes read this as "Give me unique departments"

But actual response:

IT    50000
IT    70000
HR    50000

IT appears twice, because SQL is asking "Give me unique combinations of department + salary"

4. How many different ways can you find the 2nd highest salary?

Lets take this data:

employee_id | name  | salary
------------+-------+--------
1           | A     | 100000
2           | B     | 90000
3           | C     | 90000
4           | D     | 80000
5           | E     | NULL
6           | F     | 70000
7           | G     | NULL

Multiple ways to approach this problem:

MAX() + subquery

SELECT MAX(salary) as 2nd_highest
FROM employees
WHERE salary < (
    SELECT MAX(salary)
    FROM employees
);

DISTINCT + ORDER BY

SELECT DISTINCT salary as 2nd_highest
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary DESC
LIMIT 1 OFFSET 1;

DENSE_RANK()

SELECT salary as 2nd_highest
FROM (
    SELECT salary,
           DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
    FROM employees
)temp
WHERE rnk = 2;

and there are more such ways:

What is actually the best solution with our sample data ?
What are the questions to ask your interviewer to get to perfect solution?

Drop your solution in the comments, we can discuss and improve.

Always practice SQL by writing the query yourself instead of just looking at the solution.


r/learnSQL • • Mar 07 '25

Passed a Job interview! Here are a few tips

210 Upvotes

I've been learning SQL for a while, and I finally decided to start applying for a job!

I wanted to share a few pointers for anyone out there on the same journey.

Once you can confidently apply complex joins and subqueries, you're basically ready. However, learning CTEs, Window Functions, and Regex will give you an extra edge!

Take Notes! I can't stress this enough.

During my interview, I was asked a time-related question that required converting a string to a datetime format and filtering it. Since I’ve been diligently taking notes from my courses and books, I immediately remembered the function I needed.

Make sure to take notes and know where to find them when needed—it makes a huge difference! The interviewer even asked how I managed to write the query so fast because, even for him, it would take a while. (He was awesome, by the way!) I told him I keep a collection of notes with references to useful queries and subqueries, which helps me solve problems quickly.

Next interview is coming up to seal the deal! Just wanted to share my excitement and hopefully motivate you all to keep pushing forward. Wishing you all the best in landing your dream jobs!


r/learnSQL • • Mar 21 '26

If you have an SQL interview soon, don’t ignore these small things (Part 3)

204 Upvotes

I have interviewed quite a few people, and whenever I ask, "How do you filter large data efficiently?"

almost everyone says, "add index!!!" That's it!! It solves our problem, sir!

but when I dig a bit deeper… they don’t realize their own query is not even using that index.

Everyone says indexes make things fast.

Reality is simpler:
* you already have indexes
* your query just made them useless

Here are 6 cases where your index is literally ignored.

1. You indexed it… then destroyed it yourself

WHERE DATE(created_at) = '2025-03-21'

You: "I added index on created_at"
DB: "Cool… I’ll ignore it"

You wrapped the column with the date function→ index order gone

Real fix:

WHERE created_at >= '2024-01-01'
AND created_at < '2024-01-02'

Index works on raw column, not your modified version.

2. You searched backwards… index gave up

WHERE email LIKE '%@gmail.com'

Index can’t even start

Why this hits:
Most people think LIKE always uses index

Better design (store domain separately):

WHERE email_domain = 'gmail.com'

Index is like Google search — it needs a starting word.

If any people knows better solution, please comment!

3. Your query works… but secretly scans everything

WHERE user_id = '123'

Column = INT, but you query as string

DB silently converts types
Index becomes useless

Why this is scary:
No error. No warning. Just slow.

Fix:

WHERE user_id = 123

4. Your “perfect index” fails because of column order

Index:

(user_id, created_at)

Query:

WHERE created_at = '2025-03-21'

Index exists. Still not used.

Why this hits:
People create index… but don’t understand how it’s stored

How Index stored:

user1 → dates  
user2 → dates  
user3 → dates  

You’re searching only by date → no entry point. Needs to be left to right

5. One tiny ‘>’ breaks your whole index

Index:

(user_id, created_at, status)

Query:

WHERE user_id = 10
AND created_at > '2025-03-21'
AND status = 'active'

Index works… then suddenly stops

Example to feel it:

Index is stored like:

user_id = 10
  → 2025-03-01 → active
  → 2025-03-21 → inactive
  → 2025-03-22 → active
  → 2025-03-23 → pending

When you say:

created_at > '2025-03-21'

👉 DB jumps to:

2025-03-21 → ...

From here, data is no longer neatly grouped by status

So:
* It cannot efficiently use status = 'active' from the index
* It has to scan those rows and filter manually

Best solutions (what strong candidates say):

Option 1: Reorder index based on filter priority

(user_id, status, created_at)

6. You think you optimized… you actually forced full scan

SELECT * 
FROM orders
WHERE amount + 10 > 100;

Index on amount = useless

Because you changed the column:

amount + 10

Fix:

WHERE amount > 90

Index only works when column is untouched.

One line that changes everything!!!

Most people think:

"Do I have an index?"

Strong candidates think:

"Is my query written in a way that allows index usage?"

Be the kind of SQL candidate who doesn’t just add indexes…
but actually understands when they work — and when they don’t.


r/learnSQL • • Feb 03 '26

How I Learned SQL in 4 Months Coming from a Non-Technical Background

204 Upvotes

Sharing my insights from an article I wrote back in Nov, 2022 published in Medium as I thought it may be valuable to some here.

For some background, I got hired in a tech logistics company called Upaya as a business analyst after they raised $1.5m in Series A. Since the company was growing fast, they wanted proper dashboards & better reporting for all 4 of their verticals.

They gave me a chance to explore the role as a Data Analyst which I agreed on since I saw potential in that role(especially considering pre-AI days). I had a tight time frame to provide deliverables valuable to the company and that helped me get to something tangible.

The main part of my workflow was SQL as this was integral to the dashboards we were creating as well as conducting analysis & ad-hoc reports. Looking back, the main output was a proper dashboard system custom to requirements of different departments all coded back with SQL. This helped automate much of the reporting process that happened weekly & monthly at the company.

I'm not at the company anymore but my ex-manager said their still using it and have built on top of it. I'm happy with that since the company has grown big and raised $14m (among biggest startup investments in a small country like Nepal).

Here is my learning experience insights:

  1. Start with a real, high-stakes project

I would argue this was the most important thing. It forced me to not meander around as I had accountability up to the CEO and the stakes were high considering the size of the company. It really forced me to be on my A-game and be away from a passive learning mindset into one where you focus on the important. I cannot stress this more!

2. Jump in at the intermediate level

Real-world work uses JOINs, sub-queries, etc. so start immediately with them. By doing this, you will end up covering the basics anyways (especially with A.I. nowadays it makes more sense)

3. Apply the 80/20 rule to queries

20% or so of queries are used more than 80% of the time in real projects.

JOINS, UNION & UNION ALL, CASE WHEN, IF, GROUP BY, ROW_NUMBER, LAG/LEAD are major ones. It is important to give disproportionate attention to them.

Again, if you work on an actual project, this kind of disproportion of use becomes clearer.

4. Seek immediate feedback

Another important point that may not be present especially when self-learning but effective. Tech team validated query accuracy while stakeholders judged usefulness of what I was building. Looking back if that feedback loop wasn't present, I think I would probably go around in circles in many unnecessary areas.

Resources used (all free)
– Book: “Business Analytics for Managers” by Gert Laursen & Jesper Thorlund
– Courses: Datacamp Intermediate SQL, Udacity SQL for Data Analysis
– Reference: W3Schools snippets

You can read my full 6 minute article here: https://anupambajra.medium.com/how-i-learned-sql-in-4-months-coming-from-a-non-technical-background-8482e5aec06e

Fun Fact: This article was shared by 5x NYT best-selling author Tim Ferriss too in his 5 Bullet Friday newsletter.


r/learnSQL • • Feb 26 '25

SQL Meets Sports

Post image
195 Upvotes

r/learnSQL • • Apr 28 '26

If you have SQL interviews do not ignore these small things! (Part 7)

184 Upvotes

In many interviews (from fresher to experienced), this question comes up:

Question:

"You have a table with millions of rows. You run a query with ORDER BY and LIMIT 10.
Will the database only read 10 rows from disk?? "

Most people assume yes, because the query only returns 10 rows.
But what they miss is how the database actually finds those 10 rows.

But in reality, it's not.
There will be a follow-up question:

"If the database ends up scanning the entire table…then what is the point of LIMIT, and how do you avoid a full scan??"

Let's take one example and understand this step by step:

STEP 1: Create a table and insert some dummy data

CREATE TABLE limit_demo AS
SELECT 
    id,
    NOW() - (random() * interval '365 days') AS created_at,
    repeat('data', 50) AS payload
FROM generate_series(1, 1000000) id;

Response:

Updated Rows 1000000

Execute time 2.87s

Created 1 million rows with random timestamps

STEP 2: Check the Query Plan

EXPLAIN ANALYZE
SELECT *
FROM limit_demo
ORDER BY created_at
LIMIT 10;

Response:

Limit

-> Gather Merge

Workers Planned: 2

Workers Launched: 2

-> Sort

Sort Key: created_at

Sort Method: top-N heapsort

-> Parallel Seq Scan on limit_demo (cost=0.00..35462.40 rows=416640 width=216) (actual time=0.298..448.134 rows=333333 loops=3)

What is happening here?

  • Parallel Seq Scan on limit_demo rows=333333 loops=3

  • 2 parallel workers + 1 leader process -> total ~1M rows scanned

  • Internally:

    • Scan all rows

    • Evaluate each row

    • Maintain top 10 (using top-N heapsort)

    • Then return 10

  • Sort is optimized (top-N), but the scan is NOT avoided

Now let’s fix it properly

STEP 3: Create an index on created_at

CREATE INDEX idx_created_at ON limit_demo(created_at);

STEP 4: Check the query planner again

EXPLAIN ANALYZE
SELECT *
FROM limit_demo
ORDER BY created_at
LIMIT 10;

Response:

Limit (cost=0.42..1.94 rows=10 width=216) (actual time=0.411..1.254 rows=10 loops=1)

-> Index Scan using idx_created_at on limit_demo (cost=0.42..151161.74 rows=1000000 width=216) (actual time=0.410..1.251 rows=10 loops=1)

Here you can see:

  • Index Scan

  • No full table scan

  • No sort

  • Very fast execution

Why does this work?

Because the index is already sorted.

Now the database can:

  • jump to the smallest value

  • read next 10 rows

  • stop immediately

Final Understanding:

Without index:

search problem → scan everything

With index:

navigation problem → jump directly

Where does this show up in interviews:

  • Top N highest salary queries

  • Latest 10 transactions using ORDER BY created_at DESC with LIMIT

  • Pagination queries using OFFSET and LIMIT

  • Fetching recent logs or events

Interview Level Takeaway:

Top-N optimization reduces sorting cost, but without an index, the database still scans all rows.

So next time you write query

ORDER BY <column_name> LIMIT 10

Ask yourself:

  • Does the database already know the order…or does it have to figure it out?

  • The real question is not just writing the query, it's understanding how the database executes it.

If this helps even one person understand what’s happening under the hood, it makes me happy!!!


r/learnSQL • • May 31 '26 Bravo

I built a complete SQL learning roadmap covering fundamentals, analytics, projects, and interview preparation. Looking for feedback from experienced SQL users.

178 Upvotes

GitHub

Hi everyone,

Over the past few weeks, I've been building a structured SQL learning repository aimed at aspiring Data Analysts, BI Developers, Business Analysts, and anyone preparing for SQL interviews.

The roadmap covers:

• SQL Fundamentals
• CRUD Operations
• Constraints & Database Design
• Joins & Subqueries
• CASE Statements & Views
• Indexes & Query Optimization
• Stored Procedures & Functions
• CTEs & Window Functions
• Transactions & ACID Properties
• SQL for Data Analytics
• Interview Questions
• Practice Projects

The goal was to create a single learning path that takes someone from absolute beginner level to advanced SQL concepts used in real-world analytics work.

I'm still improving the content and would genuinely appreciate feedback from the community:

  • What topics should be added?

  • Are there any concepts explained poorly?

  • What would make this more useful for learners?

Thanks for taking a look.


r/learnSQL • • Jun 03 '26

Learning SQL in the age of Claude, Codex and Gemini

172 Upvotes

Hey everyone!

Problem: Most SQL courses tend to focus on syntax and classic database systems. But current tech interviews at top startups and bigtech, and real-world systems have evolved far beyond “write a JOIN + WINDOWS statement” to solve problem X.

  1. Our focus: a post-LLM course we've been building and refining for Stanford's modern data systems class for CS/data students. We built this course to help data/CS students better harness SQL in the era of LLMs and AI systems. We cover 'good' LLM prompts to generate and accelerate basic SQL workflows, but more importantly, how to debug whether those queries are correct, scalable, and efficient once the problems become challenging and real. We discuss industry benchmarks on where generated SQL works well, when they fail, and tips on how to work out semantic gaps.

  2. A major focus is connecting SQL to modern systems. We discuss how Claude/Gemini/OpenAI's coding agents use SQL, why AI companies still depend heavily on structured data, and how OpenAI, Anthropic/Claude, Google, Uber, and Spotify approach data infrastructure differently.

Mechanically, the course is part SQL, part data systems. You learn SQL through interactive Colabs and practice systems, then how databases actually work underneath the surface: indexes, query execution, LSM trees, OLTP vs OLAP, vector search, JSONB, distributed systems, and why Postgres, Spark, BigQuery, and Snowflake evolved differently for different workloads.

Link: https://cs145-bigdata.web.app/. login: You can use a Gmail-id to review the material.

The goal is moving beyond “writing queries” toward understanding how modern software and AI systems actually work.

Feedback is super welcome. Every page has inline comments enabled, so feel free to leave thoughts/suggestions directly on the site.


r/learnSQL • • Mar 13 '26 Bravo

If you have an SQL interview soon, don’t ignore these small things (Part 2)

167 Upvotes

My previous post about small SQL mistakes in interviews received over 90k impressions and many interesting responses.

So I thought I’d share a few more that I’ve seen come up quite often.

These are all basic concepts. But under interview pressure, they’re surprisingly easy to miss.

1. NOT IN with NULL values

Consider this query:

SELECT *
FROM orders
WHERE customer_id NOT IN (
    SELECT customer_id
    FROM blacklist
);

If the subquery contains even one NULL value, the entire query may return no rows at all.

This is why many engineers prefer NOT EXISTS.

2. NULL comparisons

This one still surprises people.

WHERE column = NULL

This condition will never be true.

The correct way is:

WHERE column IS NULL

A small detail — but it shows whether someone understands how SQL actually treats NULLs.

3. Window functions without PARTITION

Example:

ROW_NUMBER() OVER (ORDER BY salary)

Without a PARTITION BY, the ranking happens across the entire dataset, not per group.

Sometimes that’s correct.
Sometimes it completely changes the answer.

4. NULL in string concatenation

This one looks simple, but it can surprise people.

Example:

SELECT 'John' || ' ' || NULL;

Many expect the result to be: John

But the actual result is: NULL

Because in SQL, if any part of a concatenation is NULL, the entire result becomes NULL.

A common fix is using COALESCE.

5. NULL and CASE conditions

Consider this query:

SELECT
  CASE 
    WHEN NULL = NULL THEN 'Equal'
    ELSE 'Not Equal'
  END;

Many people expect the result to be: Equal

But the actual result is: Not Equal

Because in SQL, NULL = NULL is not TRUE.
It evaluates to UNKNOWN.

6. NULL and ORDER BY

Consider this query:

SELECT salary
FROM employees
ORDER BY salary DESC;

Now imagine the data:

salary
5000
3000
NULL
2000

Where will the NULL appear?

At the top or the bottom?

The interesting part is that different databases handle this differently.

That’s why SQL allows you to control it explicitly:

ORDER BY salary DESC NULLS LAST

These are small things, but interviewers often use details like this to test how deeply someone understands SQL.

I’m curious — what other small SQL behaviors have you seen people miss in interviews?

I also turned some of these scenarios into SQL challenges on my platform.

You can practice here: https://www.thequerylab.com/

Best of luck!


r/learnSQL • • Mar 24 '26 Bravo

If you have an SQL interview soon, don’t ignore these small things (Part 4)

165 Upvotes

I asked this in an interview recently.

Simple JOIN related questions.

The candidate answered in 10 seconds.

Very Confident!

But Wrong!

  1. How does Inner Join actually work here?

Table A (Id as column name)

1
1
1
2
2
3
NULL
NULL

Table B (Id as column name)

1
1
2
2
2
3
3
NULL

Query:

SELECT *
FROM A
INNER JOIN B
ON A.id = B.id;

Question I asked:

How many rows will this return?

Most answers I get:

  • around 6

  • maybe 8

  • depends on duplicates

Very few actually calculate it.

2. I slightly changed it.

Same data. Just one keyword changed.

Query:

SELECT *
FROM A
LEFT JOIN B
ON A.id = B.id;

How many rows will this return? Same as inner join result???

3. Same 2 tables.
Just one extra condition in JOIN.

That’s it.

Almost everyone gets the count wrong.

Query:

SELECT *
FROM A
LEFT JOIN B
  ON A.id = B.id
 AND B.id = 1;

How many rows will this return?

Do comment with your answer and explanation to learn together!

Don’t just learn SQL syntax.
Play with the data. Break it! Twist it! Shuffle it!

That’s where you understand how SQL actually behaves.

Be that kind of developer.

If you want Part 5 (even more tricky scenarios), pls drop a comment.


r/learnSQL • • Dec 09 '22

SQL Cheat Sheet

Post image
155 Upvotes

r/learnSQL • • Sep 17 '26

If you have an SQL interview soon, don’t ignore these small things!!!! (Part 10)

150 Upvotes

I’ve noticed something about SQL interviews.

Most people don’t fail because they don’t know SQL.
They fail because they forget tiny things while typing under pressure. It's pressure!!!

Few examples I’ve seen in real interviews:

1. NOT IN vs NOT EXISTS

If the list contains NULL values:

  • NOT IN → can return no rows

  • NOT EXISTS → checks if a matching row exists

Example:

SELECT 30
WHERE 30 NOT IN (10, 20, NULL);

internally SQL does this:

30 <> 10      → TRUE
30 <> 20      → TRUE
30 <> NULL    → UNKNOWN

TRUE AND TRUE AND UNKNOWN  = UNKNOWN

So if someone asks "find users who don’t have any subscription", NOT IN can give the wrong result when NULL is involved!

2. ROWS vs RANGE

Example:

SELECT
    sub_date,
    amount,
    SUM(amount) OVER (
        ORDER BY sub_date
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS running_total
FROM subscription;

ROWS works with individual rows, while RANGE works with groups of rows having the same ORDER BY value.

So if multiple orders have the same sub_date, ROWS and RANGE can give different running totals.

3. LEFT JOIN + WHERE can change your result

Example:

SELECT *
FROM users u
LEFT JOIN subscriptions s
    ON u.user_id = s.user_id
WHERE s.plan = 'Pro';

The WHERE condition removes users who don't have a matching subscription.

So even though you wrote LEFT JOIN, you end up keeping only users who have a matching Pro subscription.

If you want to keep all users, put the condition in the ON clause instead:

LEFT JOIN subscriptions s
    ON u.user_id = s.user_id
   AND s.plan = 'Pro'

4. GROUP BY 1,2

This looks perfectly fine:

SELECT department, job_title, COUNT(*)
FROM employees
GROUP BY 1, 2;

But during an interview, especially when you're already under pressure, it can create unnecessary confusion if new column gets added to SELECT

Writing:

GROUP BY department, job_title

takes a little more typing but it's much easier to read, explain and modify later.

These are all very small things and basics, but they come up surprisingly often in interviews.

Curious what others have seen.

What’s a small SQL thing people still mess up in interviews even though they know it?

Always interesting to hear these and your interview experiences.


r/learnSQL • • Apr 07 '26

If you have an SQL interview soon, don’t ignore these small things!!! (Part 6)

144 Upvotes

In this part 6, let’s talk about database internals that you must know for interviews (especially FAANG level).

I’ve asked this in multiple interviews.
Very few candidates get it right.

This is a must-know at any level of experience!

Let's take a PostgreSQL database for this example:

Question:

What actually happens when you DELETE a row from a Table? Will that data be removed from the table & disk?

I get yes as an answer most of the time!

But actually it's no. Let's take one example to understand this:

STEP 1:

Let's create a dummy table

CREATE TABLE delete_demo (
 id SERIAL PRIMARY KEY,
 data TEXT 
);

STEP 2:

Let's add some random data to this table

INSERT INTO delete_demo (data) 
SELECT repeat('data', 1000) 
FROM generate_series(1, 100000); 

STEP 3:

Check the no of records added to this table

SELECT COUNT(*) FROM delete_demo; 

Result: 100000

STEP 4:

Let's print the size of this table

SELECT pg_size_pretty(pg_total_relation_size('delete_demo'));

Result: 13MB

STEP 5:

Let's delete all the records from this table

DELETE FROM delete_demo; 

Result:

Updated Rows 100000

Execute time 0.12s

Start time Tue Apr 07 19:06:04 IST 2026

Finish time Tue Apr 07 19:06:04 IST 2026

Query DELETE FROM delete_demo

STEP 6:

Lets again do the count to check whether all the rows are deleted

SELECT COUNT(*) FROM delete_demo; 

Result: 0

Perfect! All the rows are deleted successfully.

BUT HERE IS THE TRAP!

STEP 7:

As per our expectation, the size should be 0 bytes. Lets run the size of the table query to verify

SELECT pg_size_pretty(pg_total_relation_size('delete_demo'));

Result: 13MB

AGAIN 13MB! WHY?

Because Postgres did NOT physically delete the rows.

Instead:

  • It marks rows as dead (invisible)

  • But keeps them on disk

STEP 8:

Let's see whether dead rows exist

SELECT 
    n_live_tup,
    n_dead_tup
FROM pg_stat_user_tables
WHERE relname = 'delete_demo';

Result:

n_live_tupn_dead_tup
0100000

The table looks empty, but 100000 rows are still sitting on disk

Over time:

  • Updates + Deletes → create dead tuples

You end up with:

  • 2M live rows

  • 10M+ dead rows

This is one of the most common reasons:

Query was fast before… now it’s slow!

To solve this:

  1. Postgres has autovacuum running in background.

  • Automatically cleans dead tuples

  • Updates statistics

But sometimes

  • It may not run immediately

  • It may lag on heavy-write tables

  • Misconfigured autovacuum is silent performance killer

  1. Run the manual vacuum command to reclaim the space

VACUUM FULL delete_demo;

If people are interested, I can do next parts on:

  • WAL (why writes behave weirdly)

  • Buffer cache (why same query is fast/slow)

  • Index internals (real reason indexes fail)

Thanks for reading! Always keep learning and keep sharing!


r/learnSQL • • Dec 17 '24 Bless Up Heart of Silver

Awesome SQL Resources for 2025

142 Upvotes

I don’t know about you, but I’ve wasted so much time trying to find SQL resources that are actually useful. You search for something simple, and suddenly you’re neck-deep in outdated tutorials, half-baked blog posts, or YouTube videos that take 10 minutes to get to the point.

So, I decided to do something about it. I spent some time collecting the good stuff—articles, cheat sheets, tools, and YouTube channels—and threw it all into one GitHub repo. It’s basically a "SQL survival kit" for 2025.

Here’s what I put in there:

  • 50+ solid articles that actually teach you something.

  • 20 cookbooks with practical SQL examples for when you need solutions, not theory.

  • Cheat sheets (because no one remembers everything).

  • Tools to work with SQL.

  • Best SQL Books

  • YouTube channels that I recommand and are not waste of time.

This list is for anyone working with SQL, whether you’re just starting or already knee-deep in data.

It’s all here: Awesome SQL Resources for 2025.

Let me know if this is helpful.