Instead of the IN
operator, you can use CASE
to check if a record exists. It's like doing IF
in a structured language.
See an example:
SELECT
CASE
WHEN EXISTS(select cor from cores where cor = 'verde') THEN 'verde'
ELSE (select cor from cores where cor = 'vermelho')
END,
CASE
WHEN EXISTS(select cor from cores where cor = 'azul') THEN 'azul'
WHEN EXISTS(select cor from cores where cor = 'verde') THEN 'verde'
ELSE (select cor from cores where cor = 'vermelho')
END
Alternatively, you can use the COALESCE
function, which will return the first non-null parameter, thus setting an order of priority.
See the example:
select
COALESCE(
(select cor from cores where cor = 'azul'),
(select cor from cores where cor = 'verde'),
(select cor from cores where cor = 'vermelho')
)
See also sqlfiddle with functional examples.