I have two very simple questions
1. Multiple vs Single COUNT on same col
I need to perform CASE on an aggregate column like this:
SELECT tbl_students.school, COUNT(tbl_students.id) as students, (
CASE
WHEN students > 1000 THEN 'SMALL'
WHEN students > 10000 THEN 'MEDIUM'
WHEN students > 100000 THEN 'LARGE'
END
) as size
FROM tbl_students
GROUP BY tbl_students.school
But MySQL does not allow using the column alias within the SELECT part. So instead of above, I'll have to write:
SELECT tbl_students.school, COUNT(tbl_students.id) as students, (
CASE
WHEN COUNT(tbl_students.id) > 1000 THEN 'SMALL'
WHEN COUNT(tbl_students.id) > 10000 THEN 'MEDIUM'
WHEN COUNT(tbl_students.id) > 100000 THEN 'LARGE'
END
) as size
FROM tbl_students
GROUP BY tbl_students.school
My question is "will using COUNT multiple times on the same column actually performs COUNT multiple times? If yes, will it also result in performance issues when there are millions of records?".
2. Multiple vs Single col index
If a table has following three columns:
tbl_students(id, username, school, firstname, lastname)
And has composite unique key for username
and school
. My question is, do I need to create a separate index for school
column if I am searching only in school
column?
1 Answer 1
This is straightforward enough and more efficient:
SELECT school,
CASE
WHEN students > 1000 THEN 'SMALL'
WHEN students > 10000 THEN 'MEDIUM'
WHEN students > 100000 THEN 'LARGE'
END as size
FROM ( SELECT school,
COUNT(*) as students
FROM tbl_students
GROUP BY school
) AS cts
It would need INDEX(school)
or any index starting with school
.
-
I tried it but it makes the query too slow when there are millions of students.D3 K– D3 K2019年10月16日 06:19:04 +00:00Commented Oct 16, 2019 at 6:19
-
How many schools?Rick James– Rick James2019年10月16日 21:38:53 +00:00Commented Oct 16, 2019 at 21:38
GROUP BY
?COUNT()
will be calculated once. If you're afraid nevertheless you may use intermediate UDV. 2) No, if the index is(school, username)
and yes if in backward order.SELECT
part so it would be good to avoid any unnecessary details. @Akina do you have any reference to what you are saying and what is intermediate UDV?school
column or addGROUP BY school
. What you have does not make sense. After that, we can look deeper into your question.GROUP BY
clause as it was causing some confusion. Any feedback on second part of the question?