Search code examples
sqlpostgresqlpostgresql-8.1

How to use an 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 it in PostgreSQL 8.1.23 i get this error:

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

Anybody can help me to put it to work? I need the availale items first, after them the unnavailable items. Many thanks!


Solution

  • You can always ORDER BY this way:

    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