HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to use OR in query with priority?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
prioritywithqueryhowuse

Problem

In a simple query like

SELECT * 
FROM table
WHERE id='x' OR id='y'


How to give a priority to get only one of the WHERE clauses?

I mean getting rows with id='x'. Only if there is no row, get row with id='y'.

In other words, do not use id='y' if there is a row for id='x'.

Solution

SELECT * 
FROM   table
WHERE  id IN ('x', 'y')
AND    (id='x' OR NOT EXISTS(SELECT id FROM table WHERE id='x'))


should do the trick (caveat: I'm an MSSQL guy and haven't tried that in mySQL, but I suspect that syntax is accepted just fine there too) though the efficiency will depend on how many rows matching the first filtering clause there are (for every row matching id='x' OR id='y' he subquery in the EXISTS part will probably be run unless the query planner is bright enough to see that it depends on nothing in the outer query so can be run once and the result reused - if you are only expecting at most two (which with a column name like id I suspect is the case) this should not be an issue)

Code Snippets

SELECT * 
FROM   table
WHERE  id IN ('x', 'y')
AND    (id='x' OR NOT EXISTS(SELECT id FROM table WHERE id='x'))

Context

StackExchange Database Administrators Q#49416, answer score: 3

Revisions (0)

No revisions yet.