Native Queries
When JPQL cannot express what Postgres offers — CTEs, window functions, JSONB operators, dialect-specific intervals — use a native query with nativeQuery = true.
Introduction
When JPQL cannot express what Postgres offers — CTEs, window functions, JSONB operators, dialect-specific intervals — use a native query with nativeQuery = true. Spring Data still binds parameters safely through @Param.
Native SQL talks tables and columns (orders, created_at). That buys power and costs portability: a Postgres CTE may not run on MySQL without edits. Keep native SQL inside repository methods, not services or controllers.
Prefer interface projections or DTO mapping over raw Object[]. For large native estates, teams eventually consider jOOQ; for a few reporting queries, Spring Data native queries are enough.
Use native queries sparingly. Most Orders CRUD and filters should stay JPQL or derived methods so MySQL estates can share logic.
Purpose of this lesson
Write parameterized native SQL for Orders reporting on PostgreSQL, with typed projections and clear repository boundaries.
Understanding the topic
Native queries unlock dialect features at the cost of portability.
- nativeQuery = true: SQL string executed as-is (via Hibernate).
- tables/columns: match Flyway names, not Java fields.
- parameters: still use
@Param— never concatenate. - projections: interface or class mapping beats
Object[]. - scope: reporting and DB-specific ops — not everyday CRUD.
Step-by-step explanation
- Identify a report that needs a CTE or window function.
- Write the SQL in Postgres first; verify with
EXPLAIN. - Wrap it in
@Query(..., nativeQuery = true)with a projection. - Call it from a read-only service method; keep JPQL for standard paths.
Informative example
Postgres CTE for Orders activity by tier (native).
public interface OrderAnalyticsRepository extends JpaRepository<Order, Long> {@Query(value = """with recent as (select user_id, count(*) as cntfrom orderswhere created_at > now() - interval '30 days'group by user_id)select u.id as id,u.email as email,coalesce(r.cnt, 0) as orders30dfrom users uleft join recent r on r.user_id = u.idwhere u.tier = :tier""",nativeQuery = true)List<UserOrderActivity> activeUsersByTier(@Param("tier") String tier);}public interface UserOrderActivity {Long getId();String getEmail();long getOrders30d();}
Output
id | email | orders30d 17 | learner@example.com| 4
Real-world use
Growth asks which TechLearningPRO tiers placed orders in the last 30 days. A Postgres CTE answers in one round trip. The API service stays read-only transactional; the SQL never leaks into the controller.
Security implications
Native SQL is a high-risk surface if misused.
- Parameterized binds only — string-built SQL is injectable.
- Limit reporting endpoints to authorized staff roles.
- Do not select PII columns the caller is not allowed to see.
Best practices
- Colocate native SQL in repository interfaces only.
- Document Postgres-only assumptions next to the method.
- Consider jOOQ when native query count explodes.
Common mistakes
- Copying JPQL entity names into native SQL.
- Returning
Object[]everywhere and casting by magic index. - Sprinkling native SQL across services until dialects fork the codebase.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhen choose nativeQuery over JPQL?+
Answer
2IntermediateQuestionHow do you keep native queries type-safe?+
Answer
Object[].3IntermediateQuestionWhat is the portability trade-off?+
Answer
Hands-on exercise
Lab. Implement activeUsersByTier against Postgres (simplify tables if needed). Call it from a service and map to a JSON DTO. Attempt the same SQL on MySQL and note what breaks.
Summary
Native queries are the escape hatch for Orders analytics on Postgres. Next: page and sort large result sets safely.