It's a question of readability. There is no difference in performance.
Old versions of SQL Server were silly enough to look up meta data, but not any more.
SELECT foo FROM bar WHERE EXISTS (SELECT * FROM baz WHERE baz.id = bar.id);
SELECT foo FROM bar WHERE EXISTS (SELECT 1 FROM baz WHERE baz.id = bar.id);
I am not considering NULL or "fun variants" which don't seem intuitive to me.
SELECT foo FROM bar WHERE EXISTS (SELECT NULL FROM baz WHERE baz.id = bar.id);
SELECT foo FROM bar WHERE EXISTS (SELECT 1/0 FROM baz WHERE baz.id = bar.id);
The question popped up in comments just now. I researched the manuals of the most popular RDBMS:
- MS SQL seems to favor
SELECT *
in the manual. - The example in the PostgreSQL 9.4 manual uses
SELECT 1
. - Oracle 11g has
SELECT *
in the language reference. - MySQL 5.7 has
SELECT *
in the reference manual but alsoSELECT 1
in the comments. - SQLite has no example in the language reference.
A search on SO for code:"EXISTS (SELECT 1"
yields 5,048 results.
A search on SO for code:"EXISTS (SELECT *"
yields 5,154 results.
Updated links and counts 07.2015.
So SELECT *
has the popular vote and the big commercial RDBMS on its side.
I find SELECT 1
more intuitive. It's like saying "if at least one exists".
Is SELECT *
more intuitive?
SELECT 1
be like saying "if at least one exists"? I don't see that makes intuitive sense at all. If someone wroteSELECT 2
would you intuitively think that was checking at least 2 exist? – Daceyselect NULL
, but I would ask you to reconsider. The only time anyone would select null is where they don't care what is being returned - to me, it signifies that the only purpose of the query is to check for existence, and is therefore more intuitive than any other option. – Dumbwaiterselect NULL
? That's just not true. Example (one of many):INSERT INTO foo SELECT NULL FROM bar WHERE baz
; – NiesSELECT NULL
. – NiesSELECT NULL
, but you haven't suggested any. – DumbwaiterINSERT INTO foo(val) SELECT NULL FROM bar WHERE baz;
for a table definedTABLE foo(id serial, val text, ts timestamp default current_timestamp)
. In other words: insert a number of events with an unknown value, but the order of events and / or the timestamp are relevant. – Niesselect null
. I think this is another example of what I said in my original comment - "The only time anyone would select null is where they don't care what is being returned". Inside a sub-query, the only time you would do this (that I can think of) would be in anexists
clause, which is why I think this is the most intuitive. – Dumbwaiter