Having clause in MS SQL Server

In this article, we will be discussing having clause in MS SQL Server.

There are certain instances where the data to be extracted from the queries is done using certain conditions. To do this, having clause is used. Having clause extracts the rows based on the conditions given by the user in the query. Having clause has to be paired with the group by clause in order to extract the data. Otherwise, an error is produced.

Syntax –

select 
select_list
from
table_name
group by
group_list
having 
conditions 

Example –



Roll number Name Course
111 Riya CSE
112 Apoorva ECE
113 Mina Mech
114 Rita Biotechnology
115 Veena Chemical
116 Deepa EEE

Suppose, a user wants to extract the roll numbers of the students whose name start with R from the Student table, the query is as follows –

select roll number
from student 
having name like 'R%'

The output will display an error. This is because the group by clause has not been included in the query.
The modified query to get the desired results is as follows –

select roll number 
from student 
group by name
having name like 'r%'

The output is as follows –

Roll number Name
114 Rita
111 Riya

‘Where’ clause is generally used for extracting queries by including conditions. ‘Where’ and ‘Having’ clause, both are used for extracting data using certain conditions. Yet, ‘Having’ clause extracts data by grouping based on the group list and ‘Where’ clause extracts data directly by inserting conditions.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.