简体   繁体   中英

ORDER BY lower case of output column

I'm able to run this Postgres query without any issue:

select
(select product_types.name from product_types
 where product_types.id = products.product_type_id) AS product_type_name
 from products
order by product_type_name

But when I tried to order by lower case it doesn't work:

select
(select product_types.name from product_types
 where product_types.id = products.product_type_id) AS product_type_name
 from products
order by lower(product_type_name)

I get this error:

ERROR:  column "product_type_name" does not exist
LINE 4: order by lower(product_type_name)
                       ^

********** Error **********

ERROR: column "product_type_name" does not exist
SQL state: 42703
Character: 156

Can someone please shed me some light on this?

At first sight, your first query could be rewritten just this way:

select pt.name product_type_name from product_types pt
join products p on pt.id = p.product_type_id
order by pt.name

Then, ordering with the lower function would mean just changing the order by to:

order by lower(pt.name)

Quoting the manual page on SELECT :

Each expression can be the name or ordinal number of an output column (SELECT list item), or it can be an arbitrary expression formed from input-column values.

You were trying to order by an expression formed from an output -column, which is not possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM