1

I am brand and new with my current job i have see the following SQL sentence.

SELECT t.name store,p.id, p.name,count(1)
FROM regular_shippings sh
JOIN
   products p ON matching columns.
ANOTHER JOINS
WHERE criteria
AND anotherCriteria
GROUP BY p.id
HAVING count(1) > 0
ORDER BY t.name,count(1) desc;

My first impression is counting the records in

the select

also in the

having by 

also in the

order by 

Impacting performance for me is better use a alias. But is this assertion correct? or is not is doing the job only once? or the engine is smart enough to recognize it and just replace the previous values of the count(1) in the latter calls?

What i mean this query would perform better?

SELECT t.name store,p.id, p.name,count(1)c
FROM regular_shippings sh
JOIN
   products p ON matching columns.
ANOTHER JOINS
WHERE criteria
AND anotherCriteria
GROUP BY p.id
HAVING c>0
ORDER BY t.name,c desc;

Sorry if the question is plain!

2
  • The use of an alias would have little to no impact on the query. The expensive parts of the query would typically be the group by and order by and reading the data. Commented Sep 12, 2018 at 11:15
  • please see my edited question thanks. Commented Sep 12, 2018 at 11:18

1 Answer 1

1

COUNT(1) is a result from the aggregation (GROUP BY). It is used in

  • the SELECT clause to be displayed,
  • in the HAVING clause to limit results and
  • in the ORDER BY clause for sorting.

It's not three different counts taking place. So it doesn't matter whether you are giving it an alias or not.

(On a sidenote: Most DBMS don't even allow the alias name given in the SELECT clause to be used in HAVING, as HAVING is supposed to occur before SELECT.)

Sign up to request clarification or add additional context in comments.

4 Comments

it's not counting the records on the 3 stages?? it's counting only once?
@ThorstenKettner . . . I am guessing that MySQL would actually do the count three times. However, the overhead is minimal. Do you have a reference specifying that MySQL would do such expression elimination?
i think that MySql will do the count 3 times.
So you think that MySQL checks which results it needs after aggregation, and this is t.name and p.id and p.name and count(1) and count(1) and count(1)? That looks quite unlikely. But I must admit that I don't know how MySQL works internally, so my answer is no more than a sophisticated guess it seems. I always took it for granted that database systems look at what they actually need to select. Hence: @Gordon Linoff: No, I don't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.