SQL for Java Devs · interview question
Given a one-to-many relationship between 'products' and 'reviews', how can you retrieve all products with their reviews in a single SQL query while ensuring each product appears only once in the result set?
Multiple choiceHardchapter-8-curatedpremiumsql-for-java-devsjoins
Answer and explanation
Correct answer
C. SELECT products.*, COUNT(reviews.id) FROM products JOIN reviews ON products.id = reviews.product_id GROUP BY products.id
Why
Using COUNT and GROUP BY allows you to retrieve each product only once, while aggregating associated reviews. This technique provides a clean and organized result set.
Test yourself on SQL for Java Devs
A free test with instant, explained results. No account needed.
More SQL for Java Devs questions
- How can JDBC transactions help maintain data integrity during an e-commerce checkout process?
- What would be the effect of not closing a PreparedStatement in a Java application?
- In JDBC, how do you ensure that SQL injection is prevented when executing a query that searches for a user by email?
- Why do teams use SQL JOINs to fetch relational data in a single query in production code?
- What should a repository method mainly encapsulate?
- How can you prevent the N+1 query problem when retrieving a list of orders with their customer details?