Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the OR operator - SQL Server

I'm reading documentation about OR operator, it says:

Most of the better DBMS will not even evaluate the second condition in an OR WHERE clausule if the first condition allready been met. (If the first condition is met, the row would be retrieved regardless the second condition).

SELECT prod_code, prod_price
FROM Articles
WHERE Code = '1' OR Code = '2'

Does this mean by documentation if Code = '1' query will return all values with '1' ignoring second condition WHERE Code = '2'.

I've tested this on SQL Server and it returns all values with 1 and all values with 2, so actually 2 rows.

So I'm bit confused here.

like image 971
rokie12234 Avatar asked May 12 '26 15:05

rokie12234


2 Answers

The statement is simply about optimization, something called "short-circuiting". It is saying that the comparison to 2 is not done when 1 matches the condition. Because it does not matter what the comparison to 2 evaluates to.

You seem to be a bit confused by saying

if Code = '1' query will return all values with '1' ignoring second condition WHERE Code = '2'.

Code is a column in each row, not an overall value that is constant for all rows. (If so, it would be @Code in SQL Server, rather than @Code.)

For your example, though, you should be using IN:

WHERE Code IN ('1', '2')

If Code is numeric, the comparison values should not have single quotes.

like image 162
Gordon Linoff Avatar answered May 15 '26 05:05

Gordon Linoff


Ripped from my original comment: It means that if a row fulfils the condition of Code = 1 then it won't evaluate the clause Code = 2 for that row. That doesn't mean it stops checking the rest of the rows. The RDBMS will still return every row that fulfils either of those requirements.

So if we have a table like:

CREATE TABLE YourTable (ID int IDENTITY,
                        Code int,
                        SomeValue varchar(10));
INSERT INTO YourTable (Code,SomeValue)
VALUES (1,'asdkjsa'),
       (1,'asdojsa'),
       (2,'saohdsald'),
       (3,'sdfkjhsadk'),
       (3,'asdkjsagd');

If you were to run the query SELECT * FROM YourTable WHERE Code = 1 OR Code = 2; then for the second 1st 2 rows, the OR Code = 2 wouldn't be evaluated, as Code = 1 has already evalutated true.

However, rather than using WHERE Code = 1 OR Code = 2 you could use the more succinct operator IN: WHERE Code IN (1,2).

like image 31
Larnu Avatar answered May 15 '26 04:05

Larnu