DEV Community

AISSAM ASSOUIK
AISSAM ASSOUIK

Posted on

Building Medium-Complexity Analytics Queries in Java with Querier and PostgreSQL

Building Medium-Complexity Analytics Queries in Java with Querier and PostgreSQL

When building reporting and analytics features in Java applications, SQL queries can quickly become difficult to maintain.

A typical analytics query might involve multiple JOINs, Common Table Expressions (CTEs), aggregate functions, conditional filtering, date manipulation, and database-specific functions.

You could write all of this as a native SQL string. But what if you could build most of it using Java method references and a fluent API, without losing access to PostgreSQL's native functionality?

That's what we'll explore using Querier, an open-source, type-safe Java SQL query builder.

In this tutorial, we'll use Querier to build customer purchase analytics using:

  • Type-safe JOINs between customers, orders, and products.
  • PostgreSQL functions such as COALESCE, STRING_AGG, DATE_PART, DATE_TRUNC, and TO_CHAR.
  • Aggregations such as SUM, COUNT, and AVG.
  • CTEs to structure and reuse complex query logic.
  • Filtering aggregated results using HAVING and outer query conditions.
  • Grouping by database functions and custom SQL expressions.

The goal is not to hide SQL from developers. It's to make complex SQL easier to construct, read, and maintain in Java.

1. Add Querier to your project

We'll use querier-core, which contains the query builder, aggregation support, CTEs, JOINs, and database-specific functions.

Add the following Maven dependency:

<dependency>
    <groupId>com.aytmatech</groupId>
    <artifactId>querier-core</artifactId>
    <version>QUERIER_VERSION</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Querier requires Java 17 or higher.

Repository: https://github.com/AytmaTech/Querier

2. Our data model

We'll reuse four simple Java classes representing a basic e-commerce application:

  • Customer: customer information.
  • Product: product information.
  • Order: customer purchases and order information.
  • OrderStatus: the current order status.

The relationships are straightforward:

Customer (1) -------- (N) Order
Product  (1) -------- (N) Order
Enter fullscreen mode Exit fullscreen mode

Each order references one customer and one product through customerId and productId.

Our entities use standard JPA annotations, which Querier supports.

The important fields for this tutorial are:

// Customer
private Long id;
private String name;
private String email;

// Product
private Long id;
private String name;
private BigDecimal price;

// Order
private Long id;
private Long customerId;
private Long productId;
private BigDecimal total;
private OrderStatus status;
private LocalDate createdAt;
Enter fullscreen mode Exit fullscreen mode

The order status enum:

public enum OrderStatus {
    PENDING,
    PAID,
    SHIPPED,
    DELIVERED,
    CANCELLED
}
Enter fullscreen mode Exit fullscreen mode

The complete entity definitions can be found in the example project.

Also, keep your JPA access strategy consistent. Prefer placing @Id and @Column annotations on the same access style, or explicitly declare @Access, rather than mixing field and property access unintentionally.

3. What are we building?

Let's define a realistic business requirement.

We want to generate a customer purchasing report containing:

Metric Description
Customer Customer identifier and name
Email Customer email, with a fallback value
Order count Number of qualifying orders
Total revenue Total amount spent by the customer
Average order value Average value of their orders
Purchased products Product names aggregated into a single string

We'll apply the following business rules:

  1. Consider orders created from January 1, 2025.
  2. Only include PAID, SHIPPED, and DELIVERED orders.
  3. Exclude customers with fewer than three qualifying orders.
  4. Return only customers with more than 5,000 in total revenue.
  5. Sort customers by total revenue in descending order.
  6. Limit the report to the top 20 customers.

This is a good example of a medium-complexity analytics query because it combines data from multiple tables, performs calculations, and applies business rules at different stages of query execution.

4. Understanding PostgreSQL functions in Querier

Before building the main query, let's look at how Querier handles database-specific functions.

Querier provides vendor-specific function factories. For PostgreSQL, we have:

import com.aytmatech.querier.vendor.PgDialectFunctions;
Enter fullscreen mode Exit fullscreen mode

These factory methods return DbFunction instances, which can be used in SELECT lists, WHERE conditions, ORDER BY clauses, GROUP BY clauses, and window function expressions.

For example, PostgreSQL's COALESCE function:

