Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In a simple query like

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'.

share|improve this question
up vote 2 down vote accepted
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)

share|improve this answer

I'm not a MySQL guy either but believe that this does the trick.

FROM table
WHERE id='x' 
FROM table

Disclaimer: I'm not sure whether this is documented/guaranteed behavior.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.