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

    Native Queries

    When JPQL can't express what you need (Postgres-specific JSON ops, CTEs, window functions), drop to native SQL with nativeQuery = true.

    Course progress0%
    Focus
    3 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    When JPQL can't express what you need (Postgres-specific JSON ops, CTEs, window functions), drop to native SQL with nativeQuery = true.

    Informative example

    ts
    public interface OrderRepository extends JpaRepository<Order, Long> {
    @Query(value = """
    with recent as (
    select user_id, count(*) cnt
    from orders
    where created_at > now() - interval '30 days'
    group by user_id
    )
    select u.id, u.email, coalesce(r.cnt, 0) as orders_30d
    from users u
    left join recent r on r.user_id = u.id
    where u.tier = :tier
    """, nativeQuery = true)
    List<Object[]> activeUsersByTier(@Param("tier") String tier);
    }

    Best practices

    • Map results to a projection interface instead of Object[] — type-safe.
    • Keep native SQL in repository files only — never in services.
    • If you have many native queries, consider jOOQ for compile-time SQL.
    Ready to mark this lesson complete?Track your journey across the entire course.