Question

I have a SQL statement similar to this:

SELECT COUNT(*) AS foo, SUM(foo) AS foo_sum FROM bar

But MySQL doesn't allow this because foo is an alias. Does anyone have an idea of how this could be accomplished in SQL?

Was it helpful?

Solution

No, you can't use an alias in the select-list or a WHERE clause. You can only use the alias in a GROUP BY, HAVING, or ORDER BY.

You can also use aliases defined in a subquery:

SELECT foo, SUM(foo) AS foo_sum
FROM (
  SELECT COUNT(*) AS foo
  FROM bar
);

OTHER TIPS

SELECT SUM(foo) as foo_sum
FROM 
(
    SELECT COUNT(*) AS foo
    FROM bar
    GROUP BY baz
)

I think it's not a good idea. If you want to make a big query, it's better to do it without a subquery. Use COUNT(*) and bigger functions without alias, if you need it.

I made a query with aliases and subqueries. It took about an hour! Then I reproduced the query without the alias. It went down to about 45 minutes. Forget about subqueries in this situation. It's less hard and more pretty, but it makes your query slower.

I don't know what you are trying to do but with above solutions you are running subquery on alias table which is not efficient.

SELECT foo 
FROM (SELECT COUNT(*) AS foo FROM employees) AS T;

Basically T is your alias table and it returns foo column with count which is single record and there is no meaning of using SUM(foo) function on it since it is single record.

Anyways simple answer:

SELECT Count(1) AS foo from employees;

Since the COUNT function will return the same results regardless of what NOT NULL field(s) you include as the COUNT function parameters (ie: within the parentheses), you can use COUNT(1) to get better performance. Now the database engine will not have to fetch any data fields, instead it will just retrieve the integer value of 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top