W3. SQL Having Flashcards
Q: What is the purpose of the SQL HAVING clause?
A: HAVING is used to filter records with aggregate functions, which WHERE cannot do.
Q: Write the syntax for using HAVING in a SQL query.
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Q: Why was the HAVING clause added to SQL?
A: Because the WHERE clause cannot be used with aggregate functions.
Q: Write a query to list countries with more than 5 customers.
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
Q: How can you sort a HAVING result set in descending order by count?
A: Use ORDER BY COUNT(column_name) DESC after HAVING.
Q: Write a query to list countries with more than 5 customers, sorted high to low.
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
Q: Write a query to list employees with more than 10 orders.
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;
Q: Write a query to check if “Davolio” or “Fuller” have registered more than 25 orders.
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;