W3. SQL Having Flashcards

1
Q

Q: What is the purpose of the SQL HAVING clause?

A

A: HAVING is used to filter records with aggregate functions, which WHERE cannot do.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Q: Write the syntax for using HAVING in a SQL query.

A

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Q: Why was the HAVING clause added to SQL?

A

A: Because the WHERE clause cannot be used with aggregate functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Q: Write a query to list countries with more than 5 customers.

A

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Q: How can you sort a HAVING result set in descending order by count?

A

A: Use ORDER BY COUNT(column_name) DESC after HAVING.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Q: Write a query to list countries with more than 5 customers, sorted high to low.

A

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Q: Write a query to list employees with more than 10 orders.

A

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;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Q: Write a query to check if “Davolio” or “Fuller” have registered more than 25 orders.

A

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;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly