tags:

views:

45

answers:

4

How can the lookup order of 'where exists' be changed

example

SELECT name, dialcode
FROM np_prefixes
WHERE EXISTS ( SELECT d.name 
            FROM np_prefixes d
            GROUP BY d.name )
GROUP BY name

)

I require to get the first record it comes across in the reverse order it is currently getting as a example the result returned is 21379 (high to low) but I require 21377(low to high)

+1  A: 

ORDER BY DESC? I'm not sure I understand your question though

Vidar Nordnes
+1  A: 

try this:

Select name, Min(dialcode)
From np_prefixes 
Where Exists( Select d.name  
              From np_prefixes d 
              Group By d.name ) 
Group By name 

and actually, you don't need the Where Exists (as you've written it, it doesn't do anything anyway):

Select name, Min(dialcode)
From np_prefixes 
Where name is not null 
Group By name 
Charles Bretana
I don't think you need the `WHERE name is not null` line either.
Marcus Adams
@Marcus... Just to avoid getting an aggregate row for null names, if any exist...
Charles Bretana
+1  A: 

The order in an EXISTS clause does not matter. EXISTS only returns true or false as soon as one of the criteria is satisfied.

If you want the final output ordered differently, you need to specify an ORDER BY clause:

SELECT name, dialcode
  FROM np_prefixes
 WHERE EXISTS ( SELECT d.name 
                  FROM np_prefixes d
              GROUP BY d.name )
GROUP BY name
ORDER BY dialcode
OMG Ponies
+1  A: 

I think that your query is the same as this:

SELECT name, dialcode
FROM np_prefixes
GROUP BY name

Take a look at MAX() or MIN() to get the highest or lowest value in a group or possibly just ORDER BY and a limit clause.

Marcus Adams