Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Applies to:
SQL Server
To link conditions with OR
and give them precedence over conditions linked with AND
, you must repeat the AND
condition for each OR
condition.
For example, imagine that you want to find all employees who have been with the company more than five years and have lower-level jobs or are retired. This query requires three conditions, a single condition linked to two additional conditions with AND
:
Employees with a hire date earlier than five years ago, and
Employees with a job level of 100 or whose status is "R" (for retired).
The following procedure illustrates how to create this type of query in the Criteria pane.
Combine conditions when OR has precedence
In the Criteria Pane (Visual Database Tools), add the data columns you want to search. If you want to search the same column using two or more conditions linked with
AND
, you must add the data column name to the grid once for each value you want to search.Create the conditions to be linked with
OR
by entering the first one into the Filter grid column and the second (and subsequent ones) into separate Or... columns. For example, to link conditions withOR
that search thejob_lvl
andstatus
columns, enter= 100
in the Filter column forjob_lvl
and= 'R'
in the Or... column forstatus
.Entering these values in the grid produces the following
WHERE
clause in the statement in the SQL pane:WHERE (job_lvl = 100) OR (status = 'R')
Create the
AND
condition by entering it once for eachOR
condition. Place each entry in the same grid column as theOR
condition it corresponds to. For example, to add anAND
condition that searches thehire_date
column and applies to bothOR
conditions, enter< '1/1/91'
in both the Criteria column and the Or... column.Entering these values in the grid produces the following
WHERE
clause in the statement in the SQL pane:WHERE (job_lvl = 100) AND (hire_date < '01/01/91') OR (status = 'R') AND (hire_date < '01/01/91')
Tip
You can repeat an
AND
condition by adding it once, and then using the Cut and Paste commands from the Edit menu to repeat it for otherOR
conditions.
The WHERE
clause created by the Query and View Designer is equivalent to the following WHERE
clause, which uses parentheses to specify the precedence of OR
over AND
:
WHERE (job_lvl = 100 OR status = 'R') AND
(hire_date < '01/01/91')
Note
If you enter the search conditions in the format shown immediately above in the SQL Pane (Visual Database Tools), but then make a change to the query in the Diagram or Criteria panes, the Query and View Designer recreates the SQL statement to match the form with the AND
condition explicitly distributed to both OR
conditions.