Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Write a paged native query with @Query in Spring Data JPA and explain why you may need countQuery. Mention any newer annotation for native queries.

A paged native query looks like @Query(value = "select * from orders where customer_id = :cid", countQuery = "select count(*) from orders where customer_id = :cid", nativeQuery = true) Page<Order> byCustomer(@Param("cid") long cid, Pageable p). A Page needs a total, and without countQuery Spring Data must derive a count from the native SQL by rewriting it, which can fail or produce a slow query, so we give it the count explicitly. Sort properties from the Pageable are added to the native SQL as column names and must be validated, Spring Data JPA 3.4 added @NativeQuery as a shorthand (check your version), and SpEL such as #{#entityName} lets queries refer to the entity name generically.

Why this question is asked

Native queries are the escape hatch when JPQL cannot express what we need: database-specific functions, window functions, hints or a carefully tuned join. The moment such a query also has to be paged, Spring Data has to do something it cannot do reliably for SQL it does not understand: work out the total. Interviewers ask this to see whether we know how Page is built, why countQuery exists, and what risks come with letting a Pageable add sorting to raw SQL. In this answer, we will recap how Page works, write the paged native query, see why the count query matters, deal with sorting safely, and look at @NativeQuery and SpEL entity names.

1A Quick Recap: What a Page Needs

A Pageable is a request for one page: a page number, a page size and an optional sort. A Page<T> is the answer: the rows of that page plus the total number of matching rows, from which it computes the number of pages.

So every Page costs two queries. The content query adds a limit and offset to the main query; for page 3 of size 20, that is offset 60 and limit 20. The count query returns how many rows match in total. For JPQL, Spring Data builds the count query by parsing the JPQL and replacing the select list with count. For native SQL, it has to guess, because it does not have a full SQL parser for every dialect.

2Writing the Paged Native Query

Here is the method with an explicit count query, and what runs for page 0 of size 20.

Java
interface OrderRepository extends JpaRepository<Order, Long> {
@Query(value = "select * from orders where customer_id = :cid",
countQuery = "select count(*) from orders where customer_id = :cid",
nativeQuery = true)
Page<Order> byCustomer(@Param("cid") long cid, Pageable p);
}
Page<Order> page = orderRepository.byCustomer(42L, PageRequest.of(0, 20));
// select * from orders where customer_id = ? offset ? rows fetch first ? rows only
// (limit syntax depends on dialect)
// select count(*) from orders where customer_id = ?
// page.getContent().size() -> 20
// page.getTotalElements() -> 137
// page.getTotalPages() -> 7
Step throughOne call to a paged native query
ServiceRepository proxyDatabase
byCustomer(42, page 0 size 20)
content query with offset 0, limit 20
20 rows
countQuery: select count(*) ... where customer_id = 42
137
Page: 20 orders, total 137, 7 pages

6 messages in order. Play them, or step through them one at a time.

A Page always costs a content query and a count query.

Notice that we wrote the count ourselves and kept the same where clause, so the total matches the content. Spring Data still adds the paging clause to the content query, using the dialect's syntax.

3Why countQuery Matters

Without countQuery, Spring Data tries to turn the native query into a count by string manipulation, replacing the select list with count(*) or wrapping it. For select * from orders where customer_id = :cid, that usually works. For real native queries, the kind we wrote native for in the first place, it often does not. A query with a CTE, a window function, a union, a subquery in the select list or a database-specific clause can produce a count query that is invalid SQL, or one that is valid but counts the wrong thing.

Even when the derived count is valid, it can be slow. Counting the full content query includes joins and sorting that the count does not need. A hand-written count can drop the order by, drop joins that do not change the number of rows, and use a simpler path the database can answer from an index. On a table of fifty million orders, that difference can be seconds per request.

And sometimes the best count is no count. If the caller only needs to know whether there is a next page, returning Slice<Order> instead of Page<Order> skips the count query altogether.

4Sorting a Native Query Safely

If the Pageable carries a sort, Spring Data appends an order by to the native SQL, using the sort property names as they are, because it cannot map entity fields to columns inside SQL it does not parse. So Sort.by("createdAt") becomes order by createdAt, which fails if the column is created_at. The sort property must be the column name.

That also raises a safety question. If an endpoint passes a client-supplied sort straight into a native query, the client controls part of the SQL text. Spring Data checks sort expressions and rejects many dangerous ones, but relying on that for public input is a bad idea, and any unindexed column becomes a way to make the database sort millions of rows. The safe pattern is an allow-list that maps public sort keys to known column names.

