Example 1
Count total, completed, and cancelled orders in one query
PostgreSQL and SQLite append FILTER (WHERE status = 'complete') directly to COUNT(*) and SUM(amount), restricting each aggregate to matching rows only. MySQL, MariaDB, and SQL Server use CASE WHEN status = 'complete' THEN value END — when the condition is false the expression returns NULL, and COUNT and SUM both ignore NULL values, so only matching rows contribute. All five engines produce the same result: 5 total orders, 3 completed orders, and 550 in completed revenue (100 + 150 + 300).
CREATE TABLE orders (
id INT,
customer VARCHAR(50),
status VARCHAR(20),
amount INT
);
INSERT INTO
orders
VALUES
(1, 'Alice', 'complete', 100),
(2, 'Bob', 'pending', 200),
(3, 'Carol', 'complete', 150),
(4, 'Dave', 'cancelled', 50),
(5, 'Eve', 'complete', 300);SELECT
COUNT(*) AS total,
COUNT(
CASE
WHEN status = 'complete' THEN 1
END
) AS completed,
SUM(
CASE
WHEN status = 'complete' THEN amount
END
) AS completed_revenue
FROM
orders;| total | completed | completed_revenue |
|---|---|---|
| 5 | 3 | 550 |
CREATE TABLE orders (
id INT,
customer VARCHAR(50),
status VARCHAR(20),
amount INT
);
INSERT INTO
orders
VALUES
(1, 'Alice', 'complete', 100),
(2, 'Bob', 'pending', 200),
(3, 'Carol', 'complete', 150),
(4, 'Dave', 'cancelled', 50),
(5, 'Eve', 'complete', 300);SELECT
COUNT(*) AS total,
COUNT(*) FILTER (
WHERE
status = 'complete'
) AS completed,
SUM(amount) FILTER (
WHERE
status = 'complete'
) AS completed_revenue
FROM
orders;| total | completed | completed_revenue |
|---|---|---|
| 5 | 3 | 550 |
PostgreSQL and SQLite use `FILTER (WHERE ...)` appended to each aggregate. MySQL, MariaDB, and SQL Server use `CASE WHEN` inside the aggregate.