How to Filter Customers with High-Value Orders Using Subqueries?
Discover how to efficiently filter your customer data by leveraging subqueries in the WHERE clause to identify high-value orders.
Formula Genius can generate a draft from a plain-English prompt. Supported formulas can be checked with sample cases; review the coverage on the result.
The formula
"Filter rows using a subquery in the WHERE clause to find customers who placed at least one order above $1000"
SELECT customer_id FROM orders WHERE order_id IN (SELECT order_id FROM orders WHERE amount > 1000)
This SQL query retrieves customer IDs for those who have made at least one order exceeding $1000.
Step-by-step breakdown
- Select customer_id from the orders table.
- Use a subquery to find order_ids where the amount is greater than 1000.
- Filter the main query results based on the order_ids returned by the subquery.
- Return only the customer_ids that match the filtered order_ids.
Edge cases & warnings
- No customers have placed orders over $1000, resulting in an empty result set.
- Multiple orders exist for a customer, but only some exceed $1000.
- Customers with orders exactly at $1000 will not be included.
- Orders with NULL amounts will not be counted.
Examples
"Customer orders: (1, 500), (2, 1500), (3, 800)"
Customer ID 2
"Customer orders: (4, 1200), (4, 900), (5, 2000)"
Customer ID 4, 5
Frequently asked questions
What is a subquery?
A subquery is a query nested inside another SQL query.
Can I use multiple conditions in the subquery?
Yes, you can combine multiple conditions using AND/OR in the subquery.
What if there are no matching orders?
The query will return an empty result set if no orders match the criteria.
Can't find what you need?
Describe a formula in plain English. Formula Genius drafts and explains it, and can check supported formulas on sample cases.