Where Clause and Having clause
Basic Key Point about WHERE Clause and Having Clause. In most of the Interview this is frequently asked SQL Interview Question. Question Can be asked in different way which is below as a sample for your Reference.
⇒ Difference Between WHERE and HAVING Clause ?
⇒ Which Clause is used with an Aggregate function?
⇒ Why do we use having clauses?
- WHERE Clause and HAVING Clause is especially for filtering the set of record from the table based on the condition.
- WHERE Clause cannot be used with SQL Aggregate Function Like COUNT(), SUM(), AVG() where HAVING Clause can be used.
- HAVING Clause filter the set of record from the group row not on Individual row, WHERE Clause filter the record Set from the Column row.
Consider Student_Table for writing SQL Clause Example:
The Main difference WHERE Clause and HAVING Clause you can understand using with GROUP BY in the same query.
FullName
|
DOB
|
MARKS
|
M KUMAR
|
07-04-2003
|
60
|
MOHAMMED ISHAQ
|
14-06-2002
|
63
|
ANBUSELVAM S
|
18-06-2004
|
75
|
MORTINPRIYADOSS JAMES
|
08-03-2004
|
56
|
JAGAN J
|
10-04-2003
|
73
|
NAVEENKUMAR
|
02-06-2004
|
86
|
HARIKRISHNAN R
|
15-11-2003
|
45
|
VIJAY K
|
14-11-2002
|
32
|
SUTHAKAR
|
23-03-2004
|
94
|
KATHIRESAN P
|
15-11-2007
|
87
|
The Main difference WHERE Clause and HAVING Clause you can understand using with GROUP BY in the same query.
Query Example:
⇛ SELECT * FROM Student_Table WHERE MARKS < 80 GROUP BY MARKS
HAVING TOTALCOUNT > 1
In the above query first Student_Table record will be filter using WHERE Clause, then it will be grouped and again it will be filtered on the group row using HAVING.
Query Example:
Query Example:
⇛ SELECT * FROM Student_Table GROUP BY YEAR('DOB') HAVING COUNT(*) > 2
Query Example:
⇛ SELECT * FROM Student_Table GROUP BY YEAR('DOB') HAVING COUNT(*) > 2 AND COUNT(*) < 4
Which Clause is Faster in Execution WHERE OR HAVING Clause in MYSQL?
As Discussed above Where Clause will restrict the Set of record before returning table row based on the Condition. Having Clause will restrict the set of record after returning all the rows based on the Grouped row. So Obviously Where Clause is faster in Execution then Having.
No comments:
Post a Comment