Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a SELECT 1 from table?

Tags:

I came across a fictitious SQL, i am not sure what is the original intend, it looks like:

SELECT COUNT (*)
INTO miss
FROM billing b
WHERE b.network= network1 
and NOT EXISTS (SELECT 1 from vas NV WHERE NV.network =  
b.network);

Why is there a select 1, and not exists?

like image 770
Oh Chin Boon Avatar asked Oct 03 '11 09:10

Oh Chin Boon


People also ask

What is the meaning of select * from table *?

An asterisk (" * ") can be used to specify that the query should return all columns of the queried tables. SELECT is the most complex statement in SQL, with optional keywords and clauses that include: The FROM clause, which indicates the table(s) to retrieve data from.

What does 1 mean in SQL?

WHERE 1 is a synonym for "true" or "everything." It's a shortcut so they don't have to remove the where clause from the generated SQL.

What is the meaning of select count 1?

There is no difference. COUNT(1) is basically just counting a constant value 1 column for each row. As other users here have said, it's the same as COUNT(0) or COUNT(42) . Any non- NULL value will suffice.

What is the difference between select * and select 1?

Select * from any table will fetch and display all the column in that table, while Select 1 from any table will display one row with 1 without any column name.


2 Answers

When using the EXISTS keyword you need to have a sub-select statement, and only the existence of a row is checked, the contents of the row do not matter. SELECT is a keyword that controls what is inside the columns that are returned. SELECTing 1 or NV.network will return the same number of rows.

Therefore you can SELECT whatever you want, and canonical ways to do that include SELECT NULL or SELECT 1.

Note that an alternative to your query is:

SELECT count(*) INTO miss
  FROM billing b
  LEFT JOIN vas NV ON NV.network = b.network
 WHERE b.network = network1
   AND NV.network IS NULL

(left join fills right-hand columns with NULL values when the ON condition cannot be matched.

like image 83
Benoit Avatar answered Oct 18 '22 09:10

Benoit


SELECT 1 from vas NV WHERE NV.network =  b.network

If this query returns a row, it means that there is a record in the NV table that matches one in the billing table.

NOT EXISTS negates it, satisfying there WHERE clause if there is NOT a record in the NV table that matches one in the billing table.

like image 31
duffymo Avatar answered Oct 18 '22 09:10

duffymo