Java
private static final Map<String, String> SORTS = Map.of(
"newest", "created_at",
"total", "total");
Pageable safe(Pageable in) {
Sort sort = Sort.unsorted();
for (Sort.Order o : in.getSort()) {
String column = SORTS.get(o.getProperty());
if (column == null) throw new BadRequestException("unknown sort " + o.getProperty());
sort = sort.and(Sort.by(o.getDirection(), column));
}
return PageRequest.of(in.getPageNumber(), Math.min(in.getPageSize(), 100), sort);
}
// ?sort=newest,desc -> order by created_at desc
// ?sort=password -> 400 Bad Request

The same helper caps the page size at 100, which protects the database from size=1000000.

5@NativeQuery and SpEL Entity Names

Spring Data JPA 3.4 added @NativeQuery, a shorthand for @Query with nativeQuery = true. It reads better and has a countQuery attribute as well. Check your version before using it; on older versions, stay with @Query.

SpEL, the Spring Expression Language, can be used inside query strings. #{#entityName} is replaced by the entity name of the repository's domain type. That is mainly useful in generic base repositories marked @NoRepositoryBean, where one query string must work for many entities. In native queries it inserts the entity name, not the table name, so it only fits when the two are the same; check how your entities are mapped before relying on it.

Java
@NativeQuery(value = "select * from orders where customer_id = :cid",
countQuery = "select count(*) from orders where customer_id = :cid")
Page<Order> byCustomer(@Param("cid") long cid, Pageable p); // Spring Data JPA 3.4+
@NoRepositoryBean
interface SoftDeleteRepository<T, ID> extends JpaRepository<T, ID> {
@Query("select e from #{#entityName} e where e.deleted = false")
List<T> findActive(); // JPQL; works for every entity extending it
}

6Follow-up questions

Can I use a count query with a JPQL @Query too?

Yes. countQuery works for JPQL as well, and it is worth writing when the derived count would include joins or fetches that do not change the number of rows. For example, a query with join fetch for associations cannot be counted directly and needs its own count.

Why not just return List and compute pages myself?

We could pass a Pageable to a List method, and Spring Data will apply limit and offset without a count. That is fine when the caller does not need totals. Page is for when totals are part of the contract; Slice is the middle ground with a next-page flag.

What happens with deep pages in a native offset query?

The database must still read and discard all the skipped rows, so page 5,000 of size 20 reads 100,020 rows. For deep paging or feeds, keyset pagination, which filters on the last seen sort value, is far cheaper.

7Conclusion

In this answer, we saw that a Page needs both content and a total, so a paged native query runs two statements. Spring Data cannot reliably derive a count from native SQL, so countQuery gives it a correct and fast one, or Slice avoids the count altogether. Sort properties go into native SQL as column names, so they should come from an allow-list, and @NativeQuery in Spring Data JPA 3.4 and SpEL's #{#entityName} make such queries shorter and more reusable.

What to say in the interviewAbout 100 seconds aloud

Open with

I would write it as @Query with value select star from orders where customer_id = :cid, countQuery select count star from orders where customer_id = :cid, and nativeQuery true, on a method returning Page<Order> that takes @Param("cid") long cid and a Pageable.

Then, if they want more

When I call it, Spring Data runs the content query with the paging clause for the dialect, offset and limit, and then the count query, and builds a Page with the rows, the total and the number of pages.

The reason for countQuery is that a Page needs the total, and for native SQL Spring Data has no full parser, so it tries to derive the count by rewriting the string. That can fail for CTEs, unions or window functions, or produce a slow count that includes sorting and joins it does not need.

Writing the count myself makes it correct and lets me make it cheap. If the caller only needs to know whether there is another page, I would return Slice and skip the count entirely.

Sorting needs care: Spring Data appends the Pageable's sort properties to native SQL as they are, so they must be column names, and I would never pass a client's sort parameter straight through. I map public sort keys to known columns with an allow-list and cap the page size.

Newer versions, Spring Data JPA 3.4 and later, have @NativeQuery as a shorthand, and SpEL like #{#entityName} lets a generic base repository refer to the entity name.

About this answer

Last updated
12 November 2026
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 "Write a paged native query with @Query in Spring Data JPA and explain why you may need...": https://scrivio-interview-library.netlify.app/databases/spring-data-jpa/a70f1cf0ef/