SQL intermediate

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

Prompt

"Filter rows using a subquery in the WHERE clause to find customers who placed at least one order above $1000"

SQL
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

  1. Select customer_id from the orders table.
  2. Use a subquery to find order_ids where the amount is greater than 1000.
  3. Filter the main query results based on the order_ids returned by the subquery.
  4. 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

Prompt

"Customer orders: (1, 500), (2, 1500), (3, 800)"

SQL
Customer ID 2
Prompt

"Customer orders: (4, 1200), (4, 900), (5, 2000)"

SQL
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.