Writing complex SQL queries with AND and OR operators

For data manipulation and data retrieval in SQL databases, it is necessary to understand and properly use SQL operators, such as arithmetic, comparison, logical, and other types. A solid understanding of their basics makes it easier for users to perform different operations, including mathematical calculations, comparisons, string manipulations, and data retrieval. In addition, getting an idea of how conditional logic works in data retrieval is important for efficient database querying. Conditional logic, primarily used in WHERE clauses, lets you filter and group data based on specific conditions, create dynamic queries, and modify data up to your requirements.

Read on to get into basics of the AND and OR SQL operators and learn how they work on the examples using dbForge Studio for SQL Server.

Understanding SQL operators

A SQL operator is a keyword or symbol that you can use to establish a condition in a WHERE clause to filter result data. The query with the operator returns the result based on its functionality. Let us now have a look at the AND and OR operators and how they are used.

Basics of the AND operator

The AND operator is a logical operator to combine multiple conditions in the WHERE clause. It allows you to filter rows based on the specified conditions in the WHERE clause, which should be all true for each row in the result set.

The syntax of the AND operator is as follows:

SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;

where:

  • column1 and column2 specify the columns you want to retrieve data from. Multiple column names should be separated by commas. To select all columns, use an asterisk (*) instead of listing individual column names.
  • table_name is the name of the table whose data you want to display in the result.
  • condition1, condition2, and condition3 are the conditions according to which the data result set will be filtered.

How does it work? The AND operator evaluates multiple conditions in a WHERE clause and returns only those rows that meet all the specified criteria. If any condition does not satisfy the condition and returns false, the row is excluded from the result set.

Let us illustrate several examples of using the AND operator.

Suppose we want to retrieve products of the product model #25, which have a list price greater than $500. To combine these conditions and get results according to the specified criteria, we'll execute the SELECT query with the AND operator in the WHERE clause:

SELECT Name, ListPrice
FROM Production.Product
WHERE ProductModelID = 25 AND ListPrice > 500;

In the output, we'll see that only three products match all the specified conditions.

Combine conditions using the AND operator

Let us now consider a scenario where we want to display a list of sales orders from the Sales.SalesOrderHeaderNew table placed in 2023 by customers with credit ratings of Good or Excellent. To do this, we use AND to combine conditions and OR to include multiple credit ratings:

SELECT
  SalesOrderID
 ,OrderDate
 ,CreditRating
FROM SalesOrderHeaderNew
WHERE YEAR(OrderDate) = 2023 AND (CreditRating = 'Good' OR CreditRating = 'Excellent');

In the output, the results grid lists the orders that fit all the conditions specified in the WHERE clause.

Combine conditions using the AND operator

As you can see, these examples demonstrate how the AND operator can be used to create precise queries in the AdventureWorks2022 database, allowing for efficient and accurate data retrieval based on multiple conditions simultaneously.

Basics of the OR operator

The OR operator is a logical operator to combine multiple conditional expressions in a WHERE or HAVING clause. It allows you to filter rows from a table where at least one of the specified conditions is true.

The syntax of the AND operator is as follows:

SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;

where:

  • column1 and column2 specify the columns you want to retrieve data from. Multiple column names should be separated by commas. To select all columns, use an asterisk (*) instead of listing individual column names.
  • table_name is the name of the table whose data you want to display in the result set.
  • condition1, condition2, and condition3 are the conditions based on which the data result set will be filtered.

How does it work? The OR operator evaluates multiple conditions in a WHERE or HAVING clause, identifying rows where at least one of the conditions set with the OR operator is true.

Let us see the OR operator in practice. For example, we want to fetch a list of orders that meet alternative conditions:

SELECT * FROM orders
WHERE order_date >= '2023-01-01' OR order_date <= '2023-12-31';

In the results grid, the orders matching one of the conditions are displayed.

Use the OR operator in a WHERE clause

Comparing AND and OR operators

While the AND and OR operators may appear similar, they differ in their logic. The AND operator requires that each row in the result set must satisfy all the specified conditions simultaneously, while the OR operator allows for at least one condition to be true for each row the query returns.

To illustrate the difference between operators, let us consider the following scenarios.

Example with the AND operator

We want to retrieve all products from the 'Bikes' category with a list price greater than $500. To do this, we'll use the AND operator to combine these conditions:

Comparing SQL operators - AND

Example with the OR operator

Now, we want to get a list of products that belong to the 'Bikes' category or that have a list price greater than $500. To do this, we'll use the OR operator to specify these conditions:

Comparing SQL operators - OR

If we look at the results grids of both queries, we'll see a difference in the total number of products the queries return. In the first query with the AND operator, only products from the 'Bikes' category with a list price greater than $500 are displayed. In the contrast, the second query, using the OR operator, retrieves products from either the 'Bikes' category or those with a list price exceeding $500, which might also include products from other categories.

Try it yourself with dbForge Studio

As you have noticed, we used dbForge Studio for SQL Server to demonstrate examples with operators. It is the ultimate IDE for database development, management, administration, and deployment. This tool equips you with all the necessary features to configure your SQL development environment and enhance your database experience and productivity.

As a robust alternative to SSMS, dbForge Studio facilitates you to write errorless and accurate queries, from simple to complex, due to its IntelliSense-style code completion features, such as context-based autocompletion, suggestion of keywords, objects, and T-SQL code, code formatting and SQL refactoring. Moreover, users can version-control databases and manage changes in version control systems, including Subversion, Team Foundation Server, Git, Perforce, Mercurial, and SourceGear Vault. For those frequently involved in data migration tasks, the schema and data comparison and synchronization tools, and data export/import tools simplify daily operations and save users' time. In addition to these versatile features, the Studio offers a lot of other advanced functionalities to improve your productivity, performing all these tasks in a visual and intuitive interface.

To get a deeper understanding about the Studio features and tools, watch this video.


Do you want to see the Studio in action? Download a trial version of the tool and install it to enjoy all its cutting-edge features and functionalities within a free 30-day period.

Advanced use cases

Now, we'll have a look at more complex cases to use the AND and OR operators in SQL.

Combining the AND and OR operators

Using the AND and OR operators simultaneoulsy allows you to create complex queries to more accurately filter data results based on multiple criteria. Still, in such scenarios, you can add parentheses which help in specifying the logical order of operations within a query. So, the parentheses instruct SQL Server which condition to perform the first, then second, and so on, which prevents ambiguity and produces accurate results.

Parentheses are used to enclose groups of conditions, for example, AND and OR operators, within a WHERE clause. The basic syntax would be as follows:

SELECT column1, column2, ...
FROM table_name
WHERE (condition1 AND condition2) OR (condition3 AND condition4) OR condition5;

where:

  • column1 and column2 specify the columns you want to retrieve data from. Multiple column names should be separated by commas. To select all columns, use an asterisk (*) instead of listing individual column names.
  • table_name is the name of the table whose data you want to display in the result.
  • (condition1 AND condition2), (condition3 AND condition4) are groups of conditions using parentheses to define the evaluation order.
  • condition5 is not grouped with any other conditions but is combined with them through the OR operator.
  • Each group represents a set of conditions that need to be satisfied together.
  • The OR operator is used to combine these groups of conditions, indicating that if any of the groups evaluates to true, the row will be included in the result set.

In other words, the query retrieves rows from the specified table where at least one of the following conditions is true:

  • Both condition1 and condition2 are true, OR
  • Both condition3 and condition4 are true, OR
  • condition5 is true.

Since there may be multiple conditions in complex queries, parentheses allow for nesting conditions within each other, creating hierarchical structures to precisely define the desired criteria.

Finally, using parentheses makes queries easier to understand and maintain, especially when dealing with complicated logic involving several conditions.

For example, we need to see orders whose total sales are greater than $1000 and that were placed by customers from either New York or Los Angeles. To do this, execute the following SELECT query using parentheses to nest conditions:

