Junior — Middle
What methods can be used to improve the performance of database queries?
sobes.tech AI
Answer from AI
To improve database query performance, the following methods can be used:
- Indexing: creating indexes on columns frequently used in WHERE or JOIN conditions.
- Query optimization: avoid SELECT *, use only necessary fields, write efficient JOINs.
- Caching: store results of frequent queries in memory (e.g., using Redis or built-in cache).
- Pagination: load data in parts rather than the entire table.
- Using prepared statements: enhances performance and security.
- Query profiling: analyze execution plans (EXPLAIN) and eliminate bottlenecks.
- Parallel execution: if possible, split queries into several parallel ones.
Example of using an index in SQL:
CREATE INDEX idx_user_email ON users(email);
In Java, when working with JDBC, you can use prepared statements:
String sql = "SELECT * FROM users WHERE email = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, "user@example.com");
ResultSet rs = stmt.executeQuery();