SQL: Structured Query LanguageSQL FundamentalsMembership Filtering
How do you match a list of possible values using IN?
Question 23 of 30 · Updated
On this page
- 1. Syntax
- 2. Worked example: selecting orders in two states
- 3. IN versus multiple OR conditions
- 4. Numeric membership, duplicate list entries and ordering
- 5. NULL behavior and NOT IN
- 6. Combine IN with another condition
- 7. Membership in values supplied by a subquery
- 8. Empty lists and dynamic filters
- 9. Safe application integration
- 10. Performance considerations
- 11. Common mistakes and decision guide
- 12. Interview-ready answer
- 13. Validation and references
Use the SQL IN operator to match a value against a list of acceptable values. For example, WHERE status IN ('paid', 'shipped') returns rows whose status is paid or shipped. IN expresses alternatives compactly instead of repeating the same equality comparison with OR. It matches individual values, not a continuous range, and does not change the source data.
1. Syntax#
SQLSELECT column_name FROM table_name WHERE column_name IN (value1, value2, value3);
Supply comma-separated expressions in parentheses. Quote string literals with single quotes, use unquoted numeric literals when comparing numeric columns, and use typed date literals or parameters for date values. Choose comparable types; the database may perform implicit conversions, but incompatible comparisons can fail.
| Requirement | Predicate |
|---|---|
| Match specific statuses | status IN ('paid', 'shipped') |
| Match specific IDs | id IN (2, 5, 9) |
| Match specific calendar dates | day IN (DATE '2026-01-01', DATE '2026-01-26') |
| Exclude specific known statuses | status NOT IN ('pending', 'cancelled') |
| Match every numeric value within a closed interval | amount BETWEEN 100 AND 200 |
IN is appropriate when the allowed values are discrete alternatives. BETWEEN is appropriate for an ordered, inclusive interval. For example, IN (100,200) matches 100 and 200 but not 150; BETWEEN 100 AND 200 matches all three.
2. Worked example: selecting orders in two states#
Suppose an operations dashboard displays paid and shipped orders. Use the following synthetic dataset, where id identifies each order, status records its current state, and amount is an illustrative whole-number monetary amount. The CTE makes the SQL examples reproducible without creating permanent tables.
| id | status | amount |
|---|---|---|
| 1 | paid | 500 |
| 2 | shipped | 1200 |
| 3 | pending | 700 |
| 4 | paid | 1500 |
| 5 | cancelled | 300 |
| 6 | NULL | 900 |
| 7 | shipped | 400 |
SQLWITH orders(id,status,amount) AS ( VALUES (1,'paid',500), (2,'shipped',1200), (3,'pending',700), (4,'paid',1500), (5,'cancelled',300), (6,NULL::text,900), (7,'shipped',400) ) SELECT id,status FROM orders WHERE status IN ('paid','shipped') ORDER BY id;
Result:
| id | status |
|---|---|
| 1 | paid |
| 2 | shipped |
| 4 | paid |
| 7 | shipped |
Orders 3 and 5 have known values that do not match the list. Order 6 has unknown status, so its predicate does not evaluate TRUE. ORDER BY id establishes the displayed sequence. IN itself neither sorts rows nor guarantees a particular order. Because the result includes order identifiers, multiple orders with the same status remain separate records.
3. IN versus multiple OR conditions#
For ordinary comparable values, the following predicates have the same truth value:
SQLWHERE status IN ('paid','shipped') -- Equivalent condition: WHERE status = 'paid' OR status = 'shipped'
These are alternative clause fragments, not two WHERE clauses in one statement. Each compares the same expression against different allowed values. IN is more readable as the list grows, but it is not a general replacement for OR involving different columns or unrelated predicates. For instance, a rule that matches orders with status paid OR amount above a threshold cannot be expressed merely by listing those two conditions in a scalar IN list.
Verify equivalence by projecting both Boolean expressions:
SQLWITH orders(id,status,amount) AS ( VALUES (1,'paid',500), (2,'shipped',1200), (3,'pending',700), (4,'paid',1500), (5,'cancelled',300), (6,NULL::text,900), (7,'shipped',400) ) SELECT id,status, status IN ('paid','shipped') AS member, status='paid' OR status='shipped' AS expanded FROM orders ORDER BY id;
| id | status | member | expanded |
|---|---|---|---|
| 1 | paid | TRUE | TRUE |
| 2 | shipped | TRUE | TRUE |
| 3 | pending | FALSE | FALSE |
| 4 | paid | TRUE | TRUE |
| 5 | cancelled | FALSE | FALSE |
| 6 | NULL | NULL | NULL |
| 7 | shipped | TRUE | TRUE |
The two expressions agree in every tested case. A NULL Boolean result means UNKNOWN. This equivalence describes ordinary predicate truth values rather than promising a particular evaluation order or count for volatile expressions. The query optimizer is free to choose a suitable plan.
4. Numeric membership, duplicate list entries and ordering#
An application may retrieve orders for a user-selected list of IDs:
SQLWITH orders(id,status,amount) AS ( VALUES (1,'paid',500), (2,'shipped',1200), (3,'pending',700), (4,'paid',1500), (5,'cancelled',300), (6,NULL::text,900), (7,'shipped',400) ) SELECT id,amount FROM orders WHERE id IN (5,2,2,99) ORDER BY id;
| id | amount |
|---|---|
| 2 | 1200 |
| 5 | 300 |
The repeated value 2 does not duplicate the matching order; the predicate is evaluated as membership, not as a request to produce a row for each list entry. ID 99 has no corresponding row and does not produce a placeholder. The returned order is 2 then 5 because of ORDER BY id, not the list's sequence 5 then 2.
If the source query already contains duplicate rows, IN does not remove them. Use an appropriate projection and DISTINCT only when duplicate elimination is actually required. If the application must reproduce input ordering or multiplicity, model the input as a relation with position information and design a suitable join instead of expecting IN to do so.
5. NULL behavior and NOT IN#
IN uses SQL equality comparisons and three-valued logic. An ordinary list of known values can produce TRUE for a match, FALSE for a known nonmatch, or UNKNOWN for a missing left-hand value. Adding a NULL entry introduces another important distinction: a known match still produces TRUE, but if nothing matches and one comparison is unknown, the result is UNKNOWN rather than FALSE.
SQLWITH orders(id,status,amount) AS ( VALUES (1,'paid',500), (2,'shipped',1200), (3,'pending',700), (4,'paid',1500), (5,'cancelled',300), (6,NULL::text,900), (7,'shipped',400) ) SELECT id,status, status IN ('paid',NULL) AS member, status NOT IN ('paid',NULL) AS nonmember FROM orders ORDER BY id;
| id | status | member | nonmember |
|---|---|---|---|
| 1 | paid | TRUE | FALSE |
| 2 | shipped | NULL | NULL |
| 3 | pending | NULL | NULL |
| 4 | paid | TRUE | FALSE |
| 5 | cancelled | NULL | NULL |
| 6 | NULL | NULL | NULL |
| 7 | shipped | NULL | NULL |
WHERE retains only TRUE. Thus WHERE status IN ('paid',NULL) retains the paid rows but not the missing-status row. WHERE status NOT IN ('paid',NULL) retains no rows in this dataset: the paid rows evaluate FALSE and all others UNKNOWN. The negation of UNKNOWN is UNKNOWN, not TRUE.
To intentionally include orders with missing status, use WHERE status IN ('paid','shipped') OR status IS NULL. To select known statuses outside a list, use NOT IN with a list known not to contain NULL; decide separately whether missing left-hand values should qualify. Avoid adding NULL to a list as a shortcut for IS NULL. Detailed anti-membership with subqueries and NOT EXISTS is reserved for the later curriculum lesson on NULL-sensitive exclusions.
6. Combine IN with another condition#
IN is a Boolean predicate, so it can be combined with AND, OR and NOT. Suppose the dashboard only needs paid or shipped orders of at least 1000:
SQLWITH orders(id,status,amount) AS ( VALUES (1,'paid',500), (2,'shipped',1200), (3,'pending',700), (4,'paid',1500), (5,'cancelled',300), (6,NULL::text,900), (7,'shipped',400) ) SELECT id,status,amount FROM orders WHERE status IN ('paid','shipped') AND amount >= 1000 ORDER BY id;
| id | status | amount |
|---|---|---|
| 2 | shipped | 1200 |
| 4 | paid | 1500 |
Both conditions must qualify: the order must be in an allowed status and meet the amount threshold. If written as separate OR comparisons, parentheses are important: WHERE (status = 'paid' OR status = 'shipped') AND amount >= 1000. Without parentheses, SQL's usual AND-before-OR precedence could allow paid orders that do not meet the amount condition.
7. Membership in values supplied by a subquery#
Instead of hard-coding a list, IN can compare against the result of a single-column subquery. This is useful when allowed values are maintained as data, rather than compiled into application code. Here an inline relation supplies permitted states:
SQLWITH orders(id,status,amount) AS ( VALUES (1,'paid',500), (2,'shipped',1200), (3,'pending',700), (4,'paid',1500), (5,'cancelled',300), (6,NULL::text,900), (7,'shipped',400) ), allowed(status) AS ( VALUES ('paid'),('shipped'),('paid') ) SELECT id,status FROM orders WHERE status IN (SELECT status FROM allowed) ORDER BY id;
| id | status |
|---|---|
| 1 | paid |
| 2 | shipped |
| 4 | paid |
| 7 | shipped |
The duplicate paid entry in allowed does not multiply orders. Unlike an ordinary join, this use of IN only tests whether a qualifying value exists; it does not return the matching allowed-row columns. A scalar IN subquery must supply one column of compatible type. PostgreSQL also supports row-valued membership with matching column counts, but composite membership and correlated queries are outside this introductory lesson. Do not assume that IN is always faster or slower than a join or EXISTS; their semantics and execution strategies matter.
8. Empty lists and dynamic filters#
A literal empty list written as IN () is invalid syntax in PostgreSQL and many other SQL engines. Applications that build filters from selected values need to handle zero selections explicitly. The business rule may be match nothing, omit an optional filter, or report invalid input. These are different operations. For example, when the list represents authorized IDs, silently omitting the filter could expose unintended results.
PostgreSQL supports a comparison against an array with = ANY(array_expression). With ordinary equality, this can express membership in a parameterized array. The following literal examples demonstrate behavior:
SQLSELECT 2 = ANY(ARRAY[2,5]::integer[]) AS member, 2 = ANY(ARRAY[]::integer[]) AS empty_list, NULL::integer = ANY(ARRAY[2,5]::integer[]) AS unknown_member;
| member | empty_list | unknown_member |
|---|---|---|
| TRUE | FALSE | NULL |
An empty array makes this ANY comparison false. A SQL NULL array is not an empty array and has different semantics. Also, a subquery that returns zero rows is legal, even though a literal empty parenthesized list is not:
SQLSELECT 2 IN ( SELECT x FROM (VALUES (1)) AS v(x) WHERE FALSE ) AS empty_member, NULL::integer IN ( SELECT x FROM (VALUES (1)) AS v(x) WHERE FALSE ) AS null_empty_member;
| empty_member | null_empty_member |
|---|---|
| FALSE | FALSE |
There are no equality comparisons that could succeed or return UNKNOWN in the empty-subquery case. This differs from testing membership against a nonempty list that contains NULL. The exact behavior of empty literal lists and array syntax varies across engines; these examples use PostgreSQL.
9. Safe application integration#
Bind values using the driver's parameter API. Do not build SQL by concatenating comma-separated user strings. A typical PostgreSQL query template with a typed array parameter is:
SQLSELECT id,status FROM orders WHERE id = ANY($1::integer[]) ORDER BY id;
The driver must bind one integer array to $1. This template is not directly executable as standalone SQL without a binding or preparation context. Alternatively, build a list of placeholders from the validated number of items and bind each scalar separately. A single string parameter containing '2,5' is not automatically two SQL values. Validate types, enforce suitable list-size limits, and define empty-input semantics before execution.
For a Supabase JavaScript client, the general IN membership filter is commonly expressed with the dedicated in(column, values) method:
JAVASCRIPTconst statuses = ['paid', 'shipped']; const { data, error } = await supabase .from('orders') .select('id, status') .in('status', statuses) .order('id'); if (error) throw error;
This client snippet is illustrative, assumes an accessible orders table and a configured client, and was not executed against production data. Supabase's official Using Filters and filter reference were consulted; the latter demonstrates the raw in filter syntax and recommends specific filter methods where possible. Avoid manually assembling raw filter syntax from untrusted input. Query filters constrain results but do not replace database permissions or row-level security.
10. Performance considerations#
An IN predicate on an indexed scalar column may benefit from index access, particularly for a selective list. The optimizer may alternatively choose a scan when many rows match or when the estimated cost is lower. PostgreSQL can implement some constant lists as scalar-array comparisons; subquery membership can use other plan strategies. The syntax alone does not determine the cost.
For small, fixed lists, prioritize readability. For very large or frequently changing sets, consider an appropriate table, subquery, or array parameter depending on the engine and query contract. Large lists can increase parsing, binding and planning work; engines and drivers may impose limits. Inspect EXPLAIN and measure representative workloads. No performance benchmark or index change was performed here.
11. Common mistakes and decision guide#
| Mistake | Better approach |
|---|---|
| Writing a comma-separated string as one value | Pass distinct literals or correctly bound values |
| Assuming IN preserves list order | Specify ORDER BY or model input positions |
| Expecting duplicate list elements to duplicate output rows | Use a join when input multiplicity is required |
| Using IN to represent a numeric interval | Use BETWEEN or suitable inequality predicates |
| Expecting NULL in a list to match missing values | Use IS NULL explicitly |
| Ignoring NULL in NOT IN | Validate the list and define missing-value behavior |
| Generating an empty IN list | Handle empty input according to the business rule |
| Concatenating user input into SQL | Use typed parameters |
12. Interview-ready answer#
IN is a membership predicate used to match a value against several allowed alternatives. WHERE status IN ('paid','shipped') is equivalent in truth value to WHERE status = 'paid' OR status = 'shipped' for ordinary comparable values. IN is concise for discrete lists, does not multiply rows because of duplicate list entries, and does not guarantee result order. It also supports compatible single-column subqueries. SQL NULL can yield UNKNOWN, especially in NOT IN, so handle missing values explicitly and use bound parameters for dynamic input.
Quick interview checks: Can IN match both paid and shipped? Yes, each row can match either allowed value. Does a duplicate list entry return the row twice? No. Does IN (100,200) include 150? No. Does NULL in an IN list match a missing value? Not by ordinary equality. Can IN accept a subquery? Yes, with compatible result columns. Is an empty literal IN list portable? No; define empty-selection behavior explicitly.
13. Validation and references#
Eight read-only PostgreSQL statements were executed using synthetic VALUES data or literal expressions: string membership; OR equivalence; numeric membership with duplicate and missing IDs; IN and NOT IN with NULL; combined filtering; subquery membership; typed array membership; and empty-subquery behavior. All returned the displayed results. Clause fragments, application templates and JavaScript snippets are illustrative and were not independently executed. No educational DDL or production business-data changes were made. The result and truth-value tables convey the membership decisions directly, so no Mermaid diagram was necessary. Official Supabase Using Filters and filter documentation were retrieved through the documentation connector. The PostgreSQL reference destinations were not live fetched because web access is unavailable under the offline research exception.
References
- 1.PostgreSQL — Row and Array Comparisonspostgresql.org
- 2.PostgreSQL — Subquery Expressionspostgresql.org
- 3.PostgreSQL — Logical Operatorspostgresql.org
- 4.PostgreSQL — Index Typespostgresql.org
- 5.Supabase JavaScript — Using Filterssupabase.com
- 6.Supabase JavaScript — filtersupabase.com
Related questions
Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning