SQL Having Clause

q
 
Tips>>SQL
This chapter explains how to use the built-in HAVING function in SQL.

MAKE FULL WEB APPLICATION WITH JUST SQL KNOWLEDGE? CLICK HERE

 

The SQL GROUP BY statement is used along with the SQL aggregate functions like SUM to provide means of grouping the result data set by certain database table column(s).

GROUP BY... was added to SQL because aggregate functions (like SUM) return the aggregate of all column values every time they are called, and without the GROUP BY function it was impossible to find the sum for each individual group of column values. It allows us to calculate aggregate of groups within our table.

The SQL HAVING clause is used to restrict conditionally the output of a SQL statement, by a SQL aggregate function used in your SELECT list of columns. You can't specify a fact in a SQL WHERE clause against a column in the SELECT list for which SQL aggregate function is used.

HAVING... was added to SQL because the WHERE keyword could not be used against aggregate functions (like SUM), and without HAVING... it would be impossible to test for result conditions. This clause is applied after grouping is applied. Without the HAVING keyword it would not be possible to test for function result conditions.

The syntax for the HAVING function is:

 

SELECT Column,

SUM(column) FROM

table GROUP BY Column

HAVING SUM (Column) condition value

 

EXAMPLE1:-

This "Sales" Table:-

Company Amount
Virtual Splat 5500
India Links 4500
Virtual Splat 7100

 

This SQL:

SELECT Company,

SUM (Amount) FROM

Sales GROUP BY Company

HAVING SUM (Amount) > 10,000

 

RESULT :-

COMPANY
SUM (Amount)
Virtual Splat
12,600

 

EXAMPLE 2 :-

The following is the SQL statement:-

SELECT Employee,

SUM (Hours)FROM

Employee Hours WHERE

SUM (Hours) > 24 hours GROUP BY Employee

 

The SQL HAVING clause is used to do exactly this, to specify a condition for an aggregate function which is used in your query:

SELECT Employee,

SUM (Hours)FROM

Employee Hours GROUP BY

Employee HAVING SUM (Hours) > 24

The above SQL statement will select all employees and the sum of their respective hours, as long as this sum is greater than 24. The result of the SQL HAVING clause can be seen below:

EMPLOYEES
HOURS
Michael
25
Joseph
27


If you don't find what you are looking for. Please click here to submit your query, our experts will reply soon.

 
E-mail : sales@virtualsplat.com
Phone : +91-9892413501

Whatsapp Icon +91-9967648641

Whatsapp Icon +91-9967648641

Whatsapp Icon Whatsapp Icon Facebook Google+ Linkedin Twitter