The Java Database Connectivity (JDBC) API provides the java.sql.Statement interface that allows to represent an SQL statement and to execute queries with the database.

Why is this an issue?

A common reason for a poorly performant query is because it’s processing more data than required.

Querying unnecessary data demands extra work on the server, adds network overhead, and consumes memory and CPU resources on the application server. The effect is amplified when the query includes multiple joins.

The rule flags an issue when a SELECT * query is provided as an argument to methods in java.sql.Connection and java.sql.Statement.

What is the potential impact?

How to fix it

Make the SELECT * an explicit selection of the required fields.

Code examples

Noncompliant code example

public class OrderRepository {

    public record OrderSummary(String name, String orderId, BigDecimal price) { }

    public List<OrderSummary> queryOrderSummaries(Connection conn) {
            String sql = "SELECT * " +                                                         // Noncompliant
                          "FROM Orders JOIN Customers ON Orders.customerId = Customers.id ";

            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            return convertResultToOrderSummaryList(rs);
    }
}

Compliant solution

public class OrderRepository {

    public record OrderSummary(String name, String orderId, BigDecimal price) { }

    public List<OrderSummary> queryOrderSummaries(Connection conn) {
            String sql = "SELECT Customers.name, Orders.id, Orders.price " +                   // Compliant
                          "FROM Orders JOIN Customers ON Orders.customerId = Customers.id ";

            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            return convertResultToOrderSummaryList(rs);
    }
}

Resources

Documentation

Articles & blog posts