Skip to content
Related Articles

Related Articles

Having clause in MS SQL Server
  • Last Updated : 09 Jul, 2020

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 numberNameCourse
111RiyaCSE
112ApoorvaECE
113MinaMech
114RitaBiotechnology
115VeenaChemical
116DeepaEEE

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 numberName
114Rita
111Riya

‘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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :