-1

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
  • 605,456
  • 145
  • 1,078
  • 1,228
giozh
  • 9,868
  • 30
  • 102
  • 183

3 Answers3

4

something like

select *
from myTab
where not is_available
order by id asc
limit 1
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
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
  • 605,456
  • 145
  • 1,078
  • 1,228
Vijay
  • 8,131
  • 11
  • 43
  • 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
  • 43,142
  • 8
  • 66
  • 109