I have a rather simple question: What does "SELECT 1 FROM ..." accomplish? I am debugging a software program that is sending a "SELECT 1" statement to the database, and I am basically curious. Does it simply select one column from the record it finds?

    Requires Free Membership to View

Great question. No, it selects the same column from all the rows it finds!

I would be surprised to see a "SELECT 1" query all by itself as a stand-alone query. By itself, it's useless. Like all SELECT statements, it returns a result set, and in this case, the result set consists of a number of rows, where each row has exactly one column, and where the value of that column is an integer 1. In other words, there's a 1 in each row, and nothing else! The result set has as many rows as there are in the table being selected from, subject to WHERE conditions. Hence the result set, by itself, a table of 1s, is useless. The only meaningful information you can get from it is the number of rows, and that can be obtained a lot more efficiently by using COUNT(*).

More likely, you saw it in a subselect. SELECT 1 or SELECT * or SELECT NULL are constructions commonly used in an EXISTS subselect. In an EXISTS subselect, the database does not actually "retrieve" rows, and it does not always need to scan the entire result set for the subselect, because just one row will provide an answer. That answer is either TRUE or FALSE.

There's a somewhat contrived but illustrative example of an EXISTS subselect in one of my previous answers, How does WHERE EXISTS ( SELECT NULL... ) work? (22 February 2002).

This was first published in October 2002

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: