W3. SQL Count Flashcards
Q: What does the SQL COUNT() function do?
A: It returns the number of rows that match a specified criterion.
Q: Write a query to find the total number of rows in the “Products” table.
SELECT COUNT(*) FROM Products;
Q: What is the difference between COUNT(*) and COUNT(column_name)?
A: COUNT(*) counts all rows, including NULL values, while COUNT(column_name) only counts non-NULL values in the specified column.
Q: Write a query to find the number of products where ProductName is not NULL.
SELECT COUNT(ProductName) FROM Products;
Q: How can you use the WHERE clause with COUNT()?
A: Add a condition in WHERE to specify the rows to count, e.g., WHERE Price > 20
.
Q: Write a query to count the products with a Price greater than 20.
SELECT COUNT(ProductID) FROM Products WHERE Price > 20;
Q: How do you ignore duplicates in COUNT()?
A: Use COUNT(DISTINCT column_name) to count only unique values.
Q: Write a query to count the number of different prices in the “Products” table.
SELECT COUNT(DISTINCT Price) FROM Products;
Q: How can you give the counted column a descriptive name?
A: Use the AS keyword to set an alias, e.g., AS [Number of records].
Q: Write a query to count all records in the “Products” table and label the count as “Number of records.”
SELECT COUNT(*) AS [Number of records] FROM Products;
Q: How do you use COUNT() with GROUP BY?
A: Combine COUNT() with GROUP BY to return the count for each group, e.g., GROUP BY CategoryID.
Q: Write a query to count the number of records for each category in the “Products” table.
SELECT COUNT(*) AS [Number of records], CategoryID FROM Products GROUP BY CategoryID;