Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: case when using alias column

Tags:

postgresql

I would like to do something like this:

select 
case when (select count(*) as score from users t1 )   >5   THEN score   else 0 end 

When i try it i get error:

column score doesn't exists. 

Can i do this in some other way? I need it to set a LIMIT value. I would like to do it of course in this way:

select 
case when (select count(*) as score from users t1 )   >5   THEN (select count(*) as score from users)    else 0 end 

but than I need execute two times this same query. Have someone some ideas?

like image 704
user2514376 Avatar asked Oct 20 '25 12:10

user2514376


1 Answers

You can use WITH clause:

with a as (select count(*) score from t)
select case when score > 5 then score else 0 end from a;

Or subquery (inline-view):

select case when score > 5 then score else 0 end 
from (select count(*) score from t) t;
like image 165
ntalbs Avatar answered Oct 23 '25 04:10

ntalbs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!