Aggregations and Group Operations

Querying a PostgreSQL Database in Java

Miller Trujillo

Staff Software Engineer

Aggregations: COUNT, SUM, AVG

  • Summarize multiple rows into a single result

  • COUNT: number of rows

  • SUM: total of numeric values
  • AVG: average of numeric values
SELECT COUNT(*) AS total_books,
       AVG(publication_year) AS avg_year
FROM books;
|total_books   |avg_year |
|--------------|---------|
|14            |1999.14  |
Querying a PostgreSQL Database in Java

GROUP BY for Summarization

  • Divides rows into groups before applying aggregations
SELECT publication_year, COUNT(*) AS books_written
FROM books
GROUP BY publication_year;
| publication_year | books_written |
| ---------------- | ------------- |
| 2017             | 1             |
| 2003             | 1             |
| 1997             | 1             |
| 2018             | 3             |
| 2014             | 1             |
| 1960             | 1             |
Querying a PostgreSQL Database in Java

GROUP BY with Multiple Columns

  • Group by multiple columns for finer breakdowns
SELECT publication_year, c.name, COUNT(*) AS books_written
FROM books b
LEFT JOIN categories c on c.category_id = b.category_id 
GROUP BY publication_year, c.name;
| publication_year | name             | books_written |
| ---------------- | ---------------- | ------------- |
| 1951             | Fiction          | 1             |
| 1960             | Fiction          | 1             |
| 2018             | Computer Science | 3             |
| 1965             | Science Fiction  | 1             |
| 2010             | Fantasy          | 1             |
| 2003             | Computer Science | 1             |
Querying a PostgreSQL Database in Java

Filtering Groups with HAVING

  • WHERE filters rows before grouping
  • HAVING filters groups after aggregation
SELECT publication_year, COUNT(*) AS books_written
FROM books b
GROUP BY publication_year
HAVING COUNT(*) > 2;
| publication_year | books_written |
| ---------------- | ------------- |
| 2018             | 3             |
Querying a PostgreSQL Database in Java

Aggregations and groups in Java

String query = """SELECT publication_year, COUNT(*) AS books_written FROM books b
    GROUP BY publication_year
    HAVING COUNT(*) > ?;""";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
    pstmt.setInt(1, 2); // filter years with more than 2 books

try (ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { int year = rs.getInt("publication_year"); int count = rs.getInt("books_written"); } } }
| publication_year | books_written |
| ---------------- | ------------- |
| 2018             | 3             |
Querying a PostgreSQL Database in Java

Let's practice!

Querying a PostgreSQL Database in Java

Preparing Video For Download...