PgDialectFunctions.coalesce(
    Customer::getEmail,
    "Not provided"
).as("customer_email")
Enter fullscreen mode Exit fullscreen mode

Generates an expression equivalent to:

COALESCE(customers.email, 'Not provided') AS customer_email
Enter fullscreen mode Exit fullscreen mode

Notice that we're still using a method reference to identify the Java property.

The fallback value is handled as a bound parameter rather than being manually concatenated into SQL.

Here are some other useful PostgreSQL functions available in PgDialectFunctions:

Category Querier method PostgreSQL function
Date dateTrunc() DATE_TRUNC()
Date datePart() DATE_PART()
Date extract() EXTRACT()
Date toChar() TO_CHAR()
Date age() AGE()
String upper() UPPER()
String lower() LOWER()
String concatWs() CONCAT_WS()
String stringAgg() STRING_AGG()
String stringAggOrdered() Ordered STRING_AGG()
Array arrayAgg() ARRAY_AGG()
JSON jsonbExtractPathText() jsonb_extract_path_text()
Conditional coalesce() COALESCE()
Conditional nullif() NULLIF()
Math round() ROUND()

The complete list is available in the PgDialectFunctions source code.

The important thing is that we're not limited to standard SQL functions. We can use PostgreSQL capabilities directly while keeping the rest of the query structured through Querier.

5. Building the analytics CTE

Let's start with the actual query.

Instead of putting all the logic into one large SELECT, we'll create a CTE named customer_metrics.

The CTE will:

  • Join orders with customers.
  • Join orders with products.
  • Filter eligible orders.
  • Calculate customer-level metrics.
  • Aggregate purchased product names.
  • Filter customers using HAVING.

First, the imports:

import com.aytmatech.querier.*;
import com.aytmatech.querier.vendor.PgDialectFunctions;

import java.math.BigDecimal;
import java.time.LocalDate;
Enter fullscreen mode Exit fullscreen mode

Now, let's build the CTE:

Select customerMetrics = Select.builder()

    // Customer information
    .select(Customer::getId)
    .select(Customer::getName)

    // PostgreSQL COALESCE
    .select(
        PgDialectFunctions.coalesce(
            Customer::getEmail,
            "Not provided"
        ).as("customer_email")
    )

    // Standard SQL aggregations
    .select(Aggregate.countAll().as("order_count"))
    .select(Aggregate.sum(Order::getTotal).as("total_revenue"))
    .select(Aggregate.avg(Order::getTotal).as("average_order_value"))

    // PostgreSQL ordered STRING_AGG
    .select(
            PgDialectFunctions.stringAgg(
                    Product::getName,
                    ", "
            ).as("purchased_products")
    )

    // Main table
    .from(Order.class)

    // JOIN customers
    .join(
        Customer.class,
        Condition.eq(
            Order::getCustomerId,
            Customer::getId
        )
    )

    // JOIN products
    .join(
        Product.class,
        Condition.eq(
            Order::getProductId,
            Product::getId
        )
    )

    // Business filters
    .where(
        Condition.and(

            Condition.gte(
                Order::getCreatedAt,
                LocalDate.of(2025, 1, 1)
            ),

            Condition.or(
                Condition.eq(Order::getStatus, OrderStatus.PAID.name()),
                Condition.eq(Order::getStatus, OrderStatus.SHIPPED.name()),
                Condition.eq(Order::getStatus, OrderStatus.DELIVERED.name())
            )
        )
    )

    // Group customer information
    .groupBy(
        Customer::getId,
        Customer::getName,
        Customer::getEmail
    )

    // Only customers with more than two qualifying orders
    .having(
        Condition.gt(
            Aggregate.countAll(),
            2
        )
    )

    .build();
Enter fullscreen mode Exit fullscreen mode

Let's break down some of the important parts.

JOINs using method references

The first JOIN:

.join(
    Customer.class,
    Condition.eq(
        Order::getCustomerId,
        Customer::getId
    )
)
Enter fullscreen mode Exit fullscreen mode

Produces:

INNER JOIN customers
    ON orders.customer_id = customers.id
Enter fullscreen mode Exit fullscreen mode

The second JOIN follows the same approach:

.join(
    Product.class,
    Condition.eq(
        Order::getProductId,
        Product::getId
    )
)
Enter fullscreen mode Exit fullscreen mode

Produces:

INNER JOIN products
    ON orders.product_id = products.id
Enter fullscreen mode Exit fullscreen mode

We don't need to manually specify the table or column names. Querier resolves them from our entity classes and method references.

Aggregations

The three standard aggregates are straightforward:

Aggregate.countAll()
Aggregate.sum(Order::getTotal)
Aggregate.avg(Order::getTotal)
Enter fullscreen mode Exit fullscreen mode

They produce:

COUNT(*)
SUM(orders.total)
AVG(orders.total)
Enter fullscreen mode Exit fullscreen mode

We use aliases to make the resulting columns easier to reference:

COUNT(*) AS order_count,
SUM(orders.total) AS total_revenue,
AVG(orders.total) AS average_order_value
Enter fullscreen mode Exit fullscreen mode

PostgreSQL COALESCE

Customers might not have an email address.

Instead of handling null values in Java after executing the query, we can handle them directly in PostgreSQL:

PgDialectFunctions.coalesce(
    Customer::getEmail,
    "Not provided"
).as("customer_email")
Enter fullscreen mode Exit fullscreen mode

This gives us a consistent value in the resulting dataset.

PostgreSQL STRING_AGG

One particularly useful function for analytics is STRING_AGG.

It allows us to aggregate multiple string values into a single result.

In our example:

.select(
        PgDialectFunctions.stringAgg(
                Product::getName,
                ", "
        ).as("purchased_products")
)
Enter fullscreen mode Exit fullscreen mode

Produces an expression equivalent to:

STRING_AGG(
     products.name, 
     ', '
) AS purchased_products
Enter fullscreen mode Exit fullscreen mode

For example, instead of receiving multiple rows:

Customer 1 | Laptop
Customer 1 | Keyboard
Customer 1 | Monitor
Enter fullscreen mode Exit fullscreen mode

We can receive:

Customer 1 | Laptop, Keyboard, Monitor
Enter fullscreen mode Exit fullscreen mode

The last argument controls the ordering: true means ascending and false means descending.

This is especially useful for generating reporting datasets where a single row needs to contain a readable collection of associated values.

In this simplified model, a product name may appear multiple times if the customer orders that product more than once. We are deliberately preserving those purchase occurrences.

WHERE vs HAVING

There is an important difference between these two clauses.

WHERE filters individual rows before aggregation.

HAVING filters the resulting groups after aggregation.

Our query uses:

.where(
    Condition.and(
        Condition.gte(
            Order::getCreatedAt,
            LocalDate.of(2025, 1, 1)
        ),
        ...
    )
)
Enter fullscreen mode Exit fullscreen mode

This filters the source orders before calculating customer metrics.

Later, we use:

.having(
    Condition.gt(
        Aggregate.countAll(),
        2
    )
)
Enter fullscreen mode Exit fullscreen mode

This removes customer groups having fewer than three qualifying orders.

Keeping these two responsibilities separate makes analytics queries easier to reason about.

6. Combining the CTE with the final query

Now that we have our customer metrics, we can build the final report.

We'll reference the CTE using with() and Expression.tableRef().

Select analyticsReport = Select.builder()

    // Register the CTE
    .with("customer_metrics", customerMetrics)

    // Select the calculated metrics
    .select(
        Expression.raw("customer_metrics.id AS customer_id")
    )
    .select(
        Expression.raw("customer_metrics.name")
    )
    .select(
        Expression.raw("customer_metrics.customer_email")
    )
    .select(
        Expression.raw("customer_metrics.order_count")
    )
    .select(
        Expression.raw("customer_metrics.total_revenue")
    )
    .select(
        Expression.raw("customer_metrics.average_order_value")
    )
    .select(
        Expression.raw("customer_metrics.purchased_products")
    )

    // Read from the CTE
    .from(
        Expression.tableRef("customer_metrics")
    )

    // Filter the aggregated result
    .where(
        Condition.gt(
            Expression.raw("customer_metrics.total_revenue"),
            new BigDecimal("5000")
        )
    )

    // Highest revenue first
    .orderBy(
        OrderBy.desc("customer_metrics.total_revenue")
    )

    // Top 20 customers
    .limit(20)

    .build();
Enter fullscreen mode Exit fullscreen mode

Why use Expression.raw() here?

The CTE is not mapped to one of our Java entity classes. Its columns are calculated and exposed through the CTE definition.

We therefore reference its output columns by their SQL aliases.

This is a useful distinction: we retain method-reference type safety when working with our mapped tables, while using explicit expressions at the boundary of a CTE.

The raw expressions above are application-controlled SQL identifiers, not user-provided input.

7. What SQL are we building?

The resulting query has the following structure:

WITH customer_metrics AS (

    SELECT
        customers.id,
        customers.name,

        COALESCE(
            customers.email,
            'Not provided'
        ) AS customer_email,

        COUNT(*) AS order_count,

        SUM(orders.total) AS total_revenue,

        AVG(orders.total) AS average_order_value,

        STRING_AGG(
            products.name, 
            ', '
        ) AS purchased_products

    FROM orders

    INNER JOIN customers
        ON orders.customer_id = customers.id

    INNER JOIN products
        ON orders.product_id = products.id

    WHERE
        orders.created_at >= '2025-01-01'
        AND (
            orders.status = 'PAID'
            OR orders.status = 'SHIPPED'
            OR orders.status = 'DELIVERED'
        )

    GROUP BY
        customers.id,
        customers.name,
        customers.email

    HAVING COUNT(*) > 2
)

SELECT
    customer_metrics.id AS customer_id,
    customer_metrics.name,
    customer_metrics.customer_email,
    customer_metrics.order_count,
    customer_metrics.total_revenue,
    customer_metrics.average_order_value,
    customer_metrics.purchased_products

FROM customer_metrics

WHERE customer_metrics.total_revenue > 5000

ORDER BY customer_metrics.total_revenue DESC

LIMIT 20;
Enter fullscreen mode Exit fullscreen mode

This is the SQL equivalent of the business requirement we defined earlier.

The important point is that we constructed it using Java method references, builder methods, aggregate expressions, and PostgreSQL function factories.

Also, the SQL above is formatted for readability. Querier generates bound parameter placeholders for dynamic values rather than embedding them directly as shown here.

8. Executing the query

Querier deliberately separates query construction from database execution.

This means we can execute the same query through different Java database integration technologies.

For example, with Spring's NamedParameterJdbcTemplate:

Select.SqlAndParams sqlAndParams =
    analyticsReport.toSqlAndParams();

List<Map<String, Object>> results =
    namedParameterJdbcTemplate.queryForList(
        sqlAndParams.sql(),
        sqlAndParams.params()
    );
Enter fullscreen mode Exit fullscreen mode

We can also generate positional SQL:

Select.PositionalSqlAndParams sqlAndParams =
    analyticsReport.toPositionalSql();

List<Map<String, Object>> results =
    jdbcTemplate.queryForList(
        sqlAndParams.sql(),
        sqlAndParams.params().toArray()
    );
Enter fullscreen mode Exit fullscreen mode

Querier supports:

Method Placeholder style Typical integration
toSqlAndParams() :paramName Spring NamedParameterJdbcTemplate
toPositionalSql() ? JDBC / Spring JdbcTemplate
toIndexedSql() $1, $2 PostgreSQL drivers / Vert.x
toPlainSql() Inline values Debugging only

For actual execution, always use the parameterized output. toPlainSql() is intended for logging and debugging, not execution.

9. Another example: Sales analytics with PostgreSQL date functions

Let's explore another useful analytics scenario.

Suppose we want sales statistics containing:

  • Sales date or month.
  • Weekday number.
  • Total revenue.

PostgreSQL provides several useful date functions, and Querier exposes them through PgDialectFunctions.

Daily sales analytics

First, let's build a daily sales report:

Select dailySales = Select.builder()

    // Convert the date to a readable string
    .select(
        PgDialectFunctions.toChar(
            Order::getCreatedAt,
            "YYYY-MM-DD"
        ).as("sales_day")
    )

    // Extract the weekday
    .select(
        PgDialectFunctions.datePart(
            "dow",
            Order::getCreatedAt
        ).as("weekday_number")
    )

    // Calculate daily revenue
    .select(
        Aggregate.sum(Order::getTotal).as("revenue")
    )

    .from(Order.class)

    .where(
        Condition.gte(
            Order::getCreatedAt,
            LocalDate.of(2025, 1, 1)
        )
    )

    // Group by the actual date
    .groupBy(Order::getCreatedAt)

    .orderBy(
        OrderBy.asc(Order::getCreatedAt)
    )

    .build();
Enter fullscreen mode Exit fullscreen mode

This gives us SQL conceptually equivalent to:

SELECT
    TO_CHAR(orders.created_at, 'YYYY-MM-DD') AS sales_day,
    DATE_PART('dow', orders.created_at) AS weekday_number,
    SUM(orders.total) AS revenue

FROM orders

WHERE orders.created_at >= '2025-01-01'

GROUP BY orders.created_at

ORDER BY orders.created_at ASC;
Enter fullscreen mode Exit fullscreen mode

We are using the actual date column for grouping, while deriving the display label and weekday number from that grouped column.

Monthly revenue using DATE_TRUNC and GROUP BY DbFunction

Now let's move beyond daily reporting.

Imagine we want to generate a monthly revenue report instead. Grouping by the original createdAt column would still produce daily results, so we need to group by a calculated date expression.

PostgreSQL provides DATE_TRUNC for this purpose.

It truncates a date or timestamp to a specified precision, such as a day, week, month, quarter, or year.

Querier 2.0.4 introduces support for using DbFunction directly in GROUP BY, which makes this possible without falling back to native SQL.

Select monthlySales = Select.builder()

    // Calculate the month
    .select(
        PgDialectFunctions.dateTrunc(
            "month",
            Order::getCreatedAt
        ).as("sales_month")
    )

    // Calculate monthly revenue
    .select(
        Aggregate.sum(Order::getTotal).as("monthly_revenue")
    )

    .from(Order.class)

    .where(
        Condition.gte(
            Order::getCreatedAt,
            LocalDate.of(2025, 1, 1)
        )
    )

    // GROUP BY PostgreSQL DATE_TRUNC
    .groupBy(
        PgDialectFunctions.dateTrunc(
            "month",
            Order::getCreatedAt
        )
    )

    // Sort chronologically
    .orderBy(
        OrderBy.asc(
            PgDialectFunctions.dateTrunc(
                "month",
                Order::getCreatedAt
            )
        )
    )

    .build();
Enter fullscreen mode Exit fullscreen mode

This produces SQL equivalent to:

SELECT
    DATE_TRUNC('month', orders.created_at) AS sales_month,
    SUM(orders.total) AS monthly_revenue

FROM orders

WHERE orders.created_at >= '2025-01-01'

GROUP BY DATE_TRUNC('month', orders.created_at)

ORDER BY DATE_TRUNC('month', orders.created_at) ASC;
Enter fullscreen mode Exit fullscreen mode

Now, instead of getting one row per day, we get one row per month.

For example:

sales_month          | monthly_revenue
---------------------|----------------
2025-01-01 00:00:00  | 12500.00
2025-02-01 00:00:00  | 18200.00
2025-03-01 00:00:00  | 15300.00
Enter fullscreen mode Exit fullscreen mode

This is particularly useful for time-series reporting, revenue trends, and dashboard charts.

GROUP BY

Approach Best suited for
groupBy(ColumnRef...) Grouping by entity properties
groupBy(DbFunction...) Grouping by database functions
groupBy(Expression...) Grouping by custom SQL expressions

You can also combine grouping criteria by calling the methods separately:

.groupBy(Customer::getId)
.groupBy(
    PgDialectFunctions.dateTrunc(
        "month",
        Order::getCreatedAt
    )
)
Enter fullscreen mode Exit fullscreen mode

Or

.groupBy(Customer::getId)
.groupBy(
    Expression.raw("sales_month")
)
Enter fullscreen mode Exit fullscreen mode

This groups the results by both customer and month.

One important consideration: Expression.raw() uses SQL text directly. Keep these expressions application-controlled and never concatenate untrusted user input into them.

This addition makes Querier significantly more useful for analytics scenarios where grouping by calculated values is essential.

10. A few more PostgreSQL function examples

The examples above cover some of the most useful functions, but the PostgreSQL dialect offers more possibilities.

Working with JSONB

If you later add a JSONB column to your order model, you can extract nested values:

DbFunction orderMetadataStatus =
    PgDialectFunctions.jsonbExtractPathText(
        Order::getMetadata,
        "payment",
        "status"
    );
Enter fullscreen mode Exit fullscreen mode

This example assumes you have added a metadata property with a corresponding getMetadata() method and mapped it to a PostgreSQL JSONB column.

Then use it in a WHERE condition:

Select paidOrders = Select.builder()
    .select(Order::getId)
    .select(Order::getTotal)
    .from(Order.class)
    .where(
        Condition.eq(
            PgDialectFunctions.jsonbExtractPathText(
                Order::getMetadata,
                "payment",
                "status"
            ),
            "confirmed"
        )
    )
    .build();
Enter fullscreen mode Exit fullscreen mode

This generates an expression equivalent to:

WHERE jsonb_extract_path_text(
    orders.metadata,
    'payment',
    'status'
) = :param0
Enter fullscreen mode Exit fullscreen mode

Working with arrays

PostgreSQL's ARRAY_AGG can aggregate values into an array:

.select(
    PgDialectFunctions.arrayAgg(
        Product::getName
    ).as("product_names")
)
Enter fullscreen mode Exit fullscreen mode

This is useful when your reporting layer needs structured collections instead of comma-separated strings.

Numeric calculations

You can also use PostgreSQL's numeric functions:

.select(
    PgDialectFunctions.round(
        Product::getPrice,
        2
    ).as("rounded_price")
)
Enter fullscreen mode Exit fullscreen mode

This generates:

ROUND(products.price, 2) AS rounded_price
Enter fullscreen mode Exit fullscreen mode

These are just a few examples of what is available in the PostgreSQL dialect.

11. Practical considerations

When building analytics queries, there are a few things worth keeping in mind.

1. Keep database-specific functions explicit.

Using PgDialectFunctions makes it clear that a query depends on PostgreSQL functionality. It also makes database portability considerations easier to identify.

2. Prefer parameterized conditions.

Use method references and bound values rather than concatenating user input into SQL expressions.

3. Use CTEs to separate responsibilities.

A CTE can make a large query easier to read by separating data preparation, aggregation, and final filtering.

4. Pay attention to GROUP BY semantics.

Every non-aggregated selected column must be valid under the database's grouping rules.

When grouping by a calculated expression, make sure the grouping expression matches the intended value selected by the query. For example, grouping by createdAt produces daily groups, while grouping by DATE_TRUNC('month', createdAt) produces monthly groups.

5. Don't ignore query performance.

For example, filtering with:

DATE_PART('year', orders.created_at) >= 2025
Enter fullscreen mode Exit fullscreen mode

may prevent the use of a conventional index on created_at in the same way as a simple range condition.

Prefer:

orders.created_at >= DATE '2025-01-01'
Enter fullscreen mode Exit fullscreen mode

when it expresses the same business rule.

Always inspect the actual execution plan with PostgreSQL's EXPLAIN ANALYZE when optimizing analytics queries.

6. Be careful with the data model.

Our example assumes one product per order. Real e-commerce applications generally have an order_items table containing quantities, unit prices, and discounts. For accurate product-level revenue analytics, those line-item values should be used instead of assuming that Order.total belongs entirely to one product.

Conclusion

Building analytics queries doesn't necessarily mean choosing between writing native SQL strings everywhere and using a restrictive abstraction.

With Querier, we can combine:

  • Java method references for column resolution.
  • JOINs for relationships between entities.
  • Standard SQL aggregation functions.
  • CTEs for structuring complex queries.
  • PostgreSQL-specific functions for database-level calculations.
  • GROUP BY support for columns, database functions, and custom SQL expressions.
  • Parameterized output for execution through different Java database APIs.

The addition of groupBy(DbFunction...) and groupBy(Expression...) makes it possible to express more advanced analytical queries directly through the builder, including monthly revenue calculations using PostgreSQL's DATE_TRUNC.

The result is a query-building approach that keeps SQL concepts visible while making query construction more maintainable in Java.

Querier is open source, Java 17+, and available on Maven Central.

Explore the project:

Feedback, suggestions, and contributions are welcome!

Top comments (0)