r/learnSQL • • Oct 05 '26

A client lost six weeks of SQL Server data. Having 12TB of backups didn’t save them.

136 Upvotes

Sharing a recovery case from our team because there are a few useful lessons for anyone learning SQL Server, or even more experienced teams too.

I am a sticker for backups and cannot emphasize the importance of them enough.

So our client moved a physical SQL Server to a new location and when they brought it back up, the database didn’t become available.

During attempts to get it working, they forced the database into emergency mode, bought third-party recovery tools, and accidentally overwrote the original MDF file (not good!), the primary database data file.

Unfortunately for them that removed an important recovery option.

When we got involved, they had around 12TB of backup files. But having lots of backup files and having a usable restore sequence are different things.

They had plenty of transaction log backups, but no usable recent full backup where they expected it to be.

Full backups had been stopped weeks earlier because of performance concerns. Meanwhile, a cleanup job kept deleting backups older than two weeks.

For anyone learning how this works: transaction log backups aren’t standalone copies of a database, you need a suitable full backup to restore first, followed by the required backups in sequence. A differential backup can shorten that process, but it also depends on a full backup.

An older full backup can still be useful if you have an unbroken log backup chain covering the period you need. The age of the full backup alone doesn’t determine how much data you lose.

In this case, an older full backup eventually turned up in files used to refresh a staging environment. It gave us a recovery point, but the available backups didn’t get us all the way forward. The client still lost roughly six weeks of production data.

One distinction worth making here is that SQL Server’s RESTORING and RECOVERING states aren’t interchangeable. A database in RESTORING may be waiting for another restore step. Waiting alone won’t necessarily bring it online and you need to establish its actual state and check the restore history and error log before deciding what to do.

The lessons I’d take from this:

  • Preserve the original database files before attempting destructive recovery steps.

  • Investigate why a database is unavailable before changing its state.

  • Check that retention jobs aren’t deleting backups you still depend on.

  • Test the complete restore sequence, rather than relying only on successful backup-job messages.

If you’re learning SQL Server backup and recovery, have you tried restoring a full backup followed by several log backups in a test environment? What part was hardest to understand?


r/learnSQL • • 26d ago

Struggling with SQL as a Beginner? Try This 4-Step Method

135 Upvotes

Anyone who is struggling to solve SQL questions at the beginner stage, try this method.

I call it the Input → Output → Grain → Bridge method.

When learning SQL, the hardest part isn't always remembering syntax. It's understanding how to approach a question and where to start.

Here’s a simple 4-step method that can help 👇

1. INPUT — What data do I have?

Identify the tables and columns available to solve the question.

2. OUTPUT — What should my answer look like?

Understand what the question expects you to return.

3. GRAIN — What does one row represent?

Is it one row per customer, department, day, or month?

This step is very important because it helps you understand the level of detail required in your result.

4. BRIDGE — How do I get from input to output?

Decide which SQL operations you need, such as JOIN, WHERE, GROUP BY, COUNT, or window functions.

Let's understand with a simple example 👇

Question: Find the total orders placed by each customer.

Suppose we have an orders table:

order_idcustomer_id
1011
1022
1031
1043
1051

Step 1 — INPUT

We have an orders table with order_id and customer_id.

Step 2 — OUTPUT

We need two columns: customer_id and total_orders.

customer_idtotal_orders
??

First, roughly draw what your final output table should look like.

Step 3 — GRAIN

One row should represent one customer, not one order.

Step 4 — BRIDGE

Now think about how to transform the input table into the expected output.

  • Group orders by customer_id.

  • Count the orders for each customer.

Only now, start writing SQL:

SELECT
    customer_id,
    COUNT(order_id) AS total_orders
FROM orders
GROUP BY customer_id;

Final output:

customer_idtotal_orders
13
21
31

One extra tip that helped me understand SQL better

Don't immediately start writing SQL syntax, especially when you're a beginner.

