r/SQL • • Sep 28 '26

Discussion What is the hardest SQL bug to detect when the query never throws an error?

Some SQL bugs don't cause any error. The query runs successfully and the result even looks correct.

For example, an incorrect JOIN, unexpected duplicates, NULL handling, or a wrong date filter can silently produce incorrect results.

What is the most difficult SQL bug you've encountered where the query ran successfully but the data was wrong?

24 Upvotes

66 comments sorted by

69

u/Standgeblasen Sep 28 '26

For me, it’s usually an edge case scenario where 99% of the data is correct. Especially if you are aggregating multiple levels of granularity.

Added difficulty if you have little to no visibility into the business rules and are playing telephone with a PM to get answers to business logic questions.

3

u/nachos_nachas Sep 28 '26

Expecting PMs to know business logic is ... interesting. I've only known that to be the case for PMs who came from a different role.

2

u/bulltin Sep 29 '26

Well the PM’s job theoretically is to know the person that does know the business rule.

3

u/Stormraughtz Sep 29 '26

That telephone shit drives me nuts, just get me on a call

2

u/Standgeblasen Sep 29 '26

Amen. Connect me directly with the person who can answer my questions and actually understands what I’m asking!

19

u/Eleventhousand Sep 28 '26

Maybe a query that has some non-deterministic code within, and causes the results to look logically wrong some of the time, but not all the time. For example, a QUALIFY buried in the middle, since forgotten, flipping back and forth due to duplicates in the LAST_MODIFIED for each candidate key.

6

u/Paratwa Sep 28 '26

Yeah that was gonna be my answer. Or even worse a qualify on a field that looks like it’d be right and you’re debugging someone else’s code and the only way to find it is to pull up every damn table one by one

18

u/YourRoaring20s Sep 28 '26

If you're not actively thinking about null handling that can really cause some funky things to happen

3

u/Capable_Stranger9885 Sep 28 '26

Somebody some time Set ANSI Nulls Off and now you're living in their world

2

u/did-a-chuck Sep 28 '26

It's always the NULLs

12

u/Wuthering_depths Sep 28 '26

NULLs can cause weird results when used in a join or where comparison. They need to be handled and accounted for.

I've seen people that don't know the data that well join on IDs that appear to be the same but really aren't...those are really tricky. E.g. a "customerNum" field in two tables but it really isn't the same thing (it's a vendor db, we didn't design it). Some values match, some don't, if none did then it would be a better clue that something was wrong! This isn't really a SQL issue, it's a "I'm in a hurry to finish this and don't know this data" issue :)

11

u/promatrachh Sep 28 '26

Select a, b, c d, e from tab

2

u/gumnos Sep 28 '26

ooh, that's subtle and I've certainly done that more than once

2

u/dpenton Sep 28 '26

Aliases on the columns would have caught that

2

u/MrLuc Sep 28 '26

It's the reason why I always use alias :
select a AS a, b AS b,....

8

u/aardw0lf11 Sep 28 '26

Isolated duplicative rows when you don’t want them. I had a habit of using select distinct but over-relying on that can be an issue. Know your data.

2

u/i_literally_died Sep 28 '26

I have to OUTER APPLY TOP(1) or ROW_NUMBER join so much shit because our system allows duplicate barcodes, country of origin, pricing. It turns relatively simple queries into triple digit monsters just because the joins are all now some kind of derived table.

2

u/president_bear40 Sep 28 '26

Mistyped column name in EXISTS sub-query. Problem was that column with mistyped name existed in some of tables used in from and joins.
I'm always assigning aliases to sub-query tables since then.

2

u/ngless13 Sep 28 '26

Probably not what you meant, but I'd say race conditions that rarely surface.

2

u/dudeman618 Sep 28 '26

Bad data. I wrote a huge query and got everything down to a single row of data across many tables. I find a stray duplicate row, after researching finding it is from bad data in a table. For example, expending a single row to be returned on a transactional row but for some reason it is returning two rows... Like first contact with a client should always be a single event but there are very rarely two transactions.

2

u/StickPuppet Sep 28 '26

I've gotten to the point now where if its determined my output is wrong, I go look for bad data first instead of bad code 🤣

3

u/cwjinc Sep 28 '26

I consider implicit type conversions a bug. And they can go undetected for years.
For example a join on a number column and a string column might work as long as the number is converted to a string by the optimizer and then fail when an optimizer update starts evaluating it the other way around and start trying to convert a string column that contains non numeric values to numbers.

1

u/Ok_Werewolf2211 Sep 28 '26

Similar bug or unexpected behaviour that occurs in Pandas merge/join but the latter is easier to detect through an error.

3

u/Odd_Negotiation2627 Sep 28 '26

For me the worst thing is when someone or a bot post AI slop like OP's prompt

1

u/Equivalent_Lunch_944 Sep 28 '26

Probably anything where you aren’t familiar with what the output is supposed to look like I.e. if you’re looking up service tickets are there always this many black screens or did I mess up the filter on the query

1

u/Imaginary-poster Sep 28 '26

Just ran into this but too much error handling. Had some data missing and could not figure out the issue. Checked the job and all green marks. Checked steps, all green marks. I had to actually read the step output to see something was wrong.

Turns or it was because the query had error handling that exited gracfully when there was an issue. So it triggered no indicators that it had been failing for some time. I only caught it when my downstream script started failing.

1

u/Knight0fdragon Sep 28 '26

I am currently dealing with a case on db2 where the CTEs are causing rows to not aggregate properly causing a ton of issues. On top of that, it only happens during certain times of the day where there is high activity.

It is absolutely infuriating getting wrong results even when the query is right, forcing you to have to rewrite it anyway to combat the database engine itself.

1

u/Dfiggsmeister Sep 28 '26

I’m working with a coworker that’s dealing with something like this. Data changed in such a way where new products with new upcs are entering the market, on top of it, the company changed the way that we are viewing important items. As a result, it’s throwing off targets by excessive amounts. Turns out when he added the data, historical data from old upcs were disregarded because they went from being unimportant to important. This caused essentially the important items to suddenly have all of their volume being attributed to growth vs only a portion of volume being attributed to actual growth.

It has something to do with classification of the variables used that’s causing the issue. It’s an easy fix (merge historical data of old items with new items), but it was a pain to discover what was causing it. A perfect storm of data messiness when new items are coming in and old items are reclassified.

1

u/uncertainschrodinger Sep 28 '26

a lot great answers already so I won't repeat the same stuff, but I'd argue that there's always a way to catch these silent failures - mostly through quality checks and unit tests.

1

u/ThinkFirst1011 Sep 28 '26

For the examples you mentioned those errors are user error vs query. These are ones where you have to know the data and compare against the results. So if you just created a query, does it match previous outputs or documentations. Compare the results by segments, categories etc. 

1

u/Satehyo Sep 28 '26

I always have a hard time with alias uses in joins from people that shouldn’t even be building queries. Luckily I got them working on a day old replication in a separate environment

1

u/bannanaDOG666 Sep 28 '26

When I have multiple sub queries and the error message says there’s more than one variable being returned from the subquery. Those errors don’t contain the line number so I have to comment out all of them and toggle them back on one by one until it breaks again so I am able to ID the culprit. So annoying

1

u/fatbunyip Sep 28 '26 edited Sep 28 '26

Moat memorable is dome ETL process that worked everywhere except in integration test environment (dev pre prod, prod all no issues) and that was frequent but not consistent failures. 

Eventually we figured out (was a while ago details are hazy) that the it was the specificity of the timestamps that the various processes used to pick the latest things to process. 

So basically some columns had ms precision and others were s precision or something like that. In dev everything was fast enough it didn't matter. In pre prod everything was slow enough not to matter. But I'm integration the network lag and other stuff made it so that depending on the moon and the sun it may or may not have failed. 

Really fucken obvious once you know. Really fucken dumb of you don't. 

This is only one example of my ongoing visceral hatred for dates and times in comps sci. 

1

u/TravellingBeard Sep 28 '26

I swear my joins are perfect and criteria definitely correct, yet I sometimes get duplicate rows. I hate having to use DISTINCT but I'm not a data analyst so use it to at least continue troubleshooting

1

u/xenomachina Sep 28 '26

One time the team I was on migrated to Sybase SQL Server. After using it in production for a few weeks we discovered that some of the data we had inserted was mysteriously not in the database.

It turned out that some of the columns had a type with 2 decimal places. Something like DECIMAL(10, 2). Some of our inserts did a division on insert, and apparently on Sybase SQL Server if the result had more than 2 decimal places, the entire row would be discarded and the Sybase JDBC driver would swallow the error. For example:

INSERT INTO foo (..., amount) VALUES (..., 123.45/2)

123.45/2 = 61.725, so this row would be ignored.

Luckily, we caught it early enough that we were able to recover the missing data from logs.

1

u/carlusmagnus Sep 28 '26

Worst I ever had was a filter on November 31. The error was completely cryptic and it was buried in 2,500 lines of SQL.

1

u/Outrageous_Let5743 Sep 28 '26

Hardest one is: syntax error near , with no line number, and the linter doesn't see it.
Or something like values that are silently truncating, because the contract said varchar 3 and now it starts inserting varchar 5 in your sources.

1

u/StickPuppet Sep 28 '26

Business process change that now required a previously unknown data point to be used as part of a join or constraint. "It used to work, but now it doesn't" is always a fun one.

1

u/evilmaus Sep 28 '26

Another bot fishing for training data. Do we have a way to flag these?

1

u/HandbagHawker Sep 28 '26

logical errors. no query engine is going to catch if you put > instead of <

1

u/dolf334 Sep 29 '26

This is why you have to know the data. Not just not how to write the query.

1

u/The_Metitron Sep 29 '26

Laughs in writing hundreds of lines of dynamic sql….

Was the worst month of my life.

1

u/NachoLibero Sep 29 '26

The query that returned different results when I gave it different hints.

1

u/SQLDave Sep 29 '26

Wut

1

u/NachoLibero Sep 29 '26

Exactly.

It took me a while to even figure that out. Before that I would just run the query and randomly get different results.

1

u/SQLDave Sep 30 '26

Not sure I ever would have figured it out. How does it do that? Why did you even consider it? I'm confused and frightened.

2

u/NachoLibero Sep 30 '26

Ran it several times and got different row counts depending on ordering of where clauses. Looked at the query plan for each and the only difference was nested join versus hash join. Reduced it down to 10 records and gave a hint for each type of join amd got different results.

1

u/umognog Sep 29 '26

Upstream system changes that break the transformation logic, but not with an error.

This is where additional data quality tools shine though.

e.g. dbt tests for new values or changed values in columns.

great expectations for quantification changes - value x historically represented 41% of daily records, now it's 6%, far below a statistical threshold for variance.

And lastly, something I don't see often enough; 100% allocation check. I often see "case when else end" type statement where there is no guardrails on that default value. Small amounts to avoid variance checks from everything drops, slowly enough to avoid detection, but the default changes much quicker as that is where is all goes.

Or worse; the default is non existent and there is no "errors" table either.

1

u/CanProfessional766 Sep 29 '26

One of the nastiest ones I ran into was a LEFT JOIN where the join condition wasn’t selective enough. The query ran without any errors, and the results looked perfectly reasonable but it was multiplying rows for certain customers. The tricky part was that the totals were only slightly off so it wasn’t obvious at first. I eventually caught it by comparing the row count before and after the join and checking for duplicate keys.Those silent data issues are definitely harder to debug than a query that just throws an error

1

u/amayle1 Sep 29 '26

Personally I’ve left the “row amplification” bug in too many times. Aka a join you gloss over thinking a one to one row match will occur does not in fact match only one row. Throw an aggregate in the select and you never see the rows but the count is wrong.

1

u/ToastieCPU Sep 29 '26

When someone uses @@IDENTITY instead of SCOPE_IDENTITY()!!!!!!!

1

u/Pieterbr Sep 29 '26

Don’t use either.

1

u/Pieterbr Sep 29 '26

Select max(id) when replication is involved and it’s built into the framework, cough laravel cough.

1

u/hcf_0 Sep 30 '26

Half of the missing values in your text column are null, half are empty whitespace.

The mistake is checking for either. In dirty data, always evaluate `WHERE COALESCE(COLUMN, '') != ''.

Sure, it's expensive, but it's a frequent mistake to not test both on a platform that accepts both entries in a text field.

1

u/Recent_Expression816 Sep 30 '26

Unintended duplicate rows

1

u/NoYouAreTheFBI Sep 30 '26

With nolock. Every fuckin time.

1

u/New_Marionberry_6297 Oct 01 '26

A filter condition mistakenely put in Left join's ON condition rather than put in where clause. This caused a major bug in our project. The pipeline had 20+ SPs and the 5th proc had this bug. Nightmare to find in which layer had the issue.

1

u/attila_molnar Oct 01 '26

Commit race in two independent sessions

0

u/[deleted] Sep 28 '26

[deleted] — view deleted comment

2

u/alinroc SQL Server DBA Sep 28 '26

Microsoft fixed that in 2019 and backported it all the way to 2016 (enabled via trace flag 460). Not only does it give you the name of the column, it gives you the value that'll be truncated.

1

u/digitalnoise Sep 29 '26

My very recent - as in today - experience is that this is still an issue in 2022.

Since they back ported it, I dont think the database compatibility level matters either.

1

u/alinroc SQL Server DBA Sep 30 '26

It's working for my 2019 instances as recently as a couple weeks ago. Error message came right back to the client application, plain as day.

1

u/digitalnoise Sep 30 '26

Huh, weird. I'll try again tomorrow and intentionally force the issue and see what I get.