COUNT() in SQL
Introduction
COUNT() is an aggregate function that answers one of the most common questions asked of a database: how many? It can count result rows, non-NULL values in a column, or distinct non-NULL values. The function appears in dashboards, reports, pagination, monitoring, quality metrics, customer analysis, software testing, and data validation.
SELECT COUNT(*) AS total_employees
FROM employees;
If the query returns 100 matching employee rows, the aggregate result is 100. Although the syntax is short, reliable counting requires a precise understanding of NULL, duplicates, filtering, grouping, joins, and the entity represented by each result row.
Basic Syntax
COUNT(expression)
The three forms used most often are:
COUNT(*)
COUNT(column_name)
COUNT(DISTINCT column_name)
They are not interchangeable descriptions of the same operation. COUNT(*) counts rows. COUNT(column_name) counts rows in which the selected expression is not NULL. COUNT(DISTINCT column_name) counts unique non-NULL values after duplicates are removed.
COUNT(*) Counts Result Rows
COUNT(*) counts every row that survives the FROM, JOIN, and WHERE stages. Individual columns may contain NULL without affecting the row count.
| employee_id | name | department |
|---|---|---|
| 1 | John | IT |
| 2 | Mary | HR |
| 3 | David | NULL |
| 4 | Lisa | IT |
SELECT COUNT(*) AS total_rows
FROM employees;
The result is 4. The third row is counted because it is still a row even though its department is missing.
COUNT(column) Counts Non-NULL Values
SELECT COUNT(department) AS known_departments
FROM employees;
The result for the example data is 3. IT, HR, and IT are counted; the NULL department is ignored. Duplicate values are not removed, so both IT values contribute to the count.
COUNT(*) Versus COUNT(column)
SELECT COUNT(*) AS total_rows,
COUNT(department) AS department_values
FROM employees;
| total_rows | department_values |
|---|---|
| 4 | 3 |
The difference is meaningful. The first value describes the employee result set; the second describes completeness of the department field. Choose the form based on the question instead of assuming they always return the same number.
COUNT(DISTINCT column)
SELECT COUNT(DISTINCT department) AS department_count
FROM employees;
For IT, HR, NULL, and IT, the result is 2. DISTINCT removes the duplicate IT value, and COUNT ignores NULL. This form answers "how many different known departments?" rather than "how many employees have a department?"
Aliases Make Results Clear
An aggregate expression should normally have a descriptive alias, especially when consumed by application code, exported to a report, or displayed in a dashboard.
SELECT COUNT(*) AS total_customers
FROM customers;
Names such as total_customers, open_defects, and failed_tests communicate business meaning better than a driver-generated expression label.
Filtering Before Counting
The WHERE clause limits rows before the aggregate runs. This makes COUNT useful for targeted metrics.
SELECT COUNT(*) AS active_employees
FROM employees
WHERE status = 'Active';
The database first identifies active employee rows and then counts them. The same pattern supports pending orders, open defects, critical incidents, completed payments, and failed tests.
Multiple Filter Conditions
SELECT COUNT(*) AS critical_open_defects
FROM defects
WHERE severity = 'Critical'
AND status = 'Open';
Both conditions must be true. When either High or Critical severity qualifies, use an IN list to state the set clearly.
SELECT COUNT(*) AS important_defects
FROM defects
WHERE severity IN ('Critical', 'High');
Counting Records in Date Ranges
Date counts should use explicit boundaries that match the business period. Today's timestamped orders can be counted with a half-open range.
SELECT COUNT(*) AS todays_orders
FROM orders
WHERE created_at >= CURRENT_DATE
AND created_at < CURRENT_DATE + INTERVAL 1 DAY;
A rolling seven-day window uses the current instant instead.
SELECT COUNT(*) AS recent_orders
FROM orders
WHERE created_at >= NOW() - INTERVAL 7 DAY;
For September 2026, fixed start and exclusive end boundaries avoid fractional-second and end-of-month errors.
WHERE created_at >= '2026-09-01'
AND created_at < '2026-10-01'
COUNT() with GROUP BY
Without GROUP BY, one COUNT expression returns one aggregate row for the whole filtered result. GROUP BY divides the rows into groups and calculates one count for each group.
SELECT department,
COUNT(*) AS employee_count
FROM employees
GROUP BY department;
If IT has three rows and HR has two, the query returns one row for IT with 3 and one row for HR with 2. A NULL department forms its own group unless it is filtered out.
Business Counts by Category
SELECT status,
COUNT(*) AS order_count
FROM orders
GROUP BY status
ORDER BY order_count DESC, status;
The same pattern counts employees by department, customers by country, defects by severity, tests by result, or API requests by status code. A secondary order makes output deterministic when groups share a count.
WHERE Versus HAVING
WHERE filters individual rows before grouping. HAVING filters aggregate groups after COUNT has been calculated.
SELECT department,
COUNT(*) AS active_employee_count
FROM employees
WHERE status = 'Active'
GROUP BY department
HAVING COUNT(*) >= 5;
This query removes inactive employees first, groups the remaining rows by department, counts each group, and retains departments with at least five active employees. An aggregate condition does not belong after WHERE because the groups do not yet exist at that stage.
Counting Unique Customers
SELECT COUNT(DISTINCT customer_id)
AS customers_with_orders
FROM orders;
If customers 101, 102, and 103 produced five order rows, COUNT(customer_id) returns 5 while COUNT(DISTINCT customer_id) returns 3. The first counts non-NULL order references; the second counts unique customers represented by those orders.
Counting NULL Values
Because COUNT(column) ignores NULL, count missing values through a WHERE predicate or subtract known values from total rows.
SELECT COUNT(*) AS missing_phone_numbers
FROM customers
WHERE phone_number IS NULL;
SELECT COUNT(*) AS total_customers,
COUNT(phone_number) AS with_phone,
COUNT(*) - COUNT(phone_number) AS without_phone
FROM customers;
The subtraction is valid because each result row either contributes one non-NULL phone value or contributes to the missing remainder. If the expression contains more complex transformations, verify what produces NULL before using the same technique.
Conditional Aggregation
Several related metrics can be calculated in one scan by combining COUNT or SUM with CASE.
SELECT COUNT(*) AS total_orders,
COUNT(CASE WHEN status = 'Pending' THEN 1 END)
AS pending_orders,
COUNT(CASE WHEN status = 'Completed' THEN 1 END)
AS completed_orders,
COUNT(CASE WHEN status = 'Cancelled' THEN 1 END)
AS cancelled_orders
FROM orders;
Rows that do not match a CASE branch produce NULL, and COUNT ignores those NULL results. This is a concise way to produce dashboard columns without issuing separate queries.
Conditional COUNT Versus SUM
SUM(CASE WHEN status = 'Pending' THEN 1 ELSE 0 END)
This SUM expression and COUNT(CASE WHEN ... THEN 1 END) commonly produce the same conditional count. The COUNT form relies on NULL for nonmatching rows; the SUM form adds explicit ones and zeros. Choose one consistent project convention and test behavior when the entire input set is empty, because aggregate NULL behavior can differ.
Test Execution Summary
SELECT COUNT(*) AS total_tests,
COUNT(CASE WHEN status = 'PASSED' THEN 1 END) AS passed,
COUNT(CASE WHEN status = 'FAILED' THEN 1 END) AS failed,
COUNT(CASE WHEN status = 'SKIPPED' THEN 1 END) AS skipped
FROM test_execution
WHERE executed_at >= :run_start
AND executed_at < :run_end;
The time range ensures the summary belongs to one run or reporting period. Without it, historical executions may inflate every status count.
Calculating a Percentage Safely
SELECT COUNT(*) AS total_tests,
COUNT(CASE WHEN status = 'PASSED' THEN 1 END)
AS passed_tests,
100.0 * COUNT(CASE WHEN status = 'PASSED' THEN 1 END)
/ NULLIF(COUNT(*), 0) AS pass_percentage
FROM test_execution
WHERE run_id = :run_id;
NULLIF(COUNT(*), 0) prevents division by zero when no tests exist. Multiplication by 100.0 encourages decimal arithmetic rather than integer truncation. Decide whether an empty run should display NULL, zero, or "not applicable" in the presentation layer.
Counts Per Customer and Thresholds
SELECT customer_id,
COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 10
ORDER BY order_count DESC, customer_id;
This identifies customers with more than ten orders. If cancelled orders should not count, filter them in WHERE before grouping. The metric definition must specify which lifecycle states represent a valid order.
Counts by Day, Month, and Year
SELECT DATE(created_at) AS order_date,
COUNT(*) AS order_count
FROM orders
WHERE created_at >= :report_start
AND created_at < :report_end
GROUP BY DATE(created_at)
ORDER BY order_date;
The WHERE clause narrows the indexed range, while DATE creates daily buckets for the selected rows. Monthly reports should include the year in the key so January from multiple years is not merged.
SELECT DATE_FORMAT(order_date, '%Y-%m') AS order_month,
COUNT(*) AS total_orders
FROM orders
GROUP BY DATE_FORMAT(order_date, '%Y-%m')
ORDER BY order_month;
COUNT() with an INNER JOIN
A join changes the rows being counted. This query counts matching order-item rows by product.
SELECT p.product_id,
p.product_name,
COUNT(i.order_item_id) AS order_line_count
FROM products p
JOIN order_items i
ON i.product_id = p.product_id
GROUP BY p.product_id, p.product_name;
The result measures order lines, not necessarily unique orders or units sold. To count units, use SUM(i.quantity). To count distinct orders containing the product, use COUNT(DISTINCT i.order_id).
COUNT() with a LEFT JOIN
SELECT c.customer_id,
c.customer_name,
COUNT(o.order_id) AS order_count
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.customer_name;
A LEFT JOIN preserves every customer. When no order matches, the right-side order columns are NULL. Counting the non-NULL right-side primary key therefore returns zero for customers with no orders.
Why COUNT(*) Can Mislead After LEFT JOIN
If the previous query used COUNT(*), an unmatched customer would still have one preserved output row and could receive a count of 1. That would describe joined result rows rather than matching orders. Count a non-NULL column from the optional side when the metric means matched child records.
One-to-Many Joins Multiply Rows
Suppose one order has five order items. Joining orders to items produces five joined rows for that order.
SELECT COUNT(*)
FROM orders o
JOIN order_items i
ON i.order_id = o.order_id;
This counts joined item rows, not unique orders. If the question asks how many orders contain at least one item, count distinct order identifiers.
SELECT COUNT(DISTINCT o.order_id) AS unique_orders
FROM orders o
JOIN order_items i
ON i.order_id = o.order_id;
Always identify the grain of the result set: one row per customer, order, item, payment, event, or joined combination.
COUNT() Versus SUM, AVG, MIN, and MAX
| Function | Question answered | Example |
|---|---|---|
COUNT() | How many rows or values? | Number of orders |
SUM() | What is the numeric total? | Total revenue |
AVG() | What is the average? | Average order amount |
MIN() | What is the smallest value? | Earliest order date |
MAX() | What is the largest value? | Largest order amount |
COUNT never adds the values stored in a numeric column. A quantity row with value 5 contributes one to COUNT(quantity) but contributes five to SUM(quantity).
Counting Results from a Subquery
SELECT COUNT(*) AS high_value_customers
FROM (
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING SUM(total_amount) > 10000
) AS qualifying_customers;
The inner query produces one row per qualifying customer. The outer COUNT measures those rows. This pattern is useful when the entity to count emerges only after grouping, ranking, or deduplication.
COUNT() Versus EXISTS
If the requirement is only to know whether at least one row exists, EXISTS communicates the intent more directly.
SELECT EXISTS (
SELECT 1
FROM orders
WHERE customer_id = 101
) AS has_orders;
COUNT answers how many; EXISTS answers whether any exist. A database can often stop an EXISTS search after the first match, while an exact count must establish the complete result.
Empty Sets and NULL-Only Columns
SELECT COUNT(*)
FROM employees
WHERE department = 'UnknownDepartment';
When no rows match, COUNT returns 0 in one aggregate row. If three matching rows all contain NULL in bonus, COUNT(bonus) returns 0 while COUNT(*) returns 3. This differs from aggregates such as SUM, which commonly return NULL for an empty input.
Real-World Defect Dashboard
SELECT COUNT(*) AS total_defects,
COUNT(CASE WHEN status = 'Open' THEN 1 END)
AS open_defects,
COUNT(CASE WHEN severity = 'Critical' THEN 1 END)
AS critical_defects,
COUNT(CASE WHEN status = 'Closed' THEN 1 END)
AS closed_defects
FROM defects
WHERE project_id = :project_id;
Several metrics are calculated under one project filter. Clarify whether a critical closed defect belongs in both critical and closed counts; conditional metrics can overlap unless categories are designed to be mutually exclusive.
API Monitoring Counts
SELECT status_code,
COUNT(*) AS request_count
FROM api_logs
WHERE request_time >= NOW() - INTERVAL 1 HOUR
GROUP BY status_code
ORDER BY request_count DESC, status_code;
This supports traffic and error monitoring. A separate query can count unique active users with COUNT(DISTINCT user_id). Anonymous requests with NULL user IDs are excluded from that distinct count and may need their own metric.
E-Commerce Counts
SELECT status,
COUNT(*) AS order_count
FROM orders
WHERE created_at >= CURRENT_DATE
AND created_at < CURRENT_DATE + INTERVAL 1 DAY
GROUP BY status;
The query shows today's orders by status in the database session time zone. A global business should convert its local-day boundaries to the storage zone before counting, especially around midnight and daylight-saving transitions.
Data-Quality Metrics
SELECT COUNT(*) AS total_rows,
COUNT(*) - COUNT(email) AS missing_email,
COUNT(*) - COUNT(phone) AS missing_phone,
COUNT(*) - COUNT(address) AS missing_address
FROM customers;
These counts show field completeness but not validity. A non-NULL email may still be malformed or duplicated. Combine completeness metrics with validation predicates and trend them over consistent data snapshots.
COUNT(*) Versus COUNT(1)
Modern relational databases generally optimize both COUNT(*) and COUNT(1) as row counts. The literal 1 is non-NULL for every row, so the result normally matches. COUNT(*) is clearer because SQL defines it specifically to count rows and it does not suggest that a particular expression matters.
COUNT(primary_key)
When a primary key is guaranteed NOT NULL, COUNT(employee_id) normally equals COUNT(*) on the same single table. Their semantics still differ: the first counts non-NULL key values, while the second counts rows. Prefer COUNT(*) for row-count intent and use a right-side key deliberately when counting matches from an outer join.
COUNT() Performance
An exact count over a huge table may need to examine many index entries or visible rows. Performance depends on the DBMS, storage engine, indexes, WHERE conditions, partitioning, transaction visibility, statistics, and execution plan. Do not assume that metadata always contains an exact instantly available row count.
Filter on indexed columns, avoid unnecessary joins, and inspect EXPLAIN. If a dashboard requests expensive global counts repeatedly, consider a governed summary table, incremental metric, cache, or analytical store. Such alternatives introduce freshness and consistency tradeoffs that must be visible to users.
Exact Versus Approximate Counts
Administrative interfaces sometimes need only an estimate, while invoices, compliance reports, and pagination totals may require exact values. Catalog statistics can provide fast approximations but may be stale. Label estimates clearly and never substitute them where business correctness requires an exact transactional count.
Counting Distinct Combinations
Sometimes uniqueness is defined by more than one column. A business may ask for the number of unique customer-product pairs, user-date combinations, or country-city combinations. Database support for multi-expression COUNT(DISTINCT ...) varies, so a grouped subquery is a clear portable design.
SELECT COUNT(*) AS unique_customer_product_pairs
FROM (
SELECT customer_id, product_id
FROM order_items
GROUP BY customer_id, product_id
) AS unique_pairs;
The inner query establishes one row per combination; the outer query counts those entities. Avoid concatenating values into one string because separators, NULL handling, collation, and accidental collisions can make different combinations appear equal.
Windowed COUNT()
Aggregate COUNT normally reduces many rows to one row per group. A window function calculates a count while preserving the detail rows.
SELECT order_id,
customer_id,
created_at,
COUNT(*) OVER (
PARTITION BY customer_id
) AS customer_order_count
FROM orders;
Every order remains visible, and each row receives the total number of orders for its customer. This supports detail reports that need both row-level information and group context without joining a separate aggregate query back to the source.
Running Counts
SELECT order_id,
created_at,
COUNT(*) OVER (
ORDER BY created_at, order_id
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW
) AS running_order_count
FROM orders;
The explicit ROWS frame makes the running behavior clear, and the unique order identifier produces deterministic sequencing when timestamps tie. Running counts are useful for cumulative activity reports, sequence validation, and progressive totals.
COUNT() for Pagination
Paginated interfaces often run one query for the current page and another exact count for the total number of matching rows.
SELECT COUNT(*) AS total_matches
FROM orders
WHERE status = :status
AND created_at >= :start_time
AND created_at < :end_time;
The count query must apply the same filters and authorization rules as the page query. If the two statements run under different snapshots while writes continue, the total and displayed rows can differ. That may be acceptable for a live interface, but transactional reports may need one consistent snapshot. For very large search results, consider whether users need an exact total or whether "more results" navigation is sufficient.
Counting After UNION and UNION ALL
UNION removes duplicate result rows, while UNION ALL preserves them. Therefore, the operator directly changes an outer count.
SELECT COUNT(*) AS combined_events
FROM (
SELECT event_id FROM current_events
UNION ALL
SELECT event_id FROM archived_events
) AS all_events;
This counts every row from both sources. Replacing UNION ALL with UNION counts distinct complete result rows after duplicate removal. If the same event can appear in both tables and should be one entity, deduplicate by a governed key and investigate why lifecycle overlap occurs.
Portable Conditional Aggregation
CASE expressions work across major relational databases. PostgreSQL and some other systems also support the SQL FILTER clause, which can make intent concise.
SELECT COUNT(*) AS total_orders,
COUNT(*) FILTER (WHERE status = 'Pending')
AS pending_orders,
COUNT(*) FILTER (WHERE status = 'Completed')
AS completed_orders
FROM orders;
Use syntax supported by the target DBMS. The underlying rule remains the same: define the shared input set once and apply explicit conditions to each metric.
Transaction Visibility and Counts
An exact count reflects rows visible to the transaction under its isolation level, not necessarily every row physically present in storage. Concurrent inserts, deletes, and uncommitted changes can cause two sessions to observe different counts at the same wall-clock time.
This is normal transactional behavior. A report that must reconcile to another system should identify its snapshot or cutoff, while a live dashboard may intentionally show the most recently committed state available to each query.
Soft Deletes and Lifecycle Rules
Many applications retain deleted rows and mark them with deleted_at or a status. A raw table count then includes records that users consider deleted.
SELECT COUNT(*) AS visible_customers
FROM customers
WHERE deleted_at IS NULL;
Centralize this rule in a governed view or repository layer when every user-facing query should exclude soft-deleted records. Security, tenant, archival, and lifecycle filters must be applied consistently to avoid counts that disagree across pages.
Tenant-Aware Counts
SELECT COUNT(*) AS tenant_orders
FROM orders
WHERE tenant_id = :tenant_id
AND created_at >= :start_time
AND created_at < :end_time;
In multi-tenant applications, forgetting the tenant predicate is both a correctness defect and a potential information disclosure. Indexes commonly begin with the tenant identifier when most access is tenant-scoped, but actual index order should be validated against workload and selectivity.
Counting Relationships Correctly
A query joining customers to orders and then orders to payments can multiply one order when multiple payments exist. Counting orders after that join requires either pre-aggregating the payment side or counting distinct order identifiers.
SELECT c.customer_id,
COUNT(DISTINCT o.order_id) AS paid_order_count
FROM customers c
JOIN orders o
ON o.customer_id = c.customer_id
JOIN payments p
ON p.order_id = o.order_id
AND p.status = 'SETTLED'
GROUP BY c.customer_id;
Even DISTINCT must match the real entity. If one order can be partly settled and partly refunded, "paid order" needs a state rule that may require payment aggregation before counting.
Maintaining Summary Counts
High-traffic systems sometimes store counters such as comment count, unread notification count, or daily order count. Reading a counter is faster than aggregating a large detail table, but every write path must maintain it correctly. Retries, failed transactions, bulk imports, and manual corrections can create drift.
Use atomic updates or transactional event processing, make updates idempotent, and run periodic reconciliation against the source rows. Treat the detail records as the authority unless the architecture explicitly establishes another source of truth.
Counting with Views and Security Filters
A view may hide rows, join tables, or derive categories. COUNT(*) over a view counts the view's result rows, which may differ from the base table count. Row-level security can further change results according to the current user.
Document the counting layer in reports. "Total orders" from a security-filtered operational view may legitimately differ from an administrator's base-table total or a warehouse total loaded at an earlier time.
Cross-Database Portability
The core forms COUNT(*), COUNT(expression), and COUNT(DISTINCT expression) are broadly portable. Differences appear around multiple DISTINCT expressions, FILTER syntax, window features, execution plans, metadata estimates, and return types.
When moving a reporting query between systems, test NULL behavior, case and collation rules for distinct text values, integer type capacity, join plans, and snapshot semantics. A syntactically valid migration can still produce a different count when collation treats values as equal in one database but distinct in another.
Common Mistakes
- Using
COUNT(column)when the requirement is total rows and the column can be NULL. - Assuming
COUNT(*)ignores rows containing NULL values. - Assuming
COUNT(column)removes duplicates automatically. - Forgetting DISTINCT when counting unique entities.
- Putting an aggregate condition in WHERE instead of HAVING.
- Using
COUNT(*)to count optional children after a LEFT JOIN. - Ignoring row multiplication from one-to-many or many-to-many joins.
- Counting order lines when the requirement asks for units or unique orders.
- Issuing many separate conditional count queries for one dashboard.
- Using COUNT when EXISTS is sufficient.
- Dividing by a zero count when calculating percentages.
- Assuming an exact count over a very large table is always instant.
Testing COUNT Queries
Test with an empty table, one row, duplicate values, NULL values, all-NULL columns, and mixed categories. For joins, include parents with zero, one, and several children. Include multiple child tables to expose accidental multiplication. For conditional counts, verify whether categories overlap and whether the sum is expected to equal the total.
For time-based counts, test both range boundaries, fractional seconds, month changes, time zones, and daylight-saving transitions. For percentages, test zero input and integer-division behavior. Compare query results with a small hand-counted dataset before testing production scale.
Practical Checklist
- Define the entity being counted.
- Use
COUNT(*)for rows. - Use
COUNT(column)for non-NULL values. - Use
COUNT(DISTINCT column)for unique non-NULL values. - Apply row conditions in WHERE before aggregation.
- Use GROUP BY for one count per category.
- Apply aggregate thresholds in HAVING.
- Count a right-side non-NULL key after a LEFT JOIN.
- Check join grain before trusting any count.
- Use conditional aggregation for related dashboard metrics.
- Protect percentage calculations from zero denominators.
- Validate plans and freshness requirements for large datasets.
Interview Questions and Answers
What is COUNT()? It is an aggregate function that returns the number of rows or non-NULL expression values in a result set.
What is the difference between COUNT(*) and COUNT(column)? COUNT(*) counts rows; COUNT(column) counts only rows where the expression is not NULL.
Does COUNT count NULL? COUNT(*) counts the row regardless of column NULLs. COUNT(column) and COUNT(DISTINCT column) ignore NULL results.
How do you count unique values? Use COUNT(DISTINCT column_name).
How do you count NULL values? Filter with WHERE column IS NULL, or subtract COUNT(column) from COUNT(*).
WHERE versus HAVING? WHERE filters rows before grouping; HAVING filters groups after aggregate values are calculated.
Why count the child key after a LEFT JOIN? Unmatched children have NULL keys, so the count is zero while the parent remains in the result.
COUNT versus EXISTS? COUNT determines how many matches exist; EXISTS determines whether at least one exists.
COUNT(*) versus COUNT(1)? They normally produce the same row count, but COUNT(*) communicates row-count intent more clearly.
Mental Model
Suppose the department values are IT, IT, HR, NULL, Finance, and NULL. Then COUNT(*) returns 6 rows. COUNT(department) returns 4 non-NULL values. COUNT(DISTINCT department) returns 3 unique non-NULL values: IT, HR, and Finance.
| Expression | Question | Result |
|---|---|---|
COUNT(*) | How many rows? | 6 |
COUNT(department) | How many known department values? | 4 |
COUNT(DISTINCT department) | How many different known departments? | 3 |
Key Takeaway
COUNT() answers "how many," but the exact answer depends on what is being counted. Rows, present values, unique entities, grouped categories, and joined child records are different metrics.
COUNT(*)
-> rows
COUNT(column)
-> non-NULL values
COUNT(DISTINCT column)
-> unique non-NULL values
Filter rows with WHERE, form categories with GROUP BY, filter aggregate groups with HAVING, and use CASE for conditional metrics. Most importantly, inspect join grain and NULL behavior before trusting a count. Those habits make COUNT queries accurate for reports, dashboards, testing metrics, monitoring, and business decisions.