Instead, take a pen and paper or open Excel.

  1. Draw the input table roughly.

  2. Draw how you want the output table to look.

  3. Identify what one row in the output represents.

  4. Write down the steps needed to transform the input into the output.

  5. Think about the order of SQL operations required to get the result.

For example, you might need to filter rows first, join tables, group the data, calculate metrics, and sort the final result.

Remember, the logical order in which SQL processes a query is different from the order in which you write the SQL syntax.

In the beginning, this approach may feel difficult and time-consuming. You might feel that you're solving questions more slowly than before.

But if you practise consistently, it can help you understand the problem more clearly, reduce logical mistakes, and improve your ability to solve unfamiliar questions.

You can also use this approach in SQL interviews. Before writing the query, briefly explain your input, expected output, grain, and approach to the interviewer.

My takeaway: Don't just practise writing SQL queries. Practise translating a business question into a clear data transformation.

Hope this helps someone who's struggling with SQL at the beginning! 🚀


r/learnSQL • • Jul 21 '26

Free Live Data Analyst Learning Sessions (SQL, Excel, Power BI & Tableau)

135 Upvotes

Hi everyone! 👋

I'm planning to conduct free online live sessions for anyone interested in becoming a Data Analyst or improving their data skills.

We'll cover the essential tools used by data analysts, including:

SQL

Excel

Power BI

Tableau

The sessions are completely free and are intended for beginners or anyone who wants to strengthen their fundamentals through live learning and hands-on practice.

📍 Mode: Google Meet

💰 Fee: Free

If you're interested, comment below or send me a DM, and I'll share the details once the batch is finalized.

Looking forward to learning together! 😊


r/learnSQL • • Dec 28 '22

SQL Cheat Sheet

Post image
132 Upvotes

r/learnSQL • • Aug 05 '26

40,000 queries later: an update on the SQL detective game I shared here 7 weeks ago

129 Upvotes

About 7 weeks ago I posted in here about QueryCase, where you learn SQL by working detective cases instead of grinding tutorials. This subreddit is where it started. Most of the early users came from r/learnSQL and a lot of the feedback in the comments shaped what it became. So first, thanks everyone!

54 days in:

  • 1,064 people have signed up, across 87 countries

  • Over 40,000 queries written and run 🚀

  • 6,188 cases, drills, exams, investigations and interview questions solved

  • Top detective is on 9,635 XP, and 185 people are past 1,000 XP

The bit I did not see coming: an instructor emailed asking about using it with her students. She teaches a weekend CompTIA Data+ review session, bought a handful of seats out of her own pocket, and ran the first 90 minutes of the lab on QueryCase. Then she asked for two things: a way to see how her students were getting on, and a light mode, because a dark editor projected in a lit classroom is unreadable from the back row. Both exist now. Building something for one instructor turned out to improve it for everyone.

What has been built since launch, most of it straight from feedback:

  • A Career Hub: SQL interview questions modelled on real company loops, a rapid-fire quiz spanning SQL, statistics and A/B testing, and a guide to what each data role actually writes day to day

  • Investigations: open-ended timed whodunits where a live multi-table database is the crime scene, evidence unlocks as you query, and you get one accusation

  • A progress dashboard for instructors, so someone running a session can see how a group is doing

  • Light mode, for exactly the reason above

  • Regional pricing, after the data showed people in one country were engaging just as much as everyone else and converting ten times worse. The price had been the UK price with a currency conversion stapled on, which is not the same thing as a price that makes sense locally for everyone!

  • A LOT of bug fixes and improvements!!

What I would like from this post:

Half of this list exists because someone in a thread like this or DM said "it would be better if". So:

  • What is missing that would make it genuinely useful for the way you learn SQL?

  • Which SQL concept did you find hardest to actually get, as opposed to memorise? Those make the best cases and I am always hunting for the next one

  • If you tried it early, anything that felt off, confusing or too hand-holdy?

The goal is to keep building QueryCase into something genuinely useful whether you are breaking into data, switching careers, brushing up, or you just enjoy writing SQL for the fun of it. There is plenty still on the list: uploading your own CSVs into the sandbox so you can query your own data, more company interview questions, and a lot that will come from threads like this one.

It is free to start and you do not need an account to solve the first case, so you can poke at it before deciding whether it is nonsense.

querycase.com


r/learnSQL • • Dec 17 '25

How to Learn SQL From Zero and Become Job-Ready for Data Analytics

129 Upvotes

Hello All,
Just to give a quick background about myself I’m a B.Com graduate and I’m looking to pivot into data analytics. I want to start learning SQL from scratch and eventually become job-ready.

Could you please suggest good resources (courses, websites, practice platforms, or roadmaps) to learn SQL from zero? Any advice from people who’ve made a similar transition would be really helpful.


r/learnSQL • • Dec 23 '25

Learn SQL by playing a data detective — new SQL quest "The Bank Job"

128 Upvotes

Hey gang 👋

Ever since The SQL Murder Mystery came out, I’ve been wondering how to level up the format—make it more complex, with a deeper scenario, plot twists, and stronger educational value.

Without further ado, I’m happy to introduce the first SQL Habit Quest — “The Bank Job”.

You’ll play a detective chasing a bank thief, querying bank databases, Interpol records, city transportation data, CCTV camera feeds, and more — all modeled as closely to real life as possible.

The format is free and optionally competitive. There’s a leaderboard, but the main goal is to have fun and learn a few new things along the way.

Merry Christmas, and have fun mastering SQL! 💙


r/learnSQL • • Apr 10 '26

SQL cheat sheet

123 Upvotes

Hey guys,

I hope this doesn't come of as spammy, but here's an SQL cheat sheet that might help young devs that are in the learning phase: https://tms-outsource.com/cs/sql-cheat-sheet/

If there's something that's missing from there, let me know and I'll be happy to add it.

Also, any other feedback is appreciated.


r/learnSQL • • Nov 13 '25

Built a detective game to teach myself SQL — free, no login. Would love your thoughts.

123 Upvotes

I wanted to brush up on SQL but got bored with the usual tutorials, so I ended up building SQL Case Files — a noir-themed detective game where you solve crimes by writing real SQL queries.

It’s completely free, no sign-ups or subscriptions. Just open sqlcasefiles.com and start investigating.

It’s a Progressive Web App (PWA), so you can add it to your Home Screen and use it like a native app — it even works offline once loaded.

I built it mostly for myself to relearn SQL in a fun way, but I’d really appreciate honest feedback:

  • Does it actually feel engaging, or just a gimmick?

  • Are the hints / progression clear?

  • Anything frustrating or missing that would make it better for learners?

If you give it a spin, thank you. If not, all good — just wanted to share what I’ve been tinkering on.


r/learnSQL • • Sep 21 '26

Before your next SQL interview, keep this post handy - SQL Window Functions (Part 1)

122 Upvotes

P.S. My "If you have an SQL interview soon, don’t ignore these small things" series got a great response, so I’m starting a new one for upcoming interviews.

Simple, practical stuff that sticks in your head when you’re actually in the interview.

AI can help at work, but in an interview, your brain still has to do the job!!!

Imagine you and your friends are planning a trip. Everyone has spent some money, and you have a list of expenses.

Friend NameCityTrip DayTotal Expenses
HarryNew York1$200
JohnyNew York2$190
NicholosLas Vegas1$190
BaileyLas Vegas2$180
HarryLas Vegas3$190

Remember two things:

PARTITION BY - Look at each city separately.

ORDER BY - Within each city, decide the order based on the question - spend, day, etc.

Now every window function answers a very natural questions:

1. ROW_NUMBER():

Who spent the most, second most, third most, and so on?

ROW_NUMBER() OVER (PARTITION BY CITY ORDER BY spent DESC)

Look at each city separately, and give everyone a different number starting from 1.

Remember*: Everyone gets their own number.*

2. RANK():

Who are the top spenders? If two people spent the same, treat them equally.

RANK() OVER (PARTITION BY CITY ORDER BY spent DESC)

Notice Las Vegas:

Nicholas $190 → 1
Harry    $190 → 1
Bailey   $180 → 3

There is no rank 2.

Remember: Same spend = same rank, and the next rank is skipped.

3. DENSE_RANK():

Same idea as RANK(), but don't skip the next rank.

DENSE_RANK() OVER (PARTITION BY CITY ORDER BY spent DESC)

Notice Las Vegas:

Nicholas $190 → 1
Harry    $190 → 1
Bailey   $180 → 2

There is rank 2.

Remember: Same spend = same rank, but no gap after the tie.

4. LAG():

What did we spend the day before? Carry that number forward so we can compare.

LAG(spent, 1, 0) OVER (PARTITION BY city ORDER BY trip_day)

1 - how many rows back 
0 - what to show if no previous row exists

Las Vegas:

Day 1 → Nicholas $190 | Yesterday's spend: $0    (no previous day)
Day 2 → Bailey   $180 | Yesterday's spend: $190
Day 3 → Harry    $190 | Yesterday's spend: $180

Remember: LAG - Look Back

5. LEAD():

What will we spend the day after? Carry that number forward so we can plan ahead.

LEAD(spent,1,0) OVER (PARTITION BY city ORDER BY trip_day)

Remember: LEAD - Look Ahead

6. FIRST_VALUE():

How much did we spend on the first day? Show that number on every single row so we can always compare against it.

FIRST_VALUE(spent) OVER (PARTITION BY city ORDER BY trip_day)

Las Vegas:

Day 1 → $190 | First day = $190
Day 2 → $180 | First day = $190  ← same number follows you
Day 3 → $190 | First day = $190  ← same number follows you

Remember:  The first day's amount travels with you through the rest of the trip.

7. LAST_VALUE():

How much did we spend on the last day? Show that number on every row.

LAST_VALUE(spent) OVER (
    PARTITION BY city
    ORDER BY trip_day
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
)

Las Vegas:

Day 1 → $190 | Last day = $190  ← already knows the end
Day 2 → $180 | Last day = $190
Day 3 → $190 | Last day = $190

Remember: The last day's amount travels with you through the whole trip

8. NTILE():

Can we split everyone into 3 spending groups - high, medium, and low?

NTILE(3) OVER (PARTITION BY city ORDER BY spent DESC)

Las Vegas:

Nicholas  $190 → Group 1  (high)
Harry     $190 → Group 2  (medium)
Bailey    $180 → Group 3  (low)

Remember: Split the list into N equal groups

9. NTH_VALUE():

What was our spending on the 2nd day of the trip?

NTH_VALUE(spent, 2) OVER (
    PARTITION BY city
    ORDER BY trip_day
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
)

Remember: Pick the value at any specific position in the window.

10. PERCENT_RANK():

If 0 means the lowest spender and 1 means the highest, where do you sit?

PERCENT_RANK() OVER (PARTITION BY city ORDER BY spent)

Las Vegas:

Bailey    $180 → 0.0   (lowest — always starts at 0)
Nicholas  $190 → 0.5
Harry     $190 → 0.5   (tied with Nicholas, same score)

Remember: Your position in the group, scaled from 0 to 1. First is always 0.

11. Aggregation Window Functions - SUM(), AVG(), MIN(), MAX()

Want to know how our spending is going as the trip goes on?

SUM(spent) OVER (PARTITION BY city ORDER BY trip_day)
AVG(spent) OVER (PARTITION BY city ORDER BY trip_day)
MIN(spent) OVER (PARTITION BY city ORDER BY trip_day)
MAX(spent) OVER (PARTITION BY city ORDER BY trip_day)

Las Vegas running total (SUM with ORDER BY):

Day 1 → $190 | Total so far: $190
Day 2 → $180 | Total so far: $370
Day 3 → $190 | Total so far: $560

Sum without ORDER BY - shows the full trip total on every row:

Day 1 → $190 | Total: $560
Day 2 → $180 | Total: $560
Day 3 → $190 | Total: $560

Remember: See how our spending changes throughout the trip.

With ORDER BY → running total (keeps adding as the trip goes on)
Without ORDER BY → total for the whole city shown on every row

If you want more posts like this, let me know in the comments and I’ll keep the series going!


r/learnSQL • • Sep 16 '25

“Ever hear of SQL ‘Gaps & Islands’? They sound weird, but they show up in interviews a lot 👀”

122 Upvotes

I just put together a new learning page on my practice site all about Gap & Island problems in SQL.

These are the classic streak-and-break questions such as:

  • 🕒 Find the longest gap between two orders

  • 📈 Spot a customer’s longest streak of consecutive months

  • 📦 Measure supplier reliability over consecutive days

They’re tricky because they force you to go beyond simple aggregates and use window functions like ROW_NUMBER, LAG, and LEAD in creative ways.

My guide walks through both a Gap example and an Island example step-by-step, with code, sample data, and practice problems you can try right away.

👉 https://www.practicewindowfunctions.com/learn/gap_and_island

Would love feedback from folks here — do the walkthroughs make sense, and are there other gap/island patterns you’ve run into in interviews or real projects? Are there any errors or typos? For people who try the practice problems, are they thorough enough?

Thanks!


r/learnSQL • • Aug 29 '23

FREE Sql Course for beginners & newbies

121 Upvotes

You ever get the urge to dive into something new during those endless coffee breaks? That's basically how I started with SQL. And guess what? I went ahead and made a course for fun. The starter part's on me, as in, free. No biggie. Check it out if you fancy, and if it strikes a chord, let others know. Happy learning (or just browsing)!

Here is the link: https://grzegorzpiechnik.gumroad.com/l/nnccol


r/learnSQL • • Dec 22 '24

Free SQL data analysis course - highly rated Udemy course.

120 Upvotes

https://www.udemy.com/course/hands-on-sql-for-data-analysts/?couponCode=XMAS2024

Please spread as I want as many people to learn SQL as possible.

If you miss out you can get the discounted version through this link

https://www.udemy.com/course/hands-on-sql-for-data-analysts/?referralCode=4611DF7B820A696D7DE0

....and please subscribe to the Youtube channel advertised at the end of the course where I shall be giving tips and advice once we get enough people showing interest. Thanks


r/learnSQL • • Sep 08 '26

Hello! Anyone want to learn SQL together? I can make a groupchat!

117 Upvotes

Here is the discord link: https://discord.gg/ugEyQQXe4


r/learnSQL • • May 31 '26

SQL EXAGGERATION IN RESUME

114 Upvotes

Hi all,

I have been jobless for 2 years. I am financially struggling. So I exaggerated in my resume as everyone suggests, that you will atleast get shortlisted for the interviews. Everyone does that. Start learning after you get the interview. And so I DID exatly that. I mentioned that I know SQL, PYTHON and worked as a Data Analyst in my previous organisations with US Healthcare Datasets. So, now after 5 months... I have finally landed an interview. But i do not know how learn. I know SQL, Python and Advanced Excel. i did a small course.... but I do not know how to apply it to Healthcare dataset for patients. Like claims and insurance datesets of US Healthcare.

Anyone who has any idea, what YT videos or what software should i use to learn, please guide me. I used ChatGPT but it is confusing me. It leaves many things unanswered. And i believe it is not enough. Although I know SQL, Python and Advanced Excel. I just do not know how to implement it into a professional environment and how to justify my experience that i really did this work.


r/learnSQL • • Sep 30 '26

Before your next SQL interview, keep this post handy - WHERE, GROUP BY and HAVING (Part 3)

113 Upvotes

P.S. Parts 1 and Part 2 got a great response - thank you! Keeping this series going.

Simple, practical stuff that sticks in your head when you're actually in the interview.

AI can help at work, but in an interview, your brain still has to do the job!!!

Same trip. Same friends. Same expenses.

FriendCityTrip DayTotal Spent
HarryNew York1$200
JohnyNew York2$190
NicholasLas Vegas1$190
BaileyLas Vegas2$180
HarryLas Vegas3$190

Three things. Most people know all three.

But in an interview - knowing which one does what is what gets you the job.

1. WHERE

We have 5 rows. We don't want all of them.

"Show me only the days where someone spent more than $180."

SELECT name, city, spent
FROM expenses
WHERE spent > 180

Harry    | New York  | $200
Johny    | New York  | $190
Nicholas | Las Vegas | $190
Harry    | Las Vegas | $190

Bailey is gone. $180 is not more than $180.

Remember*: WHERE picks which rows to keep. Runs first. Looks at rows one by one.*

2. GROUP BY

Now we want one total for each city.

"Put all New York rows together. Put all Las Vegas rows together. Add them up."

SELECT city, SUM(spent) AS total
FROM expenses
GROUP BY city

New York  → $390
Las Vegas → $560

5 rows became 2. One number per city.

Remember*: GROUP BY puts rows into groups and adds them up.*

3. HAVING

Now we have city totals. We only want cities that spent more than $400.

"Remove any city where the total is $400 or less."

SELECT city, SUM(spent) AS total
FROM expenses
GROUP BY city
HAVING SUM(spent) > 400

Las Vegas → $560

New York spent $390. Less than $400. Gone.

Remember*: HAVING picks which groups to keep. Runs after GROUP BY.*

The #1 mistake in every SQL interview:

People try this:

-- Wrong
SELECT city, SUM(spent)
FROM expenses
WHERE SUM(spent) > 400
GROUP BY city

SQL gives an error.

Why?

WHERE runs first. At that point, SQL has not added anything up yet. There are no city totals. WHERE has no idea what SUM(spent) is.

You are asking for the answer before the math is done.

-- Right
SELECT city, SUM(spent)
FROM expenses
GROUP BY city
HAVING SUM(spent) > 400

HAVING runs after GROUP BY. The totals exist by then. It works.

Remember*: WHERE sees rows. HAVING sees totals. They are not the same.*

The order SQL always runs in:

FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY
  • WHERE runs before groups exist → can only see rows

  • HAVING runs after groups exist → can see totals

  • SELECT runs at the end → that's why you can't use a column alias in WHERE

Reading is one thing. Writing it yourself is another. If you're new and want real hands-on practice - SQL from Zero to Confident on TheQueryLab.


r/learnSQL • • Jun 16 '26

How did you learn SQL when you were a beginner?

111 Upvotes

As I'm completely new to SQL, I tried using ChatGPT to get some guidance, but I think it's better to hear directly from people who have gone through this phase.

Where should I start to improve my SQL skills? I have around 15–20 days that I can dedicate to learning and practicing, but I have no idea where to begin.

Also, how important is SQL for becoming a Data Analyst? Does being good at SQL make a significant difference in the role?


r/learnSQL • • Oct 06 '26

Before your next SQL interview, keep this post handy - CTEs vs Subqueries (Part 4)

110 Upvotes

Simple, practical stuff that sticks in your head when you're actually in the interview.

AI can help at work, but in an interview, your brain still has to do the job!!!

Same trip. Same friends. Same expenses.

FriendCityTrip DayTotal Spent
HarryNew York1$200
JohnyNew York2$190
NicholasLas Vegas1$190
BaileyLas Vegas2$180
HarryLas Vegas3$190

Your friend asks:

"Who spent more than the average?"

First, we need the average:

SELECT AVG(spent)
FROM expenses

Average = $190

Now we need to find who spent more than $190.

Harry spent $200. Everyone else spent $190 or $180.

So the answer is: Harry.

Easy enough. But how do we write that in SQL?

That's where subqueries and CTEs come in.

1. SUBQUERY:

We can put the average calculation inside another query.

Think of it as: First figure out the average. Then use that answer.

SELECT name, spent
FROM expenses
WHERE spent > (
    SELECT AVG(spent)
    FROM expenses
);

Remember: Subquery = query inside another query.**

2. CTE:

Now imagine the interviewer says:

"Don't put that calculation inside the WHERE. Make it easier to read."

