Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

How does JPQL differ from SQL? Write a JPQL query that returns customers in a given city who have at least one order above an amount.

JPQL queries entities and their attributes instead of tables and columns, follows mapped associations for joins, and Hibernate translates it into SQL for the configured database dialect. The query is select distinct c from Customer c join c.orders o where c.address.city = :city and o.total > :amount, with values bound through named parameters such as :city, never concatenated into the string.

Why this question is asked

Almost every Spring Data JPA application has @Query annotations, and most bugs in them come from treating JPQL as if it were SQL: using table names, joining on columns, or forgetting that a join can repeat the root entity. Interviewers ask this basic question because it shows quickly whether we think in entities, and the small query reveals whether we know why distinct is there. In this answer, we will recap the entity model, compare JPQL with SQL, build the query step by step, look at how parameters are bound and how Hibernate turns it into SQL, and finish with joins that follow no association.

1A Quick Recap of the Model

Let us use a small model. A Customer has an embedded Address, a value object stored in the customer table's own columns, and a collection of Order entities. Each Order has a total.

Java
@Entity
class Customer {
@Id Long id;
String name;
@Embedded Address address; // columns street, city in the customer table
@OneToMany(mappedBy = "customer") List<Order> orders;
}
@Embeddable
record Address(String street, String city) {}
@Entity @Table(name = "orders")
class Order {
@Id Long id;
BigDecimal total;
@ManyToOne Customer customer; // foreign key column customer_id
}

2How JPQL Differs From SQL

SQL talks about tables, columns and foreign keys. JPQL talks about the Java model: entity names, attribute names and associations. So in JPQL we write Customer, not customer, and c.address.city, not a column name, and c.orders to join, not a condition on customer_id. Hibernate knows the mapping, so it knows which tables and columns those names stand for.

A JPQL query also returns entities, not rows. select c from Customer c gives us managed Customer objects, which means Hibernate tracks them in the persistence context and writes back any changes we make. And because JPQL is independent of the database, Hibernate translates the same query into the SQL dialect of whichever database we configured: PostgreSQL, MySQL, Oracle and so on.

SQL and JPQL side by side
SQLJPQL
Works ontables and columnsentities and attributes
From clausefrom customerfrom Customer c
Joinjoin orders o on o.customer_id = c.idjoin c.orders o
Embedded valuec.city (a column)c.address.city (a path)
Resultrows of valuesmanaged entities, or values and DTOs
Database specificyes, per vendorno, translated per dialect

3Building the Query Step by Step

We want customers in a given city who have at least one order above an amount. We start from customers, join their orders through the mapped association, and filter on both.

Java
@Query("""
select distinct c
from Customer c
join c.orders o
where c.address.city = :city
and o.total > :amount""")
List<Customer> findInCityWithOrderAbove(@Param("city") String city,
@Param("amount") BigDecimal amount);
repo.findInCityWithOrderAbove("Berlin", new BigDecimal("500"));
// Ada has orders of 620 and 900, Alan has one of 750, Grace has only 120
// result: [Ada, Alan]

Notice the distinct. The join produces one row per matching order, so without distinct Ada would appear twice, once for each of her orders above 500. distinct removes the repeated customer. Hibernate 6 removes such duplicates automatically when a collection is join fetched; for a plain join like this one, keep distinct (and check your version), because it states the intent and keeps the query correct under any provider.

The join c.orders o is an inner join, so customers without orders are excluded, which is exactly right here. An exists subquery is another correct form: where exists (select 1 from Order o where o.customer = c and o.total > :amount). It avoids duplicates altogether and can be faster on large tables.

4Binding Parameters

Values go into the query through parameters, never through string concatenation. We use named parameters such as :city, bound with @Param in Spring Data or setParameter on a query, or positional parameters such as ?1. Binding keeps the query text constant, so the database can reuse its plan, and it makes SQL injection impossible, because the value is never parsed as part of the query.

Java
// wrong: user input becomes part of the query text
em.createQuery("select c from Customer c where c.address.city = '" + city + "'"); // city = "x' or '1'='1"
// right: a bound parameter
em.createQuery("select c from Customer c where c.address.city = :city", Customer.class)
.setParameter("city", city)
.getResultList();

5What Hibernate Turns It Into

When the query runs, Hibernate parses the JPQL, resolves each name through the mapping and generates SQL for the dialect. For our query on PostgreSQL, the result looks roughly like this.

SQL
select distinct c1_0.id, c1_0.city, c1_0.street, c1_0.name
from customer c1_0
join orders o1_0 on c1_0.id = o1_0.customer_id
where c1_0.city = ? and o1_0.total > ?
-- bound: 'Berlin', 500

The association c.orders became a join on the foreign key column, the embedded path c.address.city became the city column of the customer table, and the parameters became placeholders. The exact aliases vary by version.

6Joining Entities Without an Association

Joins usually follow mapped associations. Sometimes two entities are related by a value but have no mapped association, for example an audit entry that stores a customer id as a plain number. Hibernate has supported joins on unrelated entities with an explicit on clause since version 5.1, and Hibernate 6 continues to support them.

SQL
select c.name, a.action
from Customer c
join AuditEntry a on a.customerId = c.id
where a.createdAt > :since

7Follow-up questions

Why use distinct, and does it cost anything?

The join can repeat a customer once per matching order, and distinct removes the repeats. In SQL it becomes a distinct over all selected columns, which the database must sort or hash. For large results an exists subquery avoids producing duplicates in the first place.

Would this work with a left join?

A left join keeps customers without orders, but the condition o.total > :amount in the where clause then removes them again, so the result is the same as the inner join. Left joins matter when the condition is optional or moved into an on clause.

Can JPQL return only some columns?

Yes. select c.id, c.name returns Object arrays or tuples, and select new com.example.CustomerDto(c.id, c.name) returns DTOs, which are not managed and skip dirty checking.

8Conclusion

In this answer, we saw that JPQL works on entities and their attributes rather than tables and columns, joins along mapped associations, and is translated by Hibernate into SQL for the configured dialect. We wrote select distinct c from Customer c join c.orders o where c.address.city = :city and o.total > :amount, saw why distinct removes customers repeated by the join, bound values with named parameters instead of concatenation, and joined unrelated entities with an on clause.

What to say in the interviewAbout 70 seconds aloud

Open with

JPQL is the query language of JPA, and the main difference from SQL is that it works on the entity model: entity names, attributes and mapped associations, not tables, columns and foreign keys.

Then, if they want more

You write from Customer c and c.address.city, and you join with join c.orders o instead of writing the foreign key condition. Hibernate resolves those names through the mapping and translates the query into SQL for whatever dialect is configured, and the results are managed entities unless you select values or DTOs.

For the question, I would write: select distinct c from Customer c join c.orders o where c.address.city = :city and o.total > :amount. The distinct matters because the join produces one row per matching order, so a customer with two big orders would otherwise appear twice; an exists subquery is an alternative that avoids duplicates entirely.

City and amount are named parameters, bound with @Param or setParameter, never concatenated, which prevents SQL injection and lets the database reuse the plan. And when two entities are related only by a value, Hibernate also supports joining unrelated entities with an explicit on clause.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does JPQL differ from SQL? Write a JPQL query that returns customers in a given city...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/fb3eb866a9/