Table of Contents
Basic Syntax
1. Filtering with a List of Values
2. Using Strings and Dates
3. Using NOT IN to Exclude Values
4. Using Subqueries with IN
Key Points to Remember
Example: Combining IN with Other Conditions
Home Database Mysql Tutorial How to use the IN operator in MySQL?

How to use the IN operator in MySQL?

Aug 12, 2025 pm 03:46 PM
mysql IN操作符

The IN operator in MySQL checks if a value matches any in a specified list, simplifying multiple OR conditions; it works with literals, strings, dates, and subqueries, improves query readability, performs well on indexed columns, supports NOT IN (with caution for NULLs), and can be combined with other conditions, making it essential for efficient filtering in SQL queries.

How to use the IN operator in MySQL?

The IN operator in MySQL is used to check whether a value matches any value in a list. It's a convenient way to replace multiple OR conditions in a WHERE clause. Here's how to use it effectively.

Basic Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

This is equivalent to:

WHERE column_name = value1 OR column_name = value2 OR ...

1. Filtering with a List of Values

You can use IN to retrieve rows where a column matches any of several specified values.

SELECT * FROM employees
WHERE department_id IN (1, 3, 5);

This selects all employees who work in departments 1, 3, or 5 — much cleaner than writing three separate OR conditions.

2. Using Strings and Dates

The IN operator works with any data type, including strings and dates.

SELECT * FROM customers
WHERE country IN ('USA', 'Canada', 'Mexico');
SELECT * FROM orders
WHERE order_date IN ('2023-09-01', '2023-09-02', '2023-09-03');

Just make sure to use quotes for strings and date values.

3. Using NOT IN to Exclude Values

To find records that do not match any value in the list, use NOT IN.

SELECT * FROM products
WHERE category_id NOT IN (2, 4);

This returns products not in category 2 or 4.

⚠️ Be careful with NOT IN when the list contains NULL. If any value in the IN list is NULL, NOT IN may return no results because comparisons with NULL yield UNKNOWN in SQL logic.

4. Using Subqueries with IN

One of the most powerful uses of IN is with a subquery.

SELECT * FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders WHERE amount > 1000);

This finds all customers who have placed at least one order over $1000.

The subquery runs first, returns a list of customer IDs, and the outer query uses IN to match them.

Key Points to Remember

  • The IN operator improves readability and reduces code length compared to multiple OR conditions.
  • It’s case-insensitive for strings in most MySQL collations (like utf8mb4_general_ci), but this depends on your column’s collation setting.
  • Performance is generally good, especially when the column is indexed. For very large lists, consider using a temporary table or JOIN.
  • Avoid NOT IN with nullable columns or subqueries that might return NULL — use NOT EXISTS instead in such cases for safer results.

Example: Combining IN with Other Conditions

SELECT name, salary FROM employees
WHERE department_id IN (1, 2)
  AND salary > 50000;

This shows employees in departments 1 or 2 who earn more than $50,000.

Basically, IN simplifies filtering by a set of values — whether literal values or from a subquery — and is a staple in everyday MySQL querying.

The above is the detailed content of How to use the IN operator in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add a primary key to an existing table in MySQL? How to add a primary key to an existing table in MySQL? Aug 12, 2025 am 04:11 AM

To add a primary key to an existing table, use the ALTERTABLE statement with the ADDPRIMARYKEY clause. 1. Ensure that the target column has no NULL value, no duplication and is defined as NOTNULL; 2. The single-column primary key syntax is ALTERTABLE table name ADDPRIMARYKEY (column name); 3. The multi-column combination primary key syntax is ALTERTABLE table name ADDPRIMARYKEY (column 1, column 2); 4. If the column allows NULL, you must first execute MODIFY to set NOTNULL; 5. Each table can only have one primary key, and the old primary key must be deleted before adding; 6. If you need to increase it yourself, you can use MODIFY to set AUTO_INCREMENT. Ensure data before operation