SELECT *
FROM orders
WHERE total_amount > 1000 AND (city = 'New York' OR city = 'Los Angeles');

In the result, the SQL query retrieves all columns from the orders table where two conditions are met:

  • total_amount > 1000 condition filters orders where the total amount greater than $1000.
  • (city = 'New York' OR city = 'Los Angeles') condition filters orders that were made either in New York or Los Angeles. The parentheses ensure that this condition is evaluated as a single unit and allow the query to return orders from any of the specified city.
  • The AND operator here combines these two conditions, which must be true for each row in the result set. Therefore, the query retrieves orders whose total amount is greater than $1000, and the city is either 'New York' or 'Los Angeles'.
Combining AND and OR operators - OR

Let us have a look at another example. First, execute the following SELECT statement:

SELECT *
FROM products
WHERE (category = 'Electronics' AND price > 500) OR category = 'Clothing';

In the output, the query returns all columns from the products table where at least one of the following conditions is true:

  • (category = 'Electronics' AND price > 500) filters products that belong to the 'Electronics' category and whose price is greater than $500. The AND operator ensures that both conditions are true for each product in the results grid.
  • OR category = 'Clothing' selects products with the 'Clothing' category. Since this condition is not enclosed in parentheses, it acts independently of the first condition.
  • The OR operator here combines these conditions, notifying that if any of the conditions is considered to be true, the product will be included in the results grid. Therefore, the query retrieves products that either belong to the 'Electronics' category and have a price greater than $500, or any product that belong to the 'Clothing' category.
Combining AND and OR operators - OR

Operator precedence and evaluation order

Order precedence defines which operations happen first when there are multiple conditions in an expression. For instance, arithmetic operators, such as division and multiplication, hold higher precedence compared to addition and subtraction. Comparison operators, such as equal and not equal, have higher precedence over logical operators, such as AND and OR. Therefore, it is important to understand operator precedence when working with complex queries having multiple conditions. If you do not explicitly group conditions in parentheses to get the required result, SQL Server will adhere to the default precedence rules. For example, if the query contains arithmetic and logical operators in the WHERE clause without using parentheses, SQL Server may evaluate logical operators first and then arithmetic ones.

If you do not want to face the undesired results, consider the following when using operators in complex queries:

  • Operators with higher precedence are evaluated before operators with lower precedence. For example, multiplication happens before addition.
  • Parentheses can be used to change the default order in the expression. For example, in the expression - "(3 + 5) * 2", the addition is done first because of the parentheses.
  • When logical and arithmetic operators are combined in a query, enclosing logical conditions in parentheses ensures they are solved first before the arithmetic operations.

So, understanding operator precedence and using parentheses to control the evaluation order can ensure accurate results, efficient SQL queries, and better query performance.

Common pitfalls

You should also be aware of potential issues that may occur when using operators and parentheses in SQL queries:

  • Overusing parentheses or omitting them when they are needed may alter the logic of your query and lead to unexpected results. So, use parentheses carefully to make sure your query works the way you want it to.
  • SQL follows predefined rules for operator precedence, where specific operators get done first in a query before others. Ignoring these rules might cause wrong behavior in queries. For instance, forgetting to use parentheses when required may result in expressions being calculated in a different way than you meant. So, understanding the precedence of operators will ensure the proper evaluation order.

Thus, following best practices for using parentheses and remembering about operator precedence will guarantee expected behavior and accurate results returned by SQL queries.

Further learning

The following guides can be helpful when working with SQL queries:

Conclusion

To sum it up, understanding the AND and OR operators is important. By learning how to use these operators, users can create more accurate and complex queries, retrieve specific data results, and perform advanced data filtering. For better user experience, dbForge Studio for SQL Server offers powerful tools not only to easily work with SQL operators in queries but also perform other database-related tasks. So, get ready to dive in, download dbForge Studio, and explore the world of SQL!