Michael Silva Michael Silva - 6 months ago 24
SQL Question

SQL select entries from table where atribute equals parameter else select * entries

It is possible in SQL (ORACLE) to select all entry from a table where an atribute equals an parameter and if not select all the others entries?

like in this example:

COD | Name

1 | Monday

2 | Thursday

3 | Saturday

parameter=3

when cod equals parameter(cod=3) return entry of cod parameter(cod=3) (including cod and name)

else

return all others entries different from parameter(cod=3) (including cod and name) (like 1 Monday and 2 Thursday)

Is it possible with SQL (oracle), or i need something like PLSQL?

Answer

I'd use a correlated query and a non-correlated query:

SELECT COD, NAME 
FROM TABLE a
WHERE EXISTS (SELECT 1 FROM TABLE b WHERE b.COD = a.COD AND b.COD = 3)
    OR NOT EXISTS (SELECT 1 FROM TABLE c WHERE c.COD = 3)

I'm not sure if I'm following your logic, entirely, however.

And, actually, in cases where it's all from one table it can be simplified to just:

SELECT COD, NAME 
FROM TABLE a
WHERE a.COD = 3
    OR NOT EXISTS (SELECT 1 FROM TABLE c WHERE c.COD = 3)