Skip to content
Advertisement

Select one existing row order by where clause

I have a table like that:

ID | lang
---------
1  | ru
2  | en

I want to select 1 top existing row from my where clause. Not ordering by id or by lang, but ordering by my where clause.

where lang in ('en', 'ru') should return row with lang en because en comes firstly in my clause.

where lang in ('de', 'ru') should return row with lang ru because row with de is not existed.

This not works properly because it is sorted by “default” order:

select * from "table_name" where lang in ('en', 'ru') limit 1;

Advertisement

Answer

There is no default order. A SQL query without an ORDER BY returns an unordered result set — and the ordering can change between runs of the same query on the same data.

Just add the order by you want. For instance:

order by (case lang where 'en' then 1 when 'ru' then 2 end)

Or use arrays:

where lang = any (array['en', 'ru'])
order by array_position(array['en', 'ru'], lang)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement