Skip to content
Advertisement

Select by code and if there is no result select any other

Imagine there are some table with some data:

There can be only one record with code == 0002. Also it may be absent.

How could I select record with code == 0002 and if there is no such record then select any other record with single query?

For example for the data example above query returns record with id == 2. And for the example below:

any other (one)?

Advertisement

Answer

One method uses order by and limiting the results to one row:

This uses Standard SQL. Not all databases support fetch first, so you might need to use limit or select top or something else.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement