count
The count() function retrieves the number of records that match a specific condition. It works with any data type supported by Redpanda SQL and returns a bigint.
|
The output will indicate the total number of rows in a table, regardless of the input types. |
Examples
This example uses an orders table that stores details of the purchase transactions:
CREATE TABLE orders (
orderid int,
custname text,
orderproduct text,
ordertotal real
);
INSERT INTO orders (orderid, custname, orderproduct, ordertotal)
VALUES
(9557411, 'Maya', 'Jeans', 10.5),
(9557421, 'Aaron', 'T-Shirt', 9.2),
(9557451, 'Alex', 'Hat', 10.8),
(9557311, 'Will', 'Hat', 8.5),
(9557321, 'Will', 'T-Shirt', 12.15),
(9557351, 'Maya', 'T-Shirt', 9.5),
(9557221, 'Maya', 'Jeans', 11.02),
(9557251, 'Alex', 'Jeans', 11.09),
(9557231, 'Aaron', 'Hat', 14.56),
(9557281, 'Aaron', 'Hat', 12.15),
(9557291, 'Will', 'T-Shirt', 13.1);
SELECT * FROM orders;
This query shows the following table:
+----------+-----------+---------------+-------------+
| orderid | custname | orderproduct | ordertotal |
+----------+-----------+---------------+-------------+
| 9557411 | Maya | Jeans | 10.5 |
| 9557421 | Aaron | T-Shirt | 9.2 |
| 9557451 | Alex | Hat | 10.8 |
| 9557311 | Will | Hat | 8.5 |
| 9557321 | Will | T-Shirt | 12.15 |
| 9557351 | Maya | T-Shirt | 9.5 |
| 9557221 | Maya | Jeans | 11.02 |
| 9557251 | Alex | Jeans | 11.09 |
| 9557231 | Aaron | Hat | 14.56 |
| 9557281 | Aaron | Hat | 12.15 |
| 9557291 | Will | T-Shirt | 13.1 |
+----------+-----------+---------------+-------------+
count() with a single expression
This example returns the number of all orders in the orders table:
SELECT COUNT(*) FROM orders;
The query returns:
+-------+
| count |
+-------+
| 11 |
+-------+
count() with a GROUP BY clause
This example will combine the count() function and the GROUP BY clause.
-
The
GROUP BYclause groups the orders based on the customer’s name. -
The
count()function counts the orders for each customer.
SELECT custname, COUNT (orderid)
FROM orders
GROUP BY custname;
The query returns:
+-----------+--------+
| custname | count |
+-----------+--------+
| Aaron | 3 |
| Alex | 2 |
| Will | 3 |
| Maya | 3 |
+-----------+--------+
count() with a HAVING clause
This example combines the count() function and the HAVING clause to apply a specific condition to find customers who have made more than two orders:
SELECT custname, COUNT (orderid)
FROM orders
GROUP BY custname
HAVING COUNT (orderid) > 2;
-
The
GROUP BYclause groups the orders based on the customer’s name. -
The
HAVINGclause will filter only customers with more than two order IDs. -
The
count()function counts the orders for each customer.
+-----------+-------+
| custname | count |
+-----------+-------+
| Aaron | 3 |
| Will | 3 |
| Maya | 3 |
+-----------+-------+