Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Why we use "where 1" in this query

Author  Topic 

ashutosh011283
Starting Member

6 Posts

Posted - 2011-06-09 : 08:35:58
Hi Friends,

I have some question related to below query for sql server.
What is the meaning of using "Where 1" for getting second heighest sal.
select *from emp e where 1=(select count(distinct sal) from emp m where m.sal>e.sal)

Thanks
Ashutosh

ashutosh upadhyay

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2011-06-09 : 09:07:17
I can see no "Where=1" and it would give a syntax error...


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

ashutosh011283
Starting Member

6 Posts

Posted - 2011-06-10 : 00:37:45
Sorry friend I did mistake while write the syntax ,correct syntax is below
What is the meaning of using "Where 1" for getting second heighest sal.
"Where 1=" used in below query.
select *from emp e where 1=(select count(distinct sal) from emp m where m.sal>e.sal)


ashutosh upadhyay
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2011-06-10 : 01:37:49
The statement means (in my words):
select a row from emp
and then count the rows where the sal is higher than the sal of th actual row.
If the count equals 1 then there is only one row with a higher sal hence the actual row must have the second highest sal.

You can also write:
select * from emp e where (select count(distinct sal) from emp m where m.sal > e.sal) = 1

edit: typo

No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

ashutosh011283
Starting Member

6 Posts

Posted - 2011-06-13 : 00:45:04
Thanks

ashutosh upadhyay
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2011-06-14 : 04:16:01
Many methods
http://beyondrelational.com/blogs/madhivanan/archive/2007/08/27/find-nth-maximum-value.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -