Your export says the total is 1, even when you know there are more rows. Start with the count SQL. If it looks like SELECT COUNT(*) FROM (SELECT COUNT(*) FROM ...) AS counted, the outer query is counting the one summary row the inner query produced. The number inside that row never gets read.
Run the exact count statement directly before editing it. If SQL returns the right value but PHP shows 1, check the result-reading code. mysqli_result::$num_rows counts result rows, and a count query normally has just one. Read the value in its first column instead. Below, we're dealing with the other case: the SQL total itself is wrong.
For an ungrouped detail export, you can usually use the inner count directly. With GROUP BY, though, that outer count might belong there. First decide what a row in the exported file is supposed to represent.
Download the complete SQL examples. The file includes all eight cases with expected results. Each statement contains its own synthetic fixture and runs on MySQL 8.0+ without creating tables or changing data.
We found this pattern while reviewing a real PHP export builder. It tried to replace the selected columns with COUNT(1), then wrapped the result in COUNT(*). There was another catch: the replacement expected spaces where the SQL template had line breaks.
That's an awkward bug to untangle. A failed replacement can leave you with a meaningful total. Fix the replacement so it matches, and you may suddenly get 1.
We'll use invented table names and three synthetic rows to show why. They reproduce the counting pattern, without company data. This is a code review and a worked example, rather than a report of a fix deployed to production.
Start with three rows and two orders
Here's a small fixture you can reason through without a large export file. It uses a MySQL 8.0+ common table expression, so there's no table to create:
WITH items AS (
SELECT 1 AS item_id, 10 AS order_id
UNION ALL SELECT 2, 10
UNION ALL SELECT 3, 20
)
SELECT COUNT(*) AS total
FROM items;
The result is 3. There are three item rows, belonging to two orders.
For the snippets below, keep the same WITH items AS (...) fixture and swap the final SELECT. The CTE exists for one statement only. If you'd rather run each case as-is, the download includes the fixture in every statement.
Now wrap a count inside another count:
SELECT COUNT(*) AS total
FROM (
SELECT COUNT(*) AS item_count
FROM items
) AS counted;
You get 1. Start inside the query and follow what each layer receives:
- The inner query produces one row whose
item_countvalue is 3. - The outer query receives that one row.
- The outer
COUNT(*)returns 1.
The outer query doesn't read item_count. It just counts the row containing it. Swapping COUNT(*) for COUNT(1) won't help; you'll still have the extra aggregation layer.
MySQL documents that an aggregate query without GROUP BY treats its input as one group, and that COUNT(*) counts rows. Those two rules explain this result. See the MySQL aggregate-function reference.
The empty-result test catches it immediately
Try a filter that matches nothing:
SELECT COUNT(*) AS total
FROM items
WHERE order_id = 99;
This correctly returns 0. But the nested version still returns 1:
SELECT COUNT(*) AS total
FROM (
SELECT COUNT(*) AS item_count
FROM items
WHERE order_id = 99
) AS counted;
Zero is still a value inside a row. The inner count produces that row, and the outer count happily counts it.
This is why we'd include an empty filter in the regression checks. A wrong total of 1 can look perfectly reasonable if you test with one record. It's harder to miss when the answer should be zero.
When the outer count should stay
Now suppose you want one exported row per order. There are two orders in our fixture, so the total should be 2—even though there are three item rows.
SELECT COUNT(*) AS total
FROM (
SELECT order_id
FROM items
GROUP BY order_id
) AS grouped;
Here the inner query returns two rows, one per order. The outer query counts exactly what we want.
Remove the wrapper and use SELECT COUNT(*) FROM items GROUP BY order_id, and you'll get two values: 2 and 1. If the export worker reads only the first, it could use the size of one group as the total for the job.
Keep any HAVING condition that controls which groups are exported:
SELECT COUNT(*) AS total
FROM (
SELECT order_id
FROM items
GROUP BY order_id
HAVING COUNT(*) >= 2
) AS grouped;
This returns 1, because only order 10 has at least two item rows. Dropping HAVING would count groups the export excludes.
An outer count also works for a distinct result:
SELECT COUNT(*) AS total
FROM (
SELECT DISTINCT order_id
FROM items
) AS distinct_orders;
That gives 2 as well. If your export removes duplicates across several columns, keep that same combination in the inner query. Counting distinct orders instead could give you a different answer.
These subqueries are derived tables: the outer query operates on the rows they return. MySQL's derived-table documentation explains the syntax and alias requirement.
Why a harmless formatting change can reveal the bug
Back to the PHP builder. It performed two steps in a row: replace the selected columns with a count, then wrap the SQL in another count. This is a simplified version:
$countSql = preg_replace(
'/SELECT concat([\s\S]*) FROM returns/',
'SELECT count(1) FROM returns',
$exportSql
);
$totalSql = "SELECT COUNT(*) FROM ($countSql) AS counted";
Notice the literal space after SELECT and before FROM. The template we reviewed had a newline after SELECT. In our synthetic PHP check, the multiline version made zero replacements; a matching single-line version made one.
When the replacement doesn't match, the wrapper counts rows from the original detail query. When it does match, an ungrouped inner count produces one summary row. The wrapper then counts that row and gives you 1.
So getting the regex to match is only half the job. Check the SQL it leaves behind before deciding the bug is fixed.
For diagnosing existing regex-based builders, capture the replacement count:
$countSql = preg_replace(
$pattern,
$replacement,
$exportSql,
-1,
$replacements
);
if ($countSql === null || $replacements !== 1) {
throw new RuntimeException('Count-query rewrite did not match once');
}
This catches an error or an unexpected number of replacements. It does not prove that the generated SQL counts the right thing. PHP's preg_replace documentation describes the replacement-count argument and return values.
For an export builder we're maintaining, we'd build the data and count queries explicitly from shared filters and parameters. Asking a broad regex to understand nested queries, comments, aliases, and string literals leaves plenty of room for surprises.
Choose the count that matches your export
Before touching the count, finish this sentence: ‘One exported row represents…’ Then choose the shape that counts that thing.
| One exported row represents | Count approach | Check carefully |
|---|---|---|
| One joined detail row | Direct COUNT(*) over the same joins and filters |
A one-to-many join can multiply rows |
| One order regardless of item count | Count the grouped or distinct order result | Detail-row count is a different total |
| One group meeting an aggregate condition | Count a subquery retaining GROUP BY and HAVING |
Removing HAVING changes eligibility |
| One distinct combination of fields | Count the exact distinct result | Distinct on just one field can undercount |
Use the same filters and bound values in both queries. A status, date, or existence condition that's missing from the total can make an otherwise sensible count disagree with the file. Bind input values as parameters.
For a total across all matching rows, exclude batch LIMIT and OFFSET. Keep a limit only when the product deliberately exports a capped result and the total is supposed to describe that cap. Similarly, remove ordering only when it does not affect which rows are selected.
Wrapping the original result query is a useful starting point for checking correctness. Once the numbers agree, look at the execution plan with representative data. These three-row examples tell us about the count's meaning; they don't tell us how fast your production export will run.
Verify the generated SQL and its consumer
We ran the synthetic cases on MySQL 8.4. The checks covered direct and nested counts, empty results, grouped results, HAVING, and DISTINCT.
| Case | Expected total |
|---|---|
| Three detail rows | 3 |
| Count wrapped around an ungrouped count | 1 |
| Empty detail result, direct count | 0 |
| Empty detail result, nested count | 1 |
| Two grouped orders | 2 |
| Empty grouped result | 0 |
| Groups with at least two items | 1 |
| Distinct order IDs | 2 |
Check both ends of your own count path: the SQL sent to the database and the value the worker reads back. The consumer we inspected takes the first column of the first row when a count query is supplied. For that path, the query needs to return one scalar total.
Then compare that total with the file for a small, fixed dataset. Include no matches, several items for one order, and several orders. If records can change between counting and exporting, check snapshot consistency too; a correct count query can't hold changing data still.
A query can run without error and still count the wrong thing. Compare its total with the rows your export actually contains.
If your count query fails with an ambiguous-column error instead of returning the wrong number, see our related investigation of an unqualified GROUP BY column. That article follows column ownership through a generated export query; this one focuses on the shape of the total itself.
If the total is correct but rows disappear later, follow the batch through the formatter and writer in the CSV export completeness investigation.
