Example:
SELECT COUNT(id) AS total_orders,
( ( SELECT COUNT(id) FROM orders WHERE status = 'Closed' ) / total_orders * 100) AS percent_closed_orders
FROM orders
Question: How can I use total_orders in the subquery? I get a an error "unknown column ‘total_orders’ in ‘field list’".
2
Answers
You can’t use a column alias in the same SELECT statement in which it is defined. You can, however, use the alias in a subsequent SELECT statement, provided that the alias is defined in an outer SELECT statement.
In your example, you would need to move the inner SELECT statement into a subquery in order to be able to use the total_orders alias:
If
id
cannot be NULL (for example it is primary key) then you may useCOUNT(*)
for to count total rows amount.