Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql statements with equals vs in

Say that someone came up to you and said we're going to cut down the amount of SQL that we write by replacing equals with IN. The use would be both for single scalar values and lists of numbers.

SELECT *    FROM table   WHERE id = 1 

OR

SELECT *    FROM table   WHERE id IN (1) 

Are these statement equivalent to what the optimizer produces?

This looks really simple on the surface, but it leads to simplification for two reasons: 1. large blocks of SQL don't need to be duplicated, and 2. we don't overuse dynamic SQL.

This is a contrived example, but consider the following.

select a.* from tablea a  join tableb b on a.id = b.id join tablec c on b.id2 = c.id2 left join tabled d on c.id3 = c.id3 where d.type = 1 

... and the same again for the more than one case

select a.* from tablea a  join tableb b on a.id = b.id join tablec c on b.id2 = c.id2 left join tabled d on c.id3 = c.id3 where d.type in (1,2,3,4) 

(this isn't even a large statement)

conceivably you could do string concatenation, but this isn't desirable in light of ORM usage, and dynamic SQL string concatenation always starts off with good intentions (at least in these parts).

like image 930
sgtz Avatar asked Feb 28 '12 04:02

sgtz


People also ask

How use greater than or equal to in SQL query?

In SQL, you can use the >= operator to test for an expression greater than or equal to. Let's use the same customers table as the previous example. In this example, the SELECT statement would return all rows from the customers table where the customer_id is greater than or equal to 6000.

Does SQL USE ==?

The sql equal operator is used to check whether two expressions are equal or not. If it's equal, the condition will be true and will return matched records. The sql not equal operator is used to check whether two expressions are equal or not.

Is != Equivalent to <> in SQL?

Difference between SQL Not Equal Operator <> and != to do inequality test between two expressions. Both operators give the same output. The only difference is that '<>' is in line with the ISO standard while '!= ' does not follow ISO standard.


1 Answers

The two will produce the same execution plan - either a table scan, index scan, or index seek, depending on if/how you have your table indexed.

You can see for yourself - Displaying Graphical Execution Plans (SQL Server Management Studio) - See the section called "Using the Execution Plan Options".

like image 86
Jeremy Wiggins Avatar answered Oct 07 '22 03:10

Jeremy Wiggins