Open In App

Having clause in MS SQL Server

Last Updated : 09 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads