SQL IN and NOT IN

Use IN when a column can match any value from a list. It is often clearer than repeating several equality conditions with OR.

SELECT id, name, class, mark
FROM student
WHERE class IN (
    'Four',
    'Five'
)
ORDER BY id;
Run these queries using Plus2Net's own sample data. The 35-record student table and complete MySQL SQL dump let you recreate these examples and compare the actual output. Import it into a practice database; examples that change data should run on a copy.

This returns students whose class is either Four or Five.

idnameclassmark
1John DeoFour75
4Krish StarFour60
5John MikeFour60
6Alex JohnFour55
7My John RobFive78
8AsruidFive85
10Big JohnFour55
15Tade RowFour88
16GimmyFour88
18HonnyFive75
21Babby JohnFour69
31Marry ToeeyFour88
Think of IN as membership testing: keep the row when the compared value matches one of the listed values or one of the values returned by a compatible subquery.
On this page — Show page sectionsHide page sections

SQL IN Syntax

SELECT column_list
FROM table_name
WHERE column_name IN (
    value1,
    value2,
    value3
);

The list can contain text, numbers, dates or values returned by a one-column subquery, as long as they are comparable with the left-hand expression.

IN vs Repeated OR Conditions

This query:

SELECT id, name, class
FROM student
WHERE class = 'Four'
   OR class = 'Five'
   OR class = 'Six';

can be written more compactly as:

SELECT id, name, class
FROM student
WHERE class IN (
    'Four',
    'Five',
    'Six'
);

Use OR when the alternatives involve different columns or different types of conditions. Use IN when several alternatives are equality checks against the same expression.

IN with Numeric Values

Numeric values do not need quotes:

SELECT id, name, class, mark
FROM student
WHERE id IN (
    1,
    2,
    4,
    7
);

This returns only the listed student IDs.

SQL NOT IN

NOT IN excludes values in the list.

SELECT id, name, class, mark
FROM student
WHERE class NOT IN (
    'Four',
    'Five'
)
ORDER BY id;

With the complete 35-row student dataset, this excludes the Four and Five classes and returns 23 rows. Expand the result below to inspect them.

Show 23 NOT IN results
idnameclassmark
2Max RuinThree85
3ArnoldThree55
9Tes QrySix78
11RonaldSix89
12ReckySix94
13KtySeven88
14BigySeven88
17TumyuSix54
19TinnyNine18
20JacklyNine65
22ReggidSeven55
23HerodEight79
24Tiddy NowSeven78
25Giff TowSeven88
26CreleaSeven79
27Big NoseThree81
28Rojj BaseSeven86
29Tess PlayedSeven55
30Reppy RedSix79
32Binn RottSeven90
33Kenn ReinSix96
34Gain ToeSeven69
35Rows NoumpSix88

IN with a Subquery

The IN list can come from another SELECT query. Suppose student_sports contains the IDs of students who joined sports:

SELECT id, name, class, mark
FROM student
WHERE id IN (
    SELECT id
    FROM student_sports
);

The inner query returns one column of IDs. The outer query then returns the full student records for those IDs.

A subquery used with IN must return a compatible number of columns for the comparison. For a normal single-column IN test such as id IN (...), the subquery should return one comparable column.

See SQL subqueries for more examples.

NOT IN with Subqueries and NULL

NOT IN needs extra care when the list or subquery can contain NULL.

For example:

SELECT id, name
FROM student
WHERE id NOT IN (
    SELECT id
    FROM student_sports
);

If the subquery can return NULL, SQL's three-valued logic can make the NOT IN result unknown and prevent rows from matching as expected.

If NULLs are possible, either exclude them explicitly:

SELECT id, name
FROM student
WHERE id NOT IN (
    SELECT id
    FROM student_sports
    WHERE id IS NOT NULL
);

or consider a correlated NOT EXISTS design when that better expresses the anti-match requirement.

See SQL NULL values for the underlying comparison behavior.

Dynamic IN List with PHP PDO

A PDO placeholder represents one data value. You cannot bind one array directly to a single placeholder and expect it to expand into an IN list.

This does not work as intended:

<?php
$ids=[1,4,7];

$stmt=$dbo->prepare(
    "SELECT id,name
     FROM student
     WHERE id IN (:ids)"
);
?>

Create one placeholder for each validated value instead:

<?php
require 'config.php';

$ids=[1,4,7];

$ids=array_values(
    array_filter(
        $ids,
        fn($id) => filter_var(
            $id,
            FILTER_VALIDATE_INT,
            ['options' => ['min_range' => 1]]
        ) !== false
    )
);

if($ids===[]){
    exit('No valid IDs supplied.');
}

$placeholders=implode(
    ',',
    array_fill(
        0,
        count($ids),
        '?'
    )
);

$sql="SELECT id,name,class,mark
      FROM student
      WHERE id IN ($placeholders)
      ORDER BY id";

$stmt=$dbo->prepare($sql);

foreach($ids as $position => $id){
    $stmt->bindValue(
        $position+1,
        (int)$id,
        PDO::PARAM_INT
    );
}

$stmt->execute();
?>

The SQL structure is generated only from application-controlled placeholder characters. The actual IDs remain bound data values.

An empty list needs explicit application handling because IN () is not a valid normal MySQL IN list.

IN with Aggregate Queries

IN can filter the rows used by aggregate functions such as SUM():

SELECT SUM(mark) AS total_mark
FROM student
WHERE id IN (
    1,
    2,
    3,
    4
);

The aggregate is calculated only from rows whose IDs are in the list.

Handling an Empty IN List

Application code sometimes builds an IN list from selected checkboxes, filters or IDs returned by another process. If there are no values, do not generate:

-- Invalid normal IN-list syntax
WHERE id IN ()

Instead, decide what an empty selection should mean:

  • return no rows,
  • skip the filter and return all permitted rows, or
  • stop and ask the user to select at least one value.

That decision belongs in the application logic rather than being hidden inside an invalid SQL statement.

IN Performance Notes

  • Small literal IN lists are usually straightforward for MySQL to optimize.
  • An index on the compared column can help, depending on the query and data distribution.
  • For very large lists, consider whether the values should instead live in a table and be joined or queried through a subquery.
  • For IN subqueries, performance depends on the query plan, indexes and the size of both result sets.
  • Use EXPLAIN when a production IN query is unexpectedly slow.

IN vs FIND_IN_SET()

IN compares one expression against a list of separate SQL values:

WHERE class IN (
    'Four',
    'Five'
)

FIND_IN_SET() searches inside a comma-separated string value:

WHERE FIND_IN_SET(
    'Four',
    class_list
) > 0

These are different data models. If a field stores multiple independent values in one comma-separated column, consider whether a normalized related table would be a better schema.

FIND_IN_SET() Tutorial

Common SQL IN Mistakes

Using IN for unrelated conditions

IN is best when one expression is compared against several candidate values. Use AND/OR when the conditions involve different columns or operators.

Returning multiple columns from a single-column IN subquery

For id IN (subquery), the subquery should return one compatible column.

Binding an array to one PDO placeholder

Create one placeholder per value. PDO does not expand one bound array into a comma-separated SQL list.

Ignoring NULL with NOT IN

A NULL in the compared list or subquery can make NOT IN behave differently from what beginners expect because the result can become unknown.

Generating IN () from an empty application array

Handle the empty-list meaning in application logic before building the SQL.

Putting numeric data in quotes by habit

Use values according to their actual datatype. Prepared statements make this clearer by binding integers as integers and strings as strings.

SQL AND / OR SQL BETWEEN SQL Subqueries

SQL NULL FIND_IN_SET() SUM with IN

Full Student Table with SQL Dump

Frequently Asked Questions

Q1: What does SQL IN do?

IN tests whether one expression matches any value in a list or compatible subquery result.

Q2: When should I use IN instead of OR?

Use IN when several alternatives compare the same expression for equality. OR is more flexible when the alternatives involve different columns or conditions.

Q3: What does NOT IN do?

NOT IN keeps rows whose compared value does not match any value in the list, subject to SQL NULL comparison rules.

Q4: Can IN use a subquery?

Yes. For a normal single-column IN comparison, the subquery should return one compatible column of candidate values.

Q5: Why can NOT IN fail when a subquery contains NULL?

SQL uses three-valued logic. A NULL in the candidate set can make comparisons evaluate as unknown, so NULL should be handled explicitly.

Q6: Can I bind an array to one PDO placeholder in an IN clause?

No. Generate one placeholder for each value and bind each value separately.

Q7: What should I do when the IN list is empty?

Handle that case in application logic by deciding whether an empty selection means no rows, no filter, or an input error. Do not generate an empty IN () list.



SQL AND / OR SQL BETWEEN



Subscribe to our YouTube Channel here



plus2net.com
Dharitri

24-07-2009

good It help me in my project
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer