Can I skip row form select based on condition?

56 views Asked by At

Let's say I have:

ID - value
-----------
1  - pass
2  - pass
3  - pass
4  - fail

and my select is:

SELECT * 
FROM table 
ORDER BY id DESC 
LIMIT 1

However, I wish to add a condition that only if this value will be "pass" then return.. otherwise return nothing.

So if I do WHERE value="pass" then it actually gives me ID 3, this is what I do not want, I prefer nothing if the last value is not "pass".

So something like:

IF value != "pass" THEN SKIP?

Thank you

3

There are 3 answers

0
Saikat On BEST ANSWER

How about this? This should allow you to print blank if the last value is not 'pass'.

with cte AS
(
  select 1 as id , 'pass' as VALUE
  union
  select 2 as id , 'pass' as VALUE  
  union
  select 3 as id , 'pass' as VALUE
  union
  select 4 as id , 'fail' as VALUE
)  
select 
   id , 
   value 
from cte
where id = (select max(id) from cte) and value = 'pass';
0
Thorsten Kettner On

Here is one solution. You want the ID to be the maximum ID and the value to be 'pass'. Hence:

SELECT *
FROM mytable 
WHERE id = (SELECT MAX(id) FROM mytable)
AND value = 'pass';
0
Luuk On

Only return id when the value='pass'

SELECT CASE WHEN value='pass' THEN id ELSE '' END
FROM mytable
ORDER BY id DESC
LIMIT 1