This is where a CTE helps.

WITH average_spent AS (
    SELECT AVG(spent) AS avg_spent
    FROM expenses
)
SELECT name, spent
FROM expenses
WHERE spent > (
    SELECT avg_spent
    FROM average_spent
);

Remember: CTE = Let me calculate this first and give the result a name. I'll use it afterward.

So what's the point of a CTE?

Readability!!!!

  • When the calculation gets bigger, putting everything inside everything else becomes difficult to read.

The interviewer changes the question:

  1. Who spent more than the average AND show me how much more they spent?

Now we need the average and the difference. A CTE lets you break the problem into steps.

The CTE makes the calculation feel like a separate step:

Step 1 → Calculate average

Step 2 → Compare every expense to average

Step 3 → Show how much higher it is

That's why CTEs can make complicated SQL much easier to follow

Reading SQL is one thing. Writing it yourself under pressure is another.

Before the real interview, try a MOCK SQL INTERVIEW on TheQueryLab. It’s a good way to test yourself under interview pressure and see where you actually stand with interview scorecard.


r/learnSQL • • Mar 15 '26

DELETEs that have wiped entire production tables. Please learn from other people's pain.

110 Upvotes

These are real patterns that have caused real data loss. Some of these have ended careers. Read slowly!!!

☠️ 1. DELETE with a subquery that returns more than you expected

DELETE FROM employees WHERE department_id IN ( SELECT id FROM departments WHERE location = 'NYC' );

Looks precise. But what if someone inserted a NULL into the departments table last week? What if the location column has 'NYC ' with a trailing space somewhere? Your subquery silently returns more IDs than you expect and you've just deleted employees you never intended to touch. Before any DELETE with a subquery:

SELECT * FROM employees WHERE department_id IN ( SELECT id FROM departments WHERE location = 'NYC' ); -- Read every row. Then delete.

☠️ 2. The DELETE that looked safe… but the filter was wrong

DELETE FROM sessions WHERE created_at < '2023-01-01';

Looks precise. But the column was actually stored in UTC, while the engineer assumed local time. The query deleted active sessions that were still valid. A small misunderstanding of timestamps can wipe out the wrong data.

☠️ 3. DELETE with a JOIN that deletes more than expected

DELETE o FROM orders o JOIN order_items i ON o.id = i.order_id WHERE i.product_id = 42;

Seems logical. But if an order contains multiple matching items, the join expands the rows. Depending on the engine and query plan, this can behave differently than expected and delete far more rows than intended. JOINs inside DELETE statements deserve extra caution.

☠️ 4. DELETE without a transaction

DELETE FROM order_items WHERE order_id IN (...); DELETE FROM orders WHERE id IN (...); DELETE FROM customers WHERE id IN (...);

Step two fails. Now the database is left in a half-deleted state. Orphaned records everywhere.

The safe pattern:

BEGIN;

DELETE FROM order_items WHERE order_id IN (...); DELETE FROM orders WHERE id IN (...); DELETE FROM customers WHERE id IN (...);

COMMIT;

If anything looks wrong:

ROLLBACK;

The simple habits that prevent most DELETE disasters

  • Always run a SELECT with the same WHERE clause first

  • Check the row count

  • Understand foreign key cascades

  • Use transactions for multi-step deletes

  • Batch large deletes instead of running them all at once

DELETE statements are small. Their impact usually isn’t.

Curious to hear from others. What’s the worst DELETE mistake you’ve seen in production?


r/learnSQL • • Sep 03 '23

Cheeky data shirt I made the other day. Have now explained joins to so many people.

Post image
110 Upvotes

I have been stopped more than 10 times to explain. Teaching SQL can be fun.


r/learnSQL • • May 20 '26

Platforms to practice SQL

108 Upvotes

I have completed my graduation and have been practicing SQL from a while including stored procedures , triggers.

I want to know what are some certifications that i have to do it or any good platforms to practice/solve and get certifications

or should I do some projects (pls tell me if u know what type of projects )

Thank you


r/learnSQL • • Apr 15 '25

A review of 20+ SQL problem sites

108 Upvotes

I've spent the last few months working on (the hardest free) SQL problems from various sites, and wanted to share which sites I found the best

The TLDR is that the sites I'd recommend are:

I also loved:

These are all free or freemium resources, and I think they cover enough between them to get you using SQL patterns that you would need "on the job"

These resources mainly focus on crafting SELECT statements, but ones like Interview Query and the AdvancedSQLPuzzles quiz include some questions around DDL, database design, and performance (indexes etc)

I'm also working on a totally free site with difficult questions over a whole range of topics based on real-life problems I've had to solve during my career:


A full review and breakdown of all the sites I tried are on my GitHub repo where I saved my solutions, but the full post gets blocked by the Reddit filters -- the links for the full post and breakdown are:


r/learnSQL • • Jul 14 '26

How I Lost Confidence in SQL After 6 Years as a Data Engineer (and How I Got It Back)

107 Upvotes

I wanted to share something that I think many experienced Data Engineers can relate to.

A few weeks ago, I faced a SQL interview and struggled with questions that I would have solved easily 5–6 years ago. It was frustrating because I started doubting myself.

Then I realized something.

Over the last several years, my work shifted from writing complex SQL every day to building end-to-end data engineering solutions using tools like Snowflake, AWS, Azure, dbt, Jenkins, Python, orchestration tools, and cloud platforms. SQL was still part of the job, but not something I was practicing deeply on a daily basis.

Because of that, my interview confidence dropped—not because I didn't understand data engineering, but because I hadn't brushed up on the fundamentals.

Instead of feeling defeated, I decided to go back to basics.

I started practicing SQL again from scratch—joins, CTEs, window functions, ranking functions, and gradually rebuilding my confidence.

One thing that genuinely helped me was using ChatGPT as a practice partner instead of just asking for answers. I solved queries first, made mistakes, got feedback, and understood why my approach was right or wrong. It felt more like having a patient mentor than just a search engine.

Today I can already feel my confidence returning.

If you're an experienced Data Engineer and you've ever felt embarrassed by a "simple" SQL question in an interview, you're not alone. Skills that aren't practiced regularly become rusty. That doesn't mean you've become less capable—it just means they need sharpening again.

Sometimes the strongest move isn't learning something new. It's rebuilding the fundamentals.

And yes... thank you, ChatGPT. You helped me get my confidence back.


r/learnSQL • • Jun 12 '26 Heartwarming

I've been building a SQL learning platform for the past few months. It's called QueryCase and I'd love honest feedback

105 Upvotes

I've spent the last few months building something and I'm finally at the point where I want to share it properly rather than just quietly hoping people find it.

The idea came from a frustration I kept seeing (and feeling myself): SQL tutorials teach the syntax fine but there's never a reason to care about the answer. You filter a table called employees, get a result, and nothing happens. Your brain doesn't bother keeping it.

I wanted to try a different approach. QueryCase teaches SQL through detective investigations. You get a briefing from Chief Fox (our mascot), a real database to query, and a mystery to crack. The JOIN matters when a suspect has an alibi. The WHERE clause matters when you're trying to find who entered the building at 22:13. The SQL is the tool for solving something, not the point in itself.

Here's what's actually in it:

  • A structured learning path across 54 cases, going from Recruit through Rookie, Detective, Senior Detective, and Chief Detective. Each rank has drills and a level exam to pass before you progress.

  • Sandbox mode where you can explore real datasets (IMDB movies, Spotify, sports stats, Steam games) and run whatever you want with no pressure and no mystery attached. Just free exploration against actual data.

  • Everything runs in the browser using DuckDB WASM so there's nothing to install.

I'm a solo developer and this is genuinely early days. I'm sharing here because this community is exactly the kind of people I built it for, and I'd rather get honest feedback now than find out later I've built the wrong thing.

What's missing? What would make you actually stick with something like this versus what you've used before?

querycase.com if you want to take a look.

Any feedback appreciated!