How to use ALIAS in a PostgreSQL ORDER BY clause?

I have the following query:

select title, ( stock_one + stock_two ) as global_stock from product order by global_stock = 0, title; 

Running in PostgreSQL 8.1.23. I get this error:

Query failed: ERROR: column "global_stock" does not exist

Can anyone help me make it work? First I need items with available goods, after them inaccessible items. Thank you very much!

+4
source share
2 answers

You can always ORDER BY as follows:

 select title, ( stock_one + stock_two ) as global_stock from product order by 2, 1 

or wrap it in another SELECT:

 SELECT * from ( select title, ( stock_one + stock_two ) as global_stock from product ) x order by (case when global_stock = 0 then 1 else 0 end) desc, title 
+12
source

The following shall be used in the decision:

 select title, ( stock_one + stock_two ) as global_stock from product order by 2, 1 

However, the alias should work, but not necessarily this expression. What do you mean by global_stock = 0? You mean the following:

 select title, ( stock_one + stock_two ) as global_stock from product order by (case when global_stock = 0 then 1 else 0 end) desc, title 
+3
source

All Articles