I’m new to programming languages and am trying to get the customers with the longest and shortest names, combine them in a single column, and sort them by longest then shortest names.
Here's what I have. How can I query to get my desired result in MySQL?
SELECT max(length(customer_id)) AS longest, min(length(customer_id)) AS lowest
FROM orders
SELECT concat(longest,lowest) AS diff
FROM orders
ORDER BY diff desc
Table is orders
customer_id | longest | lowest |
---|---|---|
John | Nathaniel | John |
Michael | ||
Nathaniel |
Expected results are:
diff |
---|
Nathaniel |
John |
CodePudding user response:
It sounds like you want a UNION
operator. Something like:
SELECT max(length(customer_id)) as CUSTOMER_ID
FROM orders
UNION
SELECT min(length(customer_id))
FROM orders
ORDER BY CHAR_LENGTH(CUSTOMER_ID)
This should find your max and min entries and union them together into a single column named CUSTOMER_ID
. Then you just sort them by character length.