Header Ads Widget

Responsive Advertisement

SQL HAVING and ORDER BY


SQL HAVING Examples


SQL Having vs WHERE

HavingWhere
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);



SELECT COUNT(CustomerID), Country
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:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
102489051996-07-043
102498161996-07-051
102503441996-07-082

And a selection from the "Employees" table:

EmployeeIDLastNameFirstNameBirthDate
Notes
1DavolioNancy1968-12-08
Education includes a BA....
2FullerAndrew1952-02-19
Andrew received his BTS....
3LeverlingJanet1963-08-30Janet 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;


 

Post a Comment

0 Comments