Real-world examples of null pointer exceptions in SQL queries

If you work with Java, C#, or any other language that talks to a database, you’ve probably hit a nasty runtime error right in the middle of a query. That’s where real-world **examples of null pointer exceptions in SQL queries** become incredibly helpful. Instead of vague theory, seeing how these bugs actually show up in application code makes them much easier to avoid. In this guide, we’ll walk through practical examples of how null values sneak into query parameters, result mappings, ORM frameworks, and stored procedure calls. Each example of a null pointer exception in SQL is based on patterns that show up constantly in production systems: missing request data, unexpected empty result sets, misconfigured ORM mappings, and more. We’ll also touch on 2024–2025 trends such as increased use of nullable annotations, stricter compiler checks, and better database drivers, and how they change the way these errors surface. By the end, you’ll recognize the warning signs long before your users see a stack trace.
Written by
Jamie
Published
Updated

Examples of null pointer exceptions in SQL queries from real applications

Let’s skip the textbook definitions and go straight to the examples of null pointer exceptions in SQL queries that developers actually hit in production. The patterns are surprisingly consistent, whether you’re using raw JDBC, JPA/Hibernate, or a micro-ORM.

Example of a null parameter causing failure in a prepared statement

A very common example of a null pointer exception in SQL code happens when you assume a parameter is always present, then blindly use it to build or bind a query.

String userId = request.getParameter("userId");

// userId is null if the client forgot to send it
String sql = "SELECT * FROM users WHERE id = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, userId);   // NPE if userId is null in some frameworks
ResultSet rs = ps.executeQuery();

Some JDBC drivers tolerate null here and translate it to NULL in SQL; others don’t. In older stacks or custom wrappers, setString may dereference the value internally and throw. The best examples of defensive code always validate input first:

if (userId == null || userId.isBlank()) {
    throw new IllegalArgumentException("userId is required");
}

This looks trivial, but in real examples pulled from production incident reports, that missing null check has taken down entire login flows.

Examples include null from a DAO method feeding into SQL

Another family of examples of null pointer exceptions in SQL queries comes from DAO methods that quietly return null instead of an empty object or collection. A service layer then calls methods on that null, often right before building a query.

User user = userDao.findByEmail(email);  // returns null if not found

// Later, when building a query for audit logs
String sql = "SELECT * FROM audit_logs WHERE user_id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setLong(1, user.getId()); // NPE here if user is null

The SQL itself is fine; the bug is in the assumption that findByEmail never returns null. A safer pattern is to return Optional<User> in Java or throw a specific exception when nothing is found. Modern style guides from universities like Carnegie Mellon and other secure coding resources consistently recommend avoiding null as a “not found” sentinel for exactly this reason.

Example of null from a ResultSet mapping step

Sometimes the query runs successfully, but your mapping logic produces a null object that later causes a null pointer exception when another query depends on it.

String sql = "SELECT id, name FROM departments WHERE code = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, deptCode);
ResultSet rs = ps.executeQuery();

Department dept = null;
if (rs.next()) {
    dept = new Department();
    dept.setId(rs.getLong("id"));
    dept.setName(rs.getString("name"));
}

// Later, building a query using the department ID
String employeeSql = "SELECT * FROM employees WHERE department_id = ?";
PreparedStatement eps = conn.prepareStatement(employeeSql);
eps.setLong(1, dept.getId());  // NPE if no department row was found

This is a textbook example of how a null pointer exception in SQL-related code can be triggered even when the first query returns no rows instead of an error. The best examples of resilient mapping code treat “no rows” as a first-class case:

if (dept == null) {
    // Handle gracefully, e.g., return empty list of employees
    return Collections.emptyList();
}

ORM examples of null pointer exceptions in SQL queries

ORMs like Hibernate and Entity Framework reduce boilerplate, but they also hide a lot of null-related pitfalls. Here are a few real examples from ORM-based systems.

Lazy-loaded association is null during query construction

Consider a JPA entity:

@Entity
class Order {
    @ManyToOne(fetch = FetchType.LAZY)
    private Customer customer;

    // getters/setters
}

In a service method, you try to filter orders by the customer’s region using JPQL:

Order order = orderRepository.findById(orderId).orElse(null);

String region = order.getCustomer().getRegion(); // NPE if customer is null
String jpql = "SELECT o FROM Order o WHERE o.customer.region = :region";
TypedQuery<Order> q = em.createQuery(jpql, Order.class);
q.setParameter("region", region);

If the customer association is optional, some orders legitimately have customer = null. That turns into a null pointer exception long before the JPQL query even runs. This is a classic example of how null pointer exceptions in SQL queries and ORM queries are often really domain modeling problems.

Misconfigured column mapping returning null

Another ORM example of null pointer exceptions in SQL queries: a field that’s required in the database but mapped as nullable in the entity.

@Entity
class Product {
    @Column(name = "price", nullable = true)  // wrong; DB column is NOT NULL
    private BigDecimal price;
}

If data corruption or a migration bug inserts a row with price = NULL, the ORM may happily map that null into your Product object. Later, you format the price for display:

String label = "$" + product.getPrice().toPlainString(); // NPE if price is null

The SQL query succeeded; the exception shows up in UI code. These are some of the best examples of why schema constraints, ORM metadata, and application assumptions must line up. Resources from universities like MIT OpenCourseWare often highlight this alignment in database design courses.

Stored procedure examples of null pointer exceptions in SQL queries

Stored procedures can hide null behavior inside the database, and the application code often assumes a non-null response.

Imagine a stored procedure that returns a single row with an aggregate:

CREATE PROCEDURE GetTotalSales
    @CustomerId INT
AS
BEGIN
    SELECT SUM(Amount) AS TotalSales
    FROM Orders
    WHERE CustomerId = @CustomerId;
END;

In your C# code:

var cmd = new SqlCommand("GetTotalSales", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CustomerId", customerId);

var result = cmd.ExecuteScalar(); // returns DBNull.Value if no rows

decimal totalSales = (decimal)result; // InvalidCastException or NPE via wrapper

In many real examples, teams wrap this in helper methods that do result.ToString() or call extension methods, which then throw a null pointer exception or similar null reference error. A safer pattern is:

if (result == null || result == DBNull.Value)
{
    totalSales = 0m;
}
else
{
    totalSales = (decimal)result;
}

This stored procedure scenario shows how examples of null pointer exceptions in SQL queries often originate from database behavior that’s technically valid but semantically unexpected.

Example of null in dynamic SQL string concatenation

Yes, dynamic SQL string building is still common in 2024–2025, especially in legacy code and quick prototypes. It’s also a rich source of null pointer exceptions.

String baseQuery = "SELECT * FROM orders WHERE 1=1";
String statusFilter = getStatusFromRequest(request); // may return null

if (!statusFilter.isEmpty()) {  // NPE if statusFilter is null
    baseQuery += " AND status = '" + statusFilter + "'";
}

This is a simple example of a null pointer exception in SQL string construction. Besides the security nightmare of SQL injection, the null handling is broken. A more modern approach uses prepared statements and treats null as “no filter”:

String sql = "SELECT * FROM orders WHERE (:status IS NULL OR status = :status)";

In 2024–2025, with frameworks like Spring Data and query builders, the best examples of modern code avoid manual string concatenation entirely, which dramatically reduces these null-related bugs.

Framework-level examples: Spring, .NET, and micro-ORMs

Frameworks introduce their own flavors of examples of null pointer exceptions in SQL queries.

Spring JDBC template with null RowMapper output

String sql = "SELECT * FROM users WHERE username = ?";
User user = jdbcTemplate.queryForObject(sql, new Object[]{username}, (rs, rowNum) -> {
    if (rs.getBoolean("deleted")) {
        return null;  // bad idea
    }
    User u = new User();
    u.setId(rs.getLong("id"));
    u.setUsername(rs.getString("username"));
    return u;
});

// Later
String greeting = "Hello, " + user.getUsername(); // NPE if RowMapper returned null

Spring’s documentation and training materials (for example, courses referenced by universities like Harvard’s CS50 SQL content even if not Spring-specific) strongly encourage returning valid objects and handling filtering at the query level.

Dapper / micro-ORM returning null for single-or-default

In .NET micro-ORMs like Dapper, calling QuerySingleOrDefault<T> can return null if there’s no match:

var user = connection.QuerySingleOrDefault<User>(
    "SELECT * FROM Users WHERE Email = @Email",
    new { Email = email }
);

// Later, building a query based on user role
var sql = "SELECT * FROM Permissions WHERE RoleId = @RoleId";
var permissions = connection.Query<Permission>(sql, new { RoleId = user.RoleId });
// NullReferenceException if user is null

These are modern, 2020s-era examples of null pointer-like exceptions in SQL queries that show up in cloud-native services just as much as in old monoliths.

The patterns above haven’t gone away, but modern tooling is changing how often they slip through.

1. Nullable reference types and annotations.
Languages like C# with nullable reference types (#nullable enable) and Java with annotations like @NotNull and @Nullable are catching many of these errors at compile time. For instance, if a repository method is annotated to return @Nullable User, your IDE can warn you when you call user.getId() without a null check.

2. Stricter database schemas.
Teams are increasingly using migration tools (Flyway, Liquibase) to enforce NOT NULL constraints and default values. That means fewer examples of ORM-mapped fields unexpectedly becoming null after SQL queries.

3. Better observability.
Modern logging and tracing make it easier to tie a null pointer exception in SQL query code back to the exact missing parameter or empty result set. Observability guidance from organizations like NIST and related security frameworks often highlight strong logging practices that indirectly reduce time-to-fix for these bugs.

4. Safer query builders.
Fluent query builders and LINQ-style APIs reduce the number of places where you manually concatenate strings or mis-handle null parameters. The best examples of modern codebases have almost no hand-written SQL strings outside of migrations.

How to think about preventing these examples of null pointer exceptions in SQL queries

If you look across all these real examples, the patterns are consistent:

  • Treat every input to a query as potentially null. Validate early and fail clearly.
  • Avoid using null as a signal for “not found” or “empty result.” Prefer empty collections, Optional, or explicit exceptions.
  • Align database constraints, ORM mappings, and code-level assumptions about nullability.
  • Use language and framework features (nullable reference types, annotations) to surface risky spots at compile time.
  • Log enough context around SQL queries (parameters, counts, not raw sensitive data) to quickly reproduce null scenarios.

These aren’t abstract best practices; they’re concrete responses to the best examples of how null pointer exceptions in SQL queries actually break production systems.

FAQ: examples of null pointer exceptions in SQL queries

Q1. Can you give another simple example of a null pointer exception in SQL code?
Yes. Imagine reading a config value that controls a query filter:

String country = System.getenv("DEFAULT_COUNTRY"); // may be null
String sql = "SELECT * FROM customers WHERE country = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, country.toUpperCase()); // NPE if env var is missing

This is a straightforward example of how configuration nulls lead to SQL-related null pointer exceptions.

Q2. Are these examples only relevant to Java, or do they apply to other languages?
They apply broadly. In C#, you’ll see NullReferenceException instead of NullPointerException, but the root cause is the same: dereferencing a null object while preparing or processing SQL queries. In Python, you might see AttributeError: 'NoneType' object has no attribute ... in similar situations.

Q3. How do I debug real examples of null pointer exceptions in SQL queries in production?
Start with the stack trace to locate the exact line where the null was dereferenced. Then inspect:

  • Which query was being built or executed.
  • Which input values or result mappings could have been null.
  • Recent changes to schema, stored procedures, or configuration.

Adding structured logging around query parameters (without logging sensitive data) is one of the best examples of a practical debugging aid.

Q4. Is returning null from a repository or DAO method always bad?
Not always, but many of the worst examples of null pointer exceptions in SQL queries start with a repository quietly returning null. Returning Optional<T> in Java or using clear “TryGet” patterns in C# makes it much harder to accidentally ignore the possibility of “no result.”

Q5. Do modern ORMs eliminate these issues?
No. ORMs reduce boilerplate but introduce their own null-related edge cases: lazy loading, misconfigured mappings, and inconsistent nullability assumptions. The examples include everything from null associations to unexpected null aggregates. You still have to think about nulls explicitly.

Explore More Null Pointer Exceptions

Discover more examples and insights in this category.

View All Null Pointer Exceptions