Putting aside any opinions on performance, I've been trying to test a notion about whether a couple queries would output the same data (ordering doesn't matter).
SELECT *
FROM articles
WHERE (
last_updated >= %s
OR id IN (1, 2, 3)
)
AND created_at IS NOT NULL
SELECT *
FROM articles
WHERE last_updated >= %s
AND created_at IS NOT NULL
UNION
SELECT *
FROM articles
WHERE id IN (1, 2, 3)
AND created_at IS NOT NULL
I think they're equivalent, but I can't prove it to myself.
Edit:
Aye, looking at the replies, I'm becoming aware that I left out a couple key assumptions I've made. Assuming:
a) id
is a PRIMARY KEY
(or otherwise UNIQUE
)
b) I mean equivalent
insofar as "the rows returned will contain equivalent data same (though maybe ordered differently)"
~~Your results will be equivalent~~ The UNION will deduplicate your results.
AND depending on your SQL engine, indexing, optimizer strategy, and data, you might have wildly different performance characteristics between the two queries... If that matters to you
You can test this out yourself on the code below using SQLFiddle
Aye, looking at the replies, I'm becoming aware that I left out a couple key assumptions I've made. Assuming:
a)
id
is aPRIMARY KEY
(or otherwiseUNIQUE
)b) I mean
equivalent
insofar as "the rows returned will contain equivalent data same (though maybe ordered differently)"