Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 32

    Native Queries

    When JPQL cannot express what Postgres offers — CTEs, window functions, JSONB operators, dialect-specific intervals — use a native query with nativeQuery = true.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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

    1. Identify a report that needs a CTE or window function.
    2. Write the SQL in Postgres first; verify with EXPLAIN.
    3. Wrap it in @Query(..., nativeQuery = true) with a projection.
    4. Call it from a read-only service method; keep JPQL for standard paths.

    Informative example

    Postgres CTE for Orders activity by tier (native).

    java
    public interface OrderAnalyticsRepository extends JpaRepository<Order, Long> {
    @Query(value = """
    with recent as (
    select user_id, count(*) as cnt
    from orders
    where created_at > now() - interval '30 days'
    group by user_id
    )
    select u.id as id,
    u.email as email,
    coalesce(r.cnt, 0) as orders30d
    from users u
    left join recent r on r.user_id = u.id
    where 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.

    3 questions
    1BeginnerQuestionWhen choose nativeQuery over JPQL?+

    Answer

    When you need database-specific SQL (CTEs, JSONB, windows) that JPQL cannot express portably.
    2IntermediateQuestionHow do you keep native queries type-safe?+

    Answer

    Map columns to a Spring Data projection interface or DTO instead of Object[].
    3IntermediateQuestionWhat is the portability trade-off?+

    Answer

    Native SQL may lock you to Postgres (or MySQL) features; JPQL remains the portable default for CRUD/filters.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.