Explain database indexing strategies (e.g., B-Tree, Full-text) for a MySQL-backed PHP application. Explain database indexing strategies (e.g., B-Tree, Full-text) for a MySQL-backed PHP application. Aug 13, 2025 pm 02:57 PM

B-TreeindexesarebestformostPHPapplications,astheysupportequalityandrangequeries,sorting,andareidealforcolumnsusedinWHERE,JOIN,orORDERBYclauses;2.Full-Textindexesshouldbeusedfornaturallanguageorbooleansearchesontextfieldslikearticlesorproductdescripti

How to back up a database in MySQL How to back up a database in MySQL Aug 11, 2025 am 10:40 AM

Using mysqldump is the most common and effective way to back up MySQL databases. It can generate SQL scripts containing table structure and data. 1. The basic syntax is: mysqldump-u[user name]-p[database name]>backup_file.sql. After execution, enter the password to generate a backup file. 2. Back up multiple databases with --databases option: mysqldump-uroot-p--databasesdb1db2>multiple_dbs_backup.sql. 3. Back up all databases with --all-databases: mysqldump-uroot-p

What is the difference between UNION and UNION ALL in MySQL? What is the difference between UNION and UNION ALL in MySQL? Aug 14, 2025 pm 05:25 PM

UNIONremovesduplicateswhileUNIONALLkeepsallrowsincludingduplicates;1.UNIONperformsdeduplicationbysortingandcomparingrows,returningonlyuniqueresults,whichmakesitsloweronlargedatasets;2.UNIONALLincludeseveryrowfromeachquerywithoutcheckingforduplicates,

How to change the GROUP_CONCAT separator in MySQL How to change the GROUP_CONCAT separator in MySQL Aug 22, 2025 am 10:58 AM

You can customize the separator by using the SEPARATOR keyword in the GROUP_CONCAT() function; 1. Use SEPARATOR to specify a custom separator, such as SEPARATOR'; 'The separator can be changed to a semicolon and plus space; 2. Common examples include using the pipe character '|', space'', line break character '\n' or custom string '->' as the separator; 3. Note that the separator must be a string literal or expression, and the result length is limited by the group_concat_max_len variable, which can be adjusted by SETSESSIONgroup_concat_max_len=10000; 4. SEPARATOR is optional

How to lock tables in MySQL How to lock tables in MySQL Aug 15, 2025 am 04:04 AM

The table can be locked manually using LOCKTABLES. The READ lock allows multiple sessions to read but cannot be written. The WRITE lock provides exclusive read and write permissions for the current session and other sessions cannot read and write. 2. The lock is only for the current connection. Execution of STARTTRANSACTION and other commands will implicitly release the lock. After locking, it can only access the locked table; 3. Only use it in specific scenarios such as MyISAM table maintenance and data backup. InnoDB should give priority to using transaction and row-level locks such as SELECT...FORUPDATE to avoid performance problems; 4. After the operation is completed, UNLOCKTABLES must be explicitly released, otherwise resource blockage may occur.

How to select data from a table in MySQL? How to select data from a table in MySQL? Aug 19, 2025 pm 01:47 PM

To select data from MySQL table, you should use SELECT statement, 1. Use SELECTcolumn1, column2FROMtable_name to obtain the specified column, or use SELECT* to obtain all columns; 2. Use WHERE clause to filter rows, such as SELECTname, ageFROMusersWHEREage>25; 3. Use ORDERBY to sort the results, such as ORDERBYageDESC, representing descending order of age; 4. Use LIMIT to limit the number of rows, such as LIMIT5 to return the first 5 rows, or use LIMIT10OFFSET20 to implement paging; 5. Use AND, OR and parentheses to combine

How to use the IN operator in MySQL? How to use the IN operator in MySQL? Aug 12, 2025 pm 03:46 PM

TheINoperatorinMySQLchecksifavaluematchesanyinaspecifiedlist,simplifyingmultipleORconditions;itworkswithliterals,strings,dates,andsubqueries,improvesqueryreadability,performswellonindexedcolumns,supportsNOTIN(withcautionforNULLs),andcanbecombinedwith

See all articles