Subqueries in SELECT and WHERE Clauses
Свайпніть щоб показати меню
A subquery in the WHERE clause lets you filter rows based on the results of another query. This is a powerful way to select only the data you need, using information from related tables.
In e-commerce analytics, you can use a subquery in the WHERE clause to:
- Find customers who have ordered products from a specific category;
- Identify products that have ever been purchased.
The subquery returns a set of values, and the main query includes only rows that match those values. This technique allows you to apply complex filters that depend on data from other tables.
Key differences:
- A subquery in the
WHEREclause controls which rows appear in your results; - A subquery in the
SELECTclause adds calculated or related columns to each row.
Use subqueries in the WHERE clause whenever you need to filter data based on conditions that involve multiple tables or calculated results.
123456789SELECT p.product_id, p.name, ( SELECT COUNT(*) FROM orders o WHERE o.product_id = p.product_id ) AS total_orders FROM products p;
This query demonstrates how to use a subquery within the SELECT clause. The main query retrieves each product's ID and name from the products table. For each product, the subquery calculates the total number of orders by counting rows in the orders table where the product_id matches the current product. The result is a list of products, each with its total order count. This technique allows you to include calculated or aggregated data for each row in your result set, using subqueries that reference the current row's values.
12345678SELECT DISTINCT c.customer_id, c.name FROM customers c WHERE c.customer_id IN ( SELECT o.customer_id FROM orders o JOIN products p ON o.product_id = p.product_id WHERE p.category = 'Electronics' );
1. Which statement best describes the difference between using a subquery in the SELECT clause and in the WHERE clause?
2. Fill in the blanks to select product names from the products table that have been ordered at least once.
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат