Querying a PostgreSQL Database in Java
Miller Trujillo
Staff Software Engineer
Summarize multiple rows into a single result
COUNT: number of rows
SUM: total of numeric valuesAVG: average of numeric valuesSELECT COUNT(*) AS total_books,
AVG(publication_year) AS avg_year
FROM books;
|total_books |avg_year |
|--------------|---------|
|14 |1999.14 |
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 |
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 |
WHERE filters rows before groupingHAVING filters groups after aggregationSELECT publication_year, COUNT(*) AS books_written
FROM books b
GROUP BY publication_year
HAVING COUNT(*) > 2;
| publication_year | books_written |
| ---------------- | ------------- |
| 2018 | 3 |
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 bookstry (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