-2

I have a table like:

create table myTab(
  id integer primary key,
  is_available boolean not null default true
);

I need to do a query that returns only the first encountered row that has is_available set to false.

Erwin Brandstetter
  • 479,275
  • 111
  • 893
  • 1,042
giozh
  • 8,808
  • 27
  • 89
  • 163

3 Answers3

3

something like

select *
from myTab
where not is_available
order by id asc
limit 1
Roman Pekar
  • 92,153
  • 25
  • 168
  • 181
1

Try out this ..

select id,is_available from myTab
where is_available = false
order by id asc
limit 1

If you want row from last inserted then go with this ..

    select id,is_available from myTab
    where is_available = false
    order by id desc
    limit 1
Erwin Brandstetter
  • 479,275
  • 111
  • 893
  • 1,042
Vijay
  • 7,211
  • 9
  • 38
  • 69
  • 1
    in my case, ordering by id isn't a bad solution, because i the id field involved in my query are a subset of all id contained in table (i have also another clause on WHERE) – giozh Aug 11 '13 at 09:22
1

Alternatively, you could use NOT EXISTS to find the first tuple, in most cases this is the fastest solution, too:

SELECT *
FROM myTab mt
WHERE mt.is_available = False
AND NOT EXISTS (
    SELECT *
    FROM myTab nx
    WHERE nx.is_available = False
    AND nx.id < mt.id
    );
wildplasser
  • 38,231
  • 6
  • 56
  • 94