r/SQL • u/SilaPrirode • Aug 27 '26
SQL Server Finding missing rows within the same table
Hello, I have a solution already but I think it can be done in a faster/neater way.
Let's say we have a table with: ORDER_ID, Article, Value.
For every order that comes in two rows end up in table, example:
ID_1, shoes, pair
ID_1, shoes, price
where price is being pulled from a different table.
I am looking for a way to find all ORDER_IDs that have only one row, because the price didn't exist in that other table so price row didn't form up. It doesn't throw a null value because of the way it's setup, if there is no price the row won't form at all!
I solved this with a standard left joining the table with itself, but I suspect there is a way to this easier?
10
u/GRRRRRRRRRRRRRG Aug 27 '26
Try group by order_id, article having count(*) =1 on your table
7
u/Impossible_Disk_256 Aug 27 '26
Is this an e-commerce app? Who designed this obscene non-normalized table?
Entity-Attribute-Value can have a place (e.g, attributes for e-commerce items that may vary widely by merchandise category or even vendor. But price as just another EAV row? No.
Price in a lookup table by date or currency? Maybe. But w/ currency fluctuations, even that may be better served by conversion service.
1
u/Then_Artichoke3330 Aug 27 '26
WITH onlySingles AS(
SELECT ID, COUNT(*) AS how_many
FROM the_transactions
GROUP BY ID
HAVING COUNT(*) = 1)
SELECT * FROM onlySingles;
1
u/jaxjags2100 Aug 27 '26
Wouldn’t you just do an inner join on the order id to the price table? If no order id exists on the price table then no row would populate for it.
The ask was a bit confusing and its early 😂
1
u/NW1969 Aug 27 '26
For a large volume of data, this may be the most efficient approach:
SELECT DISTINCT t.ORDER_ID
FROM my_table t
WHERE NOT EXISTS (
SELECT 1
FROM my_table p
WHERE p.ORDER_ID = t.ORDER_ID
AND p.Value = 'price'
);
2
u/Lamyya Aug 27 '26
I assume you'd have a column that tells you if it's "pair" or "price" rather than just the value, if so just group by id and filter on whether price exists. If you don't then the other table is likely needed
1
u/Wild_Cup_5575 Aug 27 '26
Count the order_id would be my way to go as a first step
1
u/Yavuz_Selim Aug 27 '26
Can you share some example data? Your question seemed easy to answer, but you added conditions later on.
You can post a table (using markdown), or create it in Excel and upload screenshots to imgur.com and share the image link here.
1
u/SkullLeader Aug 27 '26 edited Aug 27 '26
SELECT OrderId FROM main
EXCEPT
SELECT OrderId FROM main WHERE Value = ‘Price’
3
u/[deleted] Aug 27 '26
[removed] — view removed comment