简体   繁体   中英

Using LENGTH(computed column) in ORDER BY in Postgres sql

SELECT  concat(first_name,last_name)  AS full_name from customer
ORDER BY  length(full_name);

I tried to run this in postgre sql database. I give me this erro

[42703] ERROR: column "full_name" does not exist

How would I resolve this? Order rows by length of full name.

Can you please try either of the below?

SELECT  concat(first_name,last_name) COLLATE "C"  AS full_name from customer
ORDER BY  length(full_name)

OR

SELECT  concat(first_name,last_name)  from customer
ORDER BY  length(concat(first_name,last_name))

This would work, and avoids the double use of concat()

WITH results AS (
  SELECT concat(first_name, last_name) AS full_name FROM customer
)
SELECT full_name FROM results ORDER BY length(full_name)

Postgres adheres to the standard by allowing column aliases as order by keys. So this works:

SELECT  CONCAT(first_name, last_name)  AS full_name
FROM customer
ORDER BY full_name;

However, it does not extend this to expressions using the aliases. You can fix this using subqueries or CTEs. I might also suggest a lateral join:

SELECT v.full_name
FROM customer c CROSS JOIN LATERAL
     (VALUES (CONCAT(c.first_name, c.last_name))) v(full_name)
ORDER BY v.full_name;

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