postgresqlHow do I use the GROUP BY clause in PostgreSQL?
The GROUP BY
clause is used in PostgreSQL to group together rows of data from a table that have the same values in one or more columns. It is typically used in conjunction with the SELECT
and HAVING
clauses.
For example, to group together all the rows in the orders
table that have the same customer_id
and get the total number of orders for each customer, the following query could be used:
SELECT customer_id, COUNT(*)
FROM orders
GROUP BY customer_id;
The output of this query would be:
customer_id | count
-------------+-------
10 | 3
11 | 2
12 | 5
(3 rows)
The components of this query are:
SELECT
: This clause is used to specify the columns that will be included in the output. In this case, thecustomer_id
and thecount
of orders for each customer.FROM
: This clause is used to specify the table that will be used in the query. In this case, theorders
table.GROUP BY
: This clause is used to group together all the rows in the table that have the same values in the specified column(s). In this case, thecustomer_id
column.COUNT
: This is an aggregate function used to count the number of rows in each group.
For more information, see the PostgreSQL documentation.
More of Postgresql
- How can I set a PostgreSQL interval to zero?
- How can I troubleshoot zero damaged pages in PostgreSQL?
- How do I use PostgreSQL ZonedDateTime to store date and time information?
- How can I monitor PostgreSQL performance using Zabbix?
- How can I use PostgreSQL and ZFS snapshots together?
- How do I use PostgreSQL's ON CONFLICT DO NOTHING clause?
- How can I use PostgreSQL's "zero if null" feature?
- How do I use PostgreSQL and ZFS together?
- How can I use PostgreSQL with Zabbix?
- How do I use PostgreSQL's XMIN and XMAX features?
See more codes...