Native SQL queries let you run real SQL commands directly in your Spring Boot app. This helps when you want full control over the database or need special SQL features.
Native SQL queries in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Spring Boot
@Query(value = "SQL query here", nativeQuery = true)
List<Entity> methodName();Use @Query annotation with nativeQuery = true to tell Spring Boot this is raw SQL.
The SQL string is written exactly as you would run it in your database.
Examples
Spring Boot
@Query(value = "SELECT * FROM users WHERE email = ?1", nativeQuery = true)
User findByEmail(String email);Spring Boot
@Query(value = "SELECT * FROM products WHERE price > :minPrice", nativeQuery = true) List<Product> findExpensiveProducts(@Param("minPrice") double minPrice);
Sample Program
This example shows a repository method using a native SQL query to get users by their status. The service calls it to print names of active users.
Spring Boot
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; public interface UserRepository extends JpaRepository<User, Long> { @Query(value = "SELECT * FROM users WHERE status = :status", nativeQuery = true) List<User> findUsersByStatus(@Param("status") String status); } // Usage in a service class @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public void printActiveUsers() { List<User> activeUsers = userRepository.findUsersByStatus("ACTIVE"); activeUsers.forEach(user -> System.out.println(user.getName())); } }
Important Notes
Make sure your SQL matches your database schema exactly.
Use parameters to avoid SQL injection risks.
Native queries bypass some JPA features like automatic mapping, so check your entity mappings carefully.
Summary
Native SQL queries let you run exact SQL in Spring Boot repositories.
Use @Query with nativeQuery = true and write your SQL as usual.
They are useful for complex or database-specific queries.
Practice
1. What annotation is used in Spring Boot to define a native SQL query inside a repository interface?
easy
Solution
Step 1: Recognize the annotation for queries in Spring Data JPA
The@Queryannotation is used to define custom queries in repository interfaces.Step 2: Identify how to specify native SQL
SettingnativeQuery = trueinside@Querytells Spring Boot to treat the query as native SQL.Final Answer:
@Query with nativeQuery = true -> Option CQuick Check:
Native SQL queries use @Query(nativeQuery = true) [OK]
Hint: Look for @Query with nativeQuery true flag [OK]
Common Mistakes:
- Using a non-existent annotation like @NativeQuery
- Forgetting to set nativeQuery = true
- Confusing @Query with @SqlQuery
- Using @SQLNative which is invalid
2. Which of the following is the correct syntax to write a native SQL query in a Spring Boot repository method?
easy
Solution
Step 1: Recall the correct attribute names in @Query
The attribute for the query string isvalue, and to mark it native SQL, usenativeQuery = true.Step 2: Check each option's syntax
@Query(value = "SELECT * FROM users", nativeQuery = true) correctly uses@Query(value = "...", nativeQuery = true). Options B, C, and D use invalid attribute names or annotations.Final Answer:
@Query(value = "SELECT * FROM users", nativeQuery = true) -> Option AQuick Check:
@Query(value=..., nativeQuery=true) is correct syntax [OK]
Hint: Use value= for query and nativeQuery=true [OK]
Common Mistakes:
- Using native=true instead of nativeQuery=true
- Using @NativeQuery annotation which doesn't exist
- Using sql= instead of value= for query string
- Swapping attribute order incorrectly
3. Given this repository method:
What will be the result of calling
@Query(value = "SELECT * FROM products WHERE price > ?1", nativeQuery = true) List<Product> findExpensiveProducts(double minPrice);
What will be the result of calling
findExpensiveProducts(100.0)?medium
Solution
Step 1: Understand the native SQL query with parameter
The query selects all products where price is greater than the first parameter (?1), which is passed as 100.0.Step 2: Predict the method output
CallingfindExpensiveProducts(100.0)returns products priced above 100.0, so the list contains those products.Final Answer:
List of products with price greater than 100.0 -> Option DQuick Check:
Native query with ?1 uses method parameter [OK]
Hint: ?1 matches first method parameter in native query [OK]
Common Mistakes:
- Thinking ?1 is invalid in native queries
- Confusing greater than with less than
- Assuming empty list without data
- Believing syntax error due to placeholder
4. Identify the error in this native query method:
@Query(value = "SELECT * FROM orders WHERE status = :status", nativeQuery = true) List<Order> findByStatus(String status);
medium
Solution
Step 1: Check parameter usage in native queries
Native SQL queries in Spring Boot do not support named parameters like:statusby default; they require positional parameters like?1.Step 2: Identify correct parameter syntax
The query should use?1to refer to the first method parameter instead of:status.Final Answer:
Query string should use ?1 instead of :status -> Option BQuick Check:
Native queries use positional parameters like ?1 [OK]
Hint: Use ?1 for parameters in native queries, not :name [OK]
Common Mistakes:
- Using named parameters in native queries
- Forgetting nativeQuery = true
- Assuming return type must be Optional
- Confusing JPQL and native SQL syntax
5. You want to write a native SQL query in Spring Boot to update the price of all products in a category. Which method signature and annotation is correct?
hard
Solution
Step 1: Recognize update queries need @Modifying
In Spring Boot, native update queries require the@Modifyingannotation to indicate a modifying operation.Step 2: Check parameter syntax and nativeQuery flag
@Modifying @Query(value = "UPDATE products SET price = price * 1.1 WHERE category = ?1", nativeQuery = true) int increasePriceByCategory(String category); correctly uses positional parameter?1and setsnativeQuery = true. @Modifying @Query(value = "UPDATE products SET price = price * 1.1 WHERE category = :category", nativeQuery = true) int increasePriceByCategory(String category); uses named parameter which is invalid in native queries. @Modifying @Query(value = "UPDATE products SET price = price * 1.1 WHERE category = ?1") int increasePriceByCategory(String category); misses nativeQuery flag. @Query(value = "UPDATE products SET price = price * 1.1 WHERE category = ?1", nativeQuery = true) void increasePriceByCategory(String category); misses @Modifying.Final Answer:
@Modifying @Query(value = "UPDATE products SET price = price * 1.1 WHERE category = ?1", nativeQuery = true) int increasePriceByCategory(String category); -> Option AQuick Check:
Update native queries need @Modifying and nativeQuery=true [OK]
Hint: Use @Modifying and nativeQuery=true for update queries [OK]
Common Mistakes:
- Omitting @Modifying on update queries
- Using named parameters in native queries
- Forgetting nativeQuery=true flag
- Returning void instead of int for update count
