Postgres how to implement calculated column with clause

会有一股神秘感。 提交于 2019-11-30 03:57:16

问题


I need to filter by calculated column in postgres. It's easy with MySQL but how to implement with Postgres SQL ?

pseudocode:

select id, (cos(id) + cos(id)) as op from myTable WHERE op > 1;

Any SQL tricks ?


回答1:


If you don't want to repeat the expression, you can use a derived table:

select *
from (
   select id, cos(id) + cos(id) as op 
   from myTable 
) as t 
WHERE op > 1;

This won't have any impact on the performance, it is merely syntactic sugar required by the SQL standard.

Alternatively you could rewrite the above to a common table expression:

with t as (
  select id, cos(id) + cos(id) as op 
  from myTable 
)
select *
from t 
where op > 1;

Which one you prefer is largely a matter of taste. CTEs are optimized in the same way as derived tables are, so the first one might be faster especially if there is an index on the expression cos(id) + cos(id)




回答2:


select id, (cos(id) + cos(id)) as op 
from selfies 
WHERE (cos(id) + cos(id)) > 1

You should specify the calculation in the where clause as you can't use a alias.



来源:https://stackoverflow.com/questions/32187583/postgres-how-to-implement-calculated-column-with-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!