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.
select select_list from table_name group by group_list having conditions
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 –
‘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.