Skip to content
Advertisement

How to select only the first elements satisfying a condition?

I have the following table (simplification of the real problem):

+----+-------+
| id | value |
+----+-------+
|  1 | T     |
|  2 | T     |
|  3 | F     |
|  4 | T     |
+----+-------+

Now a simple SELECT id FROM Table WHERE value='T'; would get me all the IDs where value is T, but I just need, in the example above, the first 2 (1 and 2).

What is the best way to do this? I’d prefer not to use a while loop.

I tagged it MySQL, but a solution working for most database engines would be better.

Edit: based on the answers, I probably wasn’t clear enough:
I only want the first IDs where value is ‘T’. This can be anything from no values to all values.

Edit 2: another example:

+----+-------+
| id | value |
+----+-------+
|  1 | F     |
|  2 | T     |
|  5 | T     |
|  6 | F     |
|  7 | T     |
|  9 | T     |
+----+-------+

The result would be [].

Example 3:

+----+-------+
| id | value |
+----+-------+
|  1 | T     |
|  2 | T     |
|  5 | T     |
|  6 | F     |
|  7 | T     |
|  9 | T     |
+----+-------+

And the result: [1, 2, 5]

Advertisement

Answer

Are you after something as simple as this? just limiting the result?

select id from table where value = 'T' order by id asc limit 2

Just change the order to desc instead of asc if for some reason you want the last two matches, instead of the first two.

I see the criteria has changed a little.

select id
  from `table` t
    where t.id >= (select @min := min(id) from `table` t2 where value = 'T') 
      and not exists (select id from `table` t3 where value = 'F' and id > @min and id < t.id)
   and value = 'T'

demo here

If you want no results when the first value is ‘F’, then this one:

select id
  from `table` t
    where 
       not exists (select id from `table` t3 where value = 'F' and id < t.id)
   and value = 'T'
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement