SQL HAVING

Posted by Monir Hossain On 9:53:00 am | No comments

SQL HAVING Clause


The HAVING Clause

The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.

SQL HAVING Syntax

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;


Demo Database

In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
OrderIDCustomerIDEmployeeIDOrderDateShipperID
102489051996-07-043
102498161996-07-051
102503441996-07-082
And a selection from the "Employees" table:
EmployeeIDLastNameFirstNameBirthDatePhotoNotes
1DavolioNancy1968-12-08EmpID1.picEducation includes a BA....
2FullerAndrew1952-02-19EmpID2.picAndrew received his BTS....
3LeverlingJanet1963-08-30EmpID3.picJanet has a BS degree....


SQL HAVING Example

Now we want to find if any of the customers have a total order of less than 2000.
We use the following SQL statement:
The following SQL statement finds if any of the employees has registered more than 10 orders:

Example

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;

Try it yourself »
Now we want to find the if the employees "Davolio" or "Fuller" have more than 25 orders
We add an ordinary WHERE clause to the SQL statement:

Example

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
WHERE LastName='Davolio' OR LastName='Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;

Try it yourself »

0 comments:

Post a Comment

Blogroll

E COMMERCE

BANGLA PAPER

ENGLISH PAPER

Blogger news

About

E COMMERCE

BANGLA PAPER

ENGLISH PAPER