Skip to content
Advertisement

How to select only the first elements satisfying a condition?

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

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:

The result would be [].

Example 3:

And the result: [1, 2, 5]

Advertisement

Answer

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

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.

demo here

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement