I’ve been doing some SQL for an exam I have on thursday and I have doubts if I’m using the EXISTS statement correctly.
So, here I have a DB with 2 tables
Machines Maintenance
============ ==============
PK ID_Machine PK ID_Machine FK
Name PK ID_Task FK
Date_bought Date
So, the query they want me to write says “Show all data from the oldest machine that has not received any maintenance in 2011”
The way I did it is the following:
SELECT M.ID_MACHINE, M.NAME, M.DATE_BOUGHT
FROM MACHINES M
WHERE NOT EXISTS (SELECT MA.*
FROM MAINTENANCE MA
WHERE MA.ID_MACHINE = M.ID_MACHINE
AND YEAR(MA.DATE) = 2011)
AND EXISTS (SELECT MIN(M2.DATE_BOUGHT)
FROM MACHINE M2
WHERE M2.ID_MACHINE = M.ID_MACHINE)
Is this a correct way to do this query? does it makes sense that I use SELECT MIN() inside a EXISTS statement?
Thanks in advance to everyone!
When you use exists, it only validates that a piece of data is returned for the filters (joins and where). Often, you will see exists queries with select 1 from…. This is because the actual return values are not used.
This was a novel idea, and one I had to test out personally. However, as I stated above, the return data is ignored for the most part. It only cares that the join and where filters match and does not care about the MIN, even though it does seem to be a filter in itself. It is more of an aggregation, so the underlying data remains, it seems. The first exists is valid, but the next part does need work. I have updated it below for what I would do.