patternsqlMinor
How and when do I use an alias in my SQL statement
Viewed 0 times
howstatementsqlwhenandusealias
Problem
I have a query in which I do some calculation and then I give that column an alias. In the next column I would like to use the result of that calculation in an IF statement. MySQL did not recognise the alias when I used it as a condition but instead required me to rewrite the whole query, put some brackets around it and then carry out the condition checking.
Here is the SQL query:
I would like to use the column alias called Percentage in the IF statement
Here is the SQL query:
SELECT StudentId
,SubjectID
, (COUNT(StudentId) / (
SELECT COUNT(SubjectID)
FROM lectureattendancein
WHERE SubjectID ='MIS4' ) * 100) AS Percentage
, IF((COUNT(StudentId) / (
SELECT COUNT(SubjectID)
FROM lectureattendancein
WHERE SubjectID ='MIS4'
)* 100) >= 80, 'ALLOWED', 'NOT ALLOWED') AS ExamAdmit
FROM attendancein
GROUP BY StudentId, SubjectID
HAVING SubjectID='MIS4'
ORDER BY StudentId ASCI would like to use the column alias called Percentage in the IF statement
Solution
Structured Query Language is a declarative language. Declarative languages don't tell the computer how to run, they simply describe the desired result. The implication here is the alias is only important for the results, not the execution of the query.
Since MySQL (and most other RDBMSs) only apply aliases after the query has completed, MySQL will complain if you attempt to use an alias in another column since it doesn't actually understand what the alias represents until the query completes.
Since MySQL (and most other RDBMSs) only apply aliases after the query has completed, MySQL will complain if you attempt to use an alias in another column since it doesn't actually understand what the alias represents until the query completes.
Context
StackExchange Database Administrators Q#125251, answer score: 5
Revisions (0)
No revisions yet.