SQL HAVING Examples
SQL Having vs WHERE
| Having | Where | 
|---|---|
| In the HAVING clause it will check the condition in group of a row. | In the WHERE condition it will check or execute at each row individual. | 
| HAVING clause can only be used with aggregate function. | The WHERE Clause cannot be used with aggregate function like Having | 
| Priority Wise HAVING Clause is executed after Group By. | Priority Wise WHERE is executed before Group By. | 
The following SQL statement lists the number of customers in each country. Only include countries with more than 5 customers:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
CUSTOMER Database
Below is a selection from the "Orders" table in the Northwind sample database:
| OrderID | CustomerID | EmployeeID | OrderDate | ShipperID | 
|---|---|---|---|---|
| 10248 | 90 | 5 | 1996-07-04 | 3 | 
| 10249 | 81 | 6 | 1996-07-05 | 1 | 
| 10250 | 34 | 4 | 1996-07-08 | 2 | 
And a selection from the "Employees" table:
| EmployeeID | LastName | FirstName | BirthDate | Notes | |
|---|---|---|---|---|---|
| 1 | Davolio | Nancy | 1968-12-08 | Education includes a BA.... | |
| 2 | Fuller | Andrew | 1952-02-19 | Andrew received his BTS.... | |
| 3 | Leverling | Janet | 1963-08-30 | Janet has a BS degree.... | 
1.
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;
2.
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;



0 Comments
Please do note create link post in comment section