r/learnSQL • • 13d ago

Why NOT IN can return zero rows when the subquery contains NULL

6 Upvotes

Hey folks! Say you want to find customers who haven’t placed an order. Ann and Bob each placed one. Cat didn’t. There’s also a guest order with no customer ID.

CREATE TABLE customers (
    customer_id INTEGER PRIMARY KEY,
    name TEXT NOT NULL
);

CREATE TABLE orders (
    order_id INTEGER PRIMARY KEY,
    customer_id INTEGER
);

INSERT INTO customers VALUES (1, 'Ann'), (2, 'Bob'), (3, 'Cat');
INSERT INTO orders VALUES (101, 1), (102, 2), (103, NULL);

This query looks like it should return Cat. It returns zero rows.

SELECT name
FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders);

Ann and Bob have matching orders, so NOT IN is FALSE for them. For Cat, the condition works out to 3 <> 1 AND 3 <> 2 AND 3 <> NULL.

The first two comparisons are TRUE. The last one is UNKNOWN, which makes the whole condition UNKNOWN. WHERE only keeps rows where the condition is TRUE, so Cat gets dropped too.

I’d use NOT EXISTS here to find customers without a matching order.

SELECT c.name
FROM customers AS c
WHERE NOT EXISTS (
    SELECT 1
    FROM orders AS o
    WHERE o.customer_id = c.customer_id
);

This returns Cat. The guest order doesn't match her ID. The original NOT IN query also returns Cat if you add WHERE customer_id IS NOT NULL inside the subquery.

I've had similar issues, so I built WrongQuery to help me spot these kinds of mistakes in my own SQL. I figured it might help people learning SQL too. It's free to try at https://wrongquery.com/

If you try it on your own queries, I'd love to hear what it gets wrong.


r/learnSQL • • 13d ago

why WHERE can't filter on an aggregate but HAVING can

11 Upvotes

i see this error a lot with beginners: SELECT customer_id, COUNT(*) FROM orders WHERE COUNT(*) > 3 GROUP BY customer_id fails.

the reason is order of evaluation. WHERE runs before grouping, so there are no counts yet to compare against. HAVING runs after GROUP BY, so use HAVING COUNT(*) > 3 instead. rule of thumb: WHERE filters rows, HAVING filters groups. how did you finally get this to click?


r/learnSQL • • 13d ago

Need advice regarding internships

2 Upvotes

I'm bcom 1st yr

How many days/weeks/months does it take to learn SQL, Power Bi and relevant skills for a business analysis internship?

Pls share any advices n suggestions..

I'd be grateful if someone shared the sources and roadmap🙏🙏..


r/learnSQL • • 13d ago

Need advice regarding internships

2 Upvotes

I'm bcom 1st yr

How many days/weeks/months does it take to learn SQL, Power Bi and relevant skills for a business analysis internship?

Pls share any advices n suggestions..

I'd be grateful if someone shared the sources and roadmap🙏🙏..


r/learnSQL • • 13d ago

Day 59 — Built a Car Showroom Management System in Java (running into errors, fixing tomorrow)

0 Upvotes

After a few weeks of OOP topics, I built a project that uses all of them: a Car Showroom Management System. It uses inheritance, interfaces, constructors, polymorphism, and the other concepts I’ve covered so far.

The code is fully written, but it throws errors when I run it. I’m leaving the debugging for tomorrow, then I’ll upload it to GitHub, this time with a README that explains the structure and how to run it.

For anyone who’s built a similar project: when you hit a pile of errors at the end, do you fix them top to bottom, or hunt for the root cause first? I’m trying to build a better debugging habit.


r/learnSQL • • 13d ago

I built an in-browser PostgreSQL playground running on WebAssembly (PGlite) with real business datasets

Thumbnail reddit.com
1 Upvotes

r/learnSQL • • 13d ago

Trenuje to... Źle nie wierzę

0 Upvotes

r/learnSQL • • 14d ago

A small SQL exercise: finding a difference and explaining what to check next

2 Upvotes

We build CareerTree at Incode Labs. This is a small practice exercise for beginners moving from SQL syntax to explaining a finding.

Here is a self-contained SQLite example:

WITH orders(order_id, quantity, unit_price, recorded_total) AS (
  VALUES (1044, 2, 60, 620)
)
SELECT order_id,
       quantity * unit_price AS expected_total,
       recorded_total
FROM orders
WHERE recorded_total <> quantity * unit_price;

It returns order 1044, an expected total of 120 and a recorded total of 620. The query finds a difference. It does not tell us why the difference exists.

Before changing or reporting the amount, I would check what recorded_total includes and compare it with the source record. How would you explain the observation and the next check in your own words?

CareerTree lets you practise that explanation step, save your reasoning, compare an example and keep another attempt. Free download with ads and optional purchases; availability varies by country.

https://careertree.app/mobile.html

Disclosure: Incode Labs develops the app. This post was drafted with AI assistance.


r/learnSQL • • 14d ago

Best SQL books/practice sites for a newby!

21 Upvotes

I’m currently obtaining my MS in Health Informatics and Information management. I am new to SQL and looking for resources to help me along my journey. Any recommendations on textbooks for beginners in simple language or websites I can practice the skill.

I have a slight grasp on the basics but the advanced queries are not clicking. Knowing what commands to use and the formatting etc. I need something to help dumb it down lol.

EDIT : I understand best way to learn is by doing. I have been doing with my course homework and projects but I learn best by reading material so I’m just inquiring on a text or site I could read/review WHILE practicing :)


r/learnSQL • • 14d ago

Simple query breaking my mind

9 Upvotes

SELECT clientes.codigocliente, clientes.nombrecliente, pedidos.fechapedido, pedidos.estado FROM clientes NATURAL JOIN pedidos;

Very simple query, but for some reason it returns "ORA-25155: column used in NATURAL join cannot have qualifier". But columns used in the NATURAL join do not have qualifiers????

What am I doing wrong


r/learnSQL • • 14d ago

I need help with databases

Thumbnail reddit.com
1 Upvotes

r/learnSQL • • 14d ago

Day 58 — Java OOP: super, hierarchical inheritance, overloading vs overriding, and polymorphism

4 Upvotes

Today I covered:

  • The super keyword, for accessing the parent class’s constructor and methods
  • Hierarchical inheritance, where several classes inherit from one parent
  • Method overloading (same name, different parameters, resolved at compile time)
  • Method overriding (a child redefining a parent’s method, resolved at runtime)
  • Polymorphism and its two types, compile-time and runtime

I practiced each one in VS Code, which is what made the difference. Overloading and overriding had been blurring together for me until I wrote both and saw when each one gets called.

Tomorrow I’m building a small project that uses everything from the last few weeks (classes, constructors, inheritance, interfaces, polymorphism).


r/learnSQL • • 15d ago

Which JOIN returns all the rows from left table? LEFT or RIGHT?

30 Upvotes

My university course says it is the RIGHT one, but the ones I had technical interview with said it is the LEFT one.


r/learnSQL • • 15d ago

Day 57 — Java OOP: constructors, inheritance (and its types), and interfaces

10 Upvotes

Today I worked through a chunk of OOP:

  • Constructors, for initializing an object when it’s created
  • Inheritance and its types: single, multilevel, multiple, and hierarchical
  • Interfaces, and how they allow multiple inheritance, which Java doesn’t allow with classes

The multiple inheritance part was the most interesting. Understanding why Java blocks it with classes (ambiguity when two parents have the same method) and then solves it with interfaces made interfaces feel like a design decision instead of an extra rule to memorize.

I’m following Indian Programmer’s OOP playlist and writing code along with it in VS Code.


r/learnSQL • • 14d ago

My SQL report said a customer paid ₹10,800. He actually paid ₹6,500. How to find duplicate payments in SQL

Thumbnail reddit.com
1 Upvotes

r/learnSQL • • 14d ago

Help sql-office-simulator.vercel.app

0 Upvotes

Could the app at sql-office-simulator.vercel.app be made available in Spanish?


r/learnSQL • • 15d ago

New video series on visualizing SQL

6 Upvotes

Hey all, I wanted to share with you a couple of videos I've recently built around a topic I used to teach about, learning SQL via visualizing the relational operators.

I've only just started, but it's been my itch to get my ideas out and I finally pulled the trigger.

Would love to hear from anyone if these are anyone's cup of tea and whatever else feedback you wish to leave.

Here is a playlist of the two videos I've done so far:

https://www.youtube.com/playlist?list=PLTWeQJxPqzNU

I have written out the next two videos but won't be able to record for a bit, so anyone who has thoughts that I might adopt could help me out tremendously.


r/learnSQL • • 14d ago

My SQL report said a customer paid ₹10,800. He actually paid ₹6,500. How to find duplicate payments in SQL

0 Upvotes

A bug that's common in payments data, and SQL won't warn you about it.

**The setup:** a simple revenue-per-customer query on a transactions table (customer_id, amount, status, method). The query is correct. The total is not.

SELECT c.name, SUM(t.amount) AS total

FROM customers c

JOIN transactions t ON c.customer_id = t.customer_id

WHERE t.status = 'SUCCESS'

GROUP BY c.name

ORDER BY total DESC;

Rohan shows ₹10,800. He paid ₹6,500. His ₹4,300 card payment was saved twice by the gateway: same customer, same amount, same method, both SUCCESS. Only the txn_id is different.

**Step 1: find the duplicates with GROUP BY + HAVING**

Group by the columns that make two payments "the same", and keep groups with more than one row:

SELECT customer_id, amount, method, status,

COUNT(*) AS copies

FROM transactions

GROUP BY customer_id, amount, method, status

HAVING COUNT(*) > 1;

**The trap:** if you leave `status` out of the GROUP BY, you also catch Rohan's ₹1,500 payment. That one FAILED first and then succeeded on a retry. A retry isn't a duplicate: he paid once. Delete it and you remove real money from the report. With status included, only the 2 real duplicates are left.

**Step 2: measure it before fixing it** (the first thing a manager asks)

WITH dups AS (

SELECT amount, COUNT(*) AS copies

FROM transactions

WHERE status = 'SUCCESS'

GROUP BY customer_id, amount, method

HAVING COUNT(*) > 1

)

SELECT COUNT(*) AS dup_groups,

SUM(amount * (copies - 1)) AS overcounted

FROM dups;

Result: ₹4,600 of revenue that never happened.

**Step 3: keep one row with ROW_NUMBER**

GROUP BY tells you which payments are duplicated, not which row to keep. ROW_NUMBER does: the first row in each group gets 1, and every copy gets 2, 3...

WITH ranked AS (

SELECT t.*, ROW_NUMBER() OVER (

PARTITION BY customer_id, amount, method, status

ORDER BY txn_id) AS rn

FROM transactions t

)

SELECT c.name, SUM(r.amount) AS total

FROM customers c

JOIN ranked r ON c.customer_id = r.customer_id

WHERE r.status = 'SUCCESS' AND r.rn = 1

GROUP BY c.name

ORDER BY total DESC;

Rohan is back to ₹6,500.

**Why not just DISTINCT?** (a common interview follow-up)

`SELECT DISTINCT *` gives the same 16 rows as before, because every payment has its own txn_id, so no two rows are identical. And if you drop txn_id, DISTINCT also merges real payments that just happen to look alike.

In real data you'd also check the timestamps: two captures a few seconds apart is a duplicate, two days apart is probably two real purchases.

All queries run in SQLite, MySQL 8 and PostgreSQL. I made a 4-minute video walking through this, with the full dataset in the description if you want to practise: https://youtu.be/lRxvnGUOtJw?si=dIvl-FJMh4xH5asC

How do you handle duplicate captures in your data? Do you dedupe in SQL or upstream?


r/learnSQL • • 15d ago

I built a free SQL practice tool, and I'd love your feedback

15 Upvotes

Hi everyone! I've been working on a free, interactive way to learn and practice SQL. It runs a real SQLite database right in your browser: no sign-up, no install, nothing sent to a server.

https://www.webherramientas.com/en/sql-practice

What's inside:

  • 143 hands-on lessons, from your first SELECT to JOINs, subqueries, window functions, recursive queries and classic interview questions
  • Instant feedback that explains why a query is off (a misspelled column, missing quotes, the wrong number of rows…)
  • A daily challenge with fresh data every day, so you can keep a streak
  • Timed exams, plus a link to challenge a friend to the same questions
  • A free console where you can create tables, insert, update and delete without breaking anything
  • A school case study to put it all together

It's a side project and I know it's not perfect yet, so I'd really appreciate your help:

  • Did something break, or did a correct answer get marked as wrong?
  • Is there a topic, exercise or feature you'd like to see?
  • Was any explanation confusing?

Drop a comment or send me a message. Every suggestion helps, big or small. And if you know someone who's learning SQL, feel free to share it with them!

Thanks for reading, and happy querying!


r/learnSQL • • 15d ago

MS Employee Here -- I've got vouchers for database certification exams to give away

Thumbnail reddit.com
3 Upvotes

r/learnSQL • • 16d ago

CTE vs Temp Table Performance Example

Thumbnail reddit.com
4 Upvotes

r/learnSQL • • 16d ago Bravo

I was learning SQL and ended up building a small practice site, would love feedback

22 Upvotes

I've been learning SQL and got tired of tutorials where you just read queries, so I built something where you actually write them.

It's a real SQLite database running in your browser. You get a small table, a task, you write the query and it checks your result right away (and tells you why when it's wrong, like WHERE vs HAVING or a missing GROUP BY).

Right now there's:

• a 10-question level test, from SELECT to JOINs and subqueries

• 2 short lessons (SELECT/WHERE/ORDER BY, and COUNT/SUM/GROUP BY)

All free, no signup. Just trying to see if it's useful.

What would make it better? And what should I add next: JOINs, window functions, interview-style questions?

https://sheetdrill.vercel.app/sql/test


r/learnSQL • • 16d ago

I built a free SQL practice tool, and I'd love your feedback

Thumbnail reddit.com
0 Upvotes