How to combine multiple conditions with AND and OR in a SQL query?
Jul 11, 2025 am 02:29 AMIn SQL queries, multiple conditions can be combined with AND and OR to accurately filter data. 1. Use AND to indicate that all conditions must be met at the same time, such as looking for users who are older than 30 and whose city is Beijing; 2. Use OR to indicate that only one of the conditions needs to be met, such as looking for users who are Beijing or Shanghai; 3. Pay attention to priority when using mixed use, AND takes precedence over OR, and use brackets to clarify the logical relationship to avoid ambiguity; 4. Replacing multiple ORs with IN can make the statement more concise and easy to read, such as matching multiple city names. Use these logical operators and brackets reasonably to write accurate and clear query statements.
In SQL queries, if you want to filter data based on multiple conditions, you can use AND
and OR
to combine these conditions. Correct use of these two logical operators allows you to obtain the data you want more accurately.

Connect multiple conditions using AND
Use AND
when you want all conditions to be met. For example, you want to find users who are older than 30 years old and whose city is Beijing:

SELECT * FROM users WHERE age > 30 AND city = 'Beijing';
This query will only return records that satisfy both "age older than 30" and "city is Beijing".
- If one of the conditions does not hold, the entire record will not be selected.
- Multiple
AND
conditions are independent of each other, but they must be true to hit.
Use OR
to satisfy any condition
If you only need to satisfy any of multiple conditions, you can use OR
. For example, if you want to find a user whose city is Beijing or Shanghai:

SELECT * FROM users WHERE city = 'Beijing' OR city = 'Shanghai';
This statement will return to all users whose city is "Beijing" or "Shanghai".
- As long as one of the conditions is true, the entire line will be selected.
- Be careful to avoid unexpected results due to priority issues and add brackets if necessary.
Use AND
and OR
at the same time: Pay attention to priority
The priority of AND
in SQL is higher than that OR
, so pay attention to the logical order when mixing. For example:
SELECT * FROM users WHERE city = 'Beijing' OR city = 'Shanghai' AND age > 30;
The above sentence is actually equivalent to:
WHERE city = 'Beijing' OR (city = 'Shanghai' AND age > 30)
If you originally meant to check "(Beijing or Shanghai) and age is older than 30", you need to write it like this:
WHERE (city = 'Beijing' OR city = 'Shanghai') AND age > 30;
- In actual use, it is recommended to use brackets to clarify the logical relationship.
- When it is uncertain, you can break it into a subquery or use
IN
to simplify the expression.
A clearer way to write: replace multiple OR
with IN
When you want to match multiple values, you can use IN
to make the statement more concise and easy to read:
SELECT * FROM users WHERE city IN ('Beijing', 'Shanghai', 'Guangzhou');
This is much cleaner than writing multiple OR
and is easier to maintain.
Basically that's it. By using AND
and OR
reasonably, and controlling priority with brackets, you can write a clear and accurate SQL query.
The above is the detailed content of How to combine multiple conditions with AND and OR in a SQL query?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

OLTPisusedforreal-timetransactionprocessing,highconcurrency,anddataintegrity,whileOLAPisusedfordataanalysis,reporting,anddecision-making.1)UseOLTPforapplicationslikebankingsystems,e-commerceplatforms,andCRMsystemsthatrequirequickandaccuratetransactio

Toduplicateatable'sstructurewithoutcopyingitscontentsinSQL,use"CREATETABLEnew_tableLIKEoriginal_table;"forMySQLandPostgreSQL,or"CREATETABLEnew_tableASSELECT*FROMoriginal_tableWHERE1=2;"forOracle.1)Manuallyaddforeignkeyconstraintsp

To improve pattern matching techniques in SQL, the following best practices should be followed: 1. Avoid excessive use of wildcards, especially pre-wildcards, in LIKE or ILIKE, to improve query efficiency. 2. Use ILIKE to conduct case-insensitive searches to improve user experience, but pay attention to its performance impact. 3. Avoid using pattern matching when not needed, and give priority to using the = operator for exact matching. 4. Use regular expressions with caution, as they are powerful but may affect performance. 5. Consider indexes, schema specificity, testing and performance analysis, as well as alternative methods such as full-text search. These practices help to find a balance between flexibility and performance, optimizing SQL queries.

IF/ELSE logic is mainly implemented in SQL's SELECT statements. 1. The CASEWHEN structure can return different values ??according to the conditions, such as marking Low/Medium/High according to the salary interval; 2. MySQL provides the IF() function for simple choice of two to judge, such as whether the mark meets the bonus qualification; 3. CASE can combine Boolean expressions to process multiple condition combinations, such as judging the "high-salary and young" employee category; overall, CASE is more flexible and suitable for complex logic, while IF is suitable for simplified writing.

The method of obtaining the current date and time in SQL varies from database system. The common methods are as follows: 1. MySQL and MariaDB use NOW() or CURRENT_TIMESTAMP, which can be used to query, insert and set default values; 2. PostgreSQL uses NOW(), which can also use CURRENT_TIMESTAMP or type conversion to remove time zones; 3. SQLServer uses GETDATE() or SYSDATETIME(), which supports insert and default value settings; 4. Oracle uses SYSDATE or SYSTIMESTAMP, and pay attention to date format conversion. Mastering these functions allows you to flexibly process time correlations in different databases

The DISTINCT keyword is used in SQL to remove duplicate rows in query results. Its core function is to ensure that each row of data returned is unique and is suitable for obtaining a list of unique values ??for a single column or multiple columns, such as department, status or name. When using it, please note that DISTINCT acts on the entire row rather than a single column, and when used in combination with multiple columns, it returns a unique combination of all columns. The basic syntax is SELECTDISTINCTcolumn_nameFROMtable_name, which can be applied to single column or multiple column queries. Pay attention to its performance impact when using it, especially on large data sets that require sorting or hashing operations. Common misunderstandings include the mistaken belief that DISTINCT is only used for single columns and abused in scenarios where there is no need to deduplicate D

Create temporary tables in SQL for storing intermediate result sets. The basic method is to use the CREATETEMPORARYTABLE statement. There are differences in details in different database systems; 1. Basic syntax: Most databases use CREATETEMPORARYTABLEtemp_table (field definition), while SQLServer uses # to represent temporary tables; 2. Generate temporary tables from existing data: structures and data can be copied directly through CREATETEMPORARYTABLEAS or SELECTINTO; 3. Notes include the scope of action is limited to the current session, rename processing mechanism, performance overhead and behavior differences in transactions. At the same time, indexes can be added to temporary tables to optimize

The main difference between WHERE and HAVING is the filtering timing: 1. WHERE filters rows before grouping, acting on the original data, and cannot use the aggregate function; 2. HAVING filters the results after grouping, and acting on the aggregated data, and can use the aggregate function. For example, when using WHERE to screen high-paying employees in the query, then group statistics, and then use HAVING to screen departments with an average salary of more than 60,000, the order of the two cannot be changed. WHERE always executes first to ensure that only rows that meet the conditions participate in the grouping, and HAVING further filters the final output based on the grouping results.
