SQL statements with equals vs in - sql

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:
large blocks of SQL don't need to be duplicated
we don't overuse dynamic SQL.
Example
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).

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".

Those two specific statements are equivalent to the optimizer (did you compare the execution plans?), but I think the more important benefit you get out of the latter is that
WHERE id = 1 OR id = 2 OR id = 3 OR id = 4 OR id = 5
Can be expressed as the following, much more concise and readable (but semantically equivalent to the optimizer) version:
WHERE id IN (1,2,3,4,5)
The problem is that when expressed as the latter most people think they can pass a string, like #list = '1,2,3,4,5' and then say:
WHERE id IN (#list)
This does not work because #list is a single scalar string, and not an array of integers.
For cases where you have a single value, I don't see how that "optimization" helps anything. You haven't written less SQL, you've actually written more. Can you outline in more detail how this is going to lead to less SQL?

Related

Oracle: Use only few tables in WHERE clause but mentioned more tables in 'FROM' in a jon SQL

What will happen in an Oracle SQL join if I don't use all the tables in the WHERE clause that were mentioned in the FROM clause?
Example:
SELECT A.*
FROM A, B, C, D
WHERE A.col1 = B.col1;
Here I didn't use the C and D tables in the WHERE clause, even though I mentioned them in FROM. Is this OK? Are there any adverse performance issues?
It is poor practice to use that syntax at all. The FROM A,B,C,D syntax has been obsolete since 1992... more than 30 YEARS now. There's no excuse anymore. Instead, every join should always use the JOIN keyword, and specify any join conditions in the ON clause. The better way to write the query looks like this:
SELECT A.*
FROM A
INNER JOIN B ON A.col1 = B.col1
CROSS JOIN C
CROSS JOIN D;
Now we can also see what happens in the question. The query will still run if you fail to specify any conditions for certain tables, but it has the effect of using a CROSS JOIN: the results will include every possible combination of rows from every included relation (where the "A,B" part counts as one relation). If each of the three parts of those joins (A&B, C, D) have just 100 rows, the result set will have 1,000,000 rows (100 * 100 * 100). This is rarely going to give the results you expect or intend, and it's especially suspect when the SELECT clause isn't looking at any of the fields from the uncorrelated tables.
Any table lacking join definition will result in a Cartesian product - every row in the intermediate rowset before the join will match every row in the target table. So if you have 10,000 rows and it joins without any join predicate to a table of 10,000 rows, you will get 100,000,000 rows as a result. There are only a few rare circumstances where this is what you want. At very large volumes it can cause havoc for the database, and DBAs are likely to lock your account.
If you don't want to use a table, exclude it entirely from your SQL. If you can't for reason due to some constraint we don't know about, then include the proper join predicates to every table in your WHERE clause and simply don't list any of their columns in your SELECT clause. If there's a cost to the join and you don't need anything from it and again for some very strange reason can't leave the table out completely from your SQL (this does occasionally happen in reusable code), then you can disable the joins by making the predicates always false. Remember to use outer joins if you do this.
Native Oracle method:
WITH data AS (SELECT ROWNUM col FROM dual CONNECT BY LEVEL < 10) -- test data
SELECT A.*
FROM data a,
data b,
data c,
data d
WHERE a.col = b.col
AND DECODE('Y','Y',NULL,a.col) = c.col(+)
AND DECODE('Y','Y',NULL,a.col) = d.col(+)
ANSI style:
WITH data AS (SELECT ROWNUM col FROM dual CONNECT BY LEVEL < 10)
SELECT A.*
FROM data a
INNER JOIN data b ON a.col = b.col
LEFT OUTER JOIN data c ON DECODE('Y','Y',NULL,a.col) = b.col
LEFT OUTER JOIN data d ON DECODE('Y','Y',NULL,a.col) = d.col
You can plug in a variable for the first Y that you set to Y or N (e.g. var_disable_join). This will bypass the join and avoid both the associated performance penalty and the Cartesian product effect. But again, I want to reiterate, this is an advanced hack and is probably NOT what you need. Simply leaving out the unwanted tables it the right approach 95% of the time.

Performance difference if first set of inner join is empty

I have to use 5 tables of my database to obtain data and I wrote a SQL query like this:
SELECT *
FROM A
INNER JOIN B ON A.id_b = B.id_b
INNER JOIN C ON B.id_c = C.id_c
INNER JOIN D ON D.id_d = C.id_d
INNER JOIN E ON E.id_e = D.id_e
WHERE A.column1 = somevalue
The columns I select doesn't matter for my explanation, but I require some columns of all tables to do the operation.
I'd like to know: If set A is empty according to the WHERE clause requirements, will it progress on the successive inner joins?
Yes and no and maybe. In all likelihood, the optimizer is going to choose an execution plan that starts with A, because you have filtering conditions in the WHERE clause.
Then, the subsequent JOINs are going to be really fast, because the SQL engine doesn't have to do much work to JOIN an empty set to anything else.
That said, there is no guarantee the the optimizer will start with the first table. So, this is really a happenstance, but a reasonable expectation given your filtering conditions. Also, the subsequent JOINs will be in the execution plan, but they will be fast, because each one will have one set that is empty.
You can try the following methods to optimize your query performance, however the actual result depends on many factors, and you have to test them to see whether they really work for your scenario or not, or which one works best:
Use stored procedure and parametrized somevalue instead of raw query;
Make sure there is an index on A.column1 and rebuild it regularly (clustered index is better if possible)
Use "with (Forceseek)" on table a; (assuming that the index on column1 is already created)
Use "OPTION (FAST 1)";
Store the result of table A to a temporary table first, then use the temporary table for the following script. (This method should be the most effective one in
most cases and table A is guaranteed to be executed first.)
Scripts will be like this:
SELECT *
INTO #A
FROM A
WHERE A.column1 = somevalue
SELECT *
FROM #A
INNER JOIN B ON A.id_b = B.id_b
INNER JOIN C ON B.id_c = C.id_c
INNER JOIN D ON D.id_d = C.id_d
INNER JOIN E ON E.id_e = D.id_e

Does the order of tables referenced in the ON clause of the JOIN matter?

Does it matter which way I order the criteria in the ON clause for a JOIN?
select a.Name, b.Status from a
inner join b
on a.StatusID = b.ID
versus
select a.Name, b.Status from a
inner join b
on b.ID = a.StatusID
Is there any impact on performance? What if I had multiple criteria?
Is one order more maintainable than another?
JOIN order can be forced by putting the tables in the right order in the FROM clause:
MySQL has a special clause called STRAIGHT_JOIN which makes the order matter.
This will use an index on b.id:
SELECT a.Name, b.Status
FROM a
STRAIGHT_JOIN
b
ON b.ID = a.StatusID
And this will use an index on a.StatusID:
SELECT a.Name, b.Status
FROM b
STRAIGHT_JOIN
a
ON b.ID = a.StatusID
Oracle has a special hint ORDERED to enforce the JOIN order:
This will use an index on b.id or build a hash table on b:
SELECT /*+ ORDERED */
*
FROM a
JOIN b
ON b.ID = a.StatusID
And this will use an index on a.StatusID or build a hash table on a:
SELECT /*+ ORDERED */
*
FROM b
JOIN a
ON b.ID = a.StatusID
SQL Server has a hint called FORCE ORDER to do the same:
This will use an index on b.id or build a hash table on b:
SELECT *
FROM a
JOIN b
ON b.ID = a.StatusID
OPTION (FORCE ORDER)
And this will use an index on a.StatusID or build a hash table on a:
SELECT *
FROM b
JOIN a
ON b.ID = a.StatusID
OPTION (FORCE ORDER)
PostgreSQL guys, sorry. Your TODO list says:
Optimizer hints (not wanted)
Optimizer hints are used to work around problems in the optimizer. We would rather have the problems reported and fixed.
As for the order in the comparison, it doesn't matter in any RDBMS, AFAIK.
Though I personally always try to estimate which column will be searched for and put this column in the left (for it to seem like an lvalue).
See this answer for more detail.
No it does not.
What i do (for readability) is your 2nd example.
No. The database should be determining the best execution plan based on the entire criteria, not creating it by looking at each item in sequence. You can confirm this by requesting the execution plan for both queries, you'll see they are the same (you'll find that even vastly different queries, as long as they ultimately specify the same logic, are often compiled into the same execution plan).
No there is not. At the end of the day, you are really just evaluating whether a=b.
And as the symmetric property of equality states:
For any quantities a and b, if a = b, then b = a.
so whether you check for (12)*=12 or 12=(12)* makes logically no difference.
If values are equal, join, if not, don't. And whether you specify it as in your first example or the second, makes no difference.
As many have said: The order does not make a difference in result or performance.
What I want to point out though is that LINQ to SQL only allows the first case!
Eg, following example works well, ...
var result = from a in db.a
join b in db.b on a.StatusID equals b.ID
select new { Name = a.Name, Status = b.Status }
... while this will throw errors in Visual Studio:
var result = from a in db.a
join b in db.b on b.ID equals a.StatusID
select new { Name = a.Name, Status = b.Status }
Which throws these compiler errors:
CS1937: The name 'name' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.
CS1938: The name 'name' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
Though not relevant in standard SQL coding, this might be a point to consider, when accustoming oneself to either one of those.
Read this
SqlServer contains an optimisation for situations far more complex than this.
If you have multiple criteria stuff is usually lazy evaluated (but I need to do a bit of research around edge cases if any.)
For readability I usually prefer
SELECT Name, Status FROM a
JOIN b
ON a.StatusID = b.ID
I think it makes better sense to reference the variable in the same order they were declared but its really a personal taste thing.
The only reason I wouldn't use your second example:
select a.Name, b.Status
from a
inner join b
on b.ID = a.StatusID
Your user is more likely to come back and say 'Can I see all the a.name's even if they have no status records?' rather than 'Can I see all of b.status even if they don't have a name record?', so just to plan ahead for this example, I would use On a.StatusID = b.ID in anticipation of a LEFT Outer Join. This assumes you could have table 'a' record without 'b'.
Correction: It won't change the result.
This is probably a moot point since users never want to change their requirements.
nope, doesn't matter. but here's an example to help make your queries more readable (at least to me)
select a.*, b.*
from tableA a
inner join tableB b
on a.name=b.name
and a.type=b.type
each table reference is on a separate line, and each join criteria is on a separate line. the tabbing helps keep what belongs to what straight.
another thing i like to do is make my criteria in my on statements flow the same order as the table. so if a is first and then b, a will be on the left side and b on the right.
ERROR: ON clause references tables to its right (php sqlite 3.2)
Replace this
LEFT JOIN itm08 i8 ON i8.id= **cdd01.idcmdds** and i8.itm like '%ormit%'
LEFT JOIN **comodidades cdd01** ON cdd01.id_registro = u.id_registro
For this
LEFT JOIN **comodidades cdd01** ON cdd01.id_registro = u.id_registro
LEFT JOIN itm08 i8 ON i8.id= **cdd01.idcmdds** and i8.itm like '%ormit%'

SQL (any) Request for insight on a query optimization

I have a particularly slow query due to the vast amount of information being joined together. However I needed to add a where clause in the shape of id in (select id from table).
I want to know if there is any gain from the following, and more pressing, will it even give the desired results.
select a.* from a where a.id in (select id from b where b.id = a.id)
as an alternative to:
select a.* from a where a.id in (select id from b)
Update:
MySQL
Can't be more specific sorry
table a is effectively a join between 7 different tables.
use of * is for examples
Edit, b doesn't get selected
Your question was about the difference between these two:
select a.* from a where a.id in (select id from b where b.id = a.id)
select a.* from a where a.id in (select id from b)
The former is a correlated subquery. It may cause MySQL to execute the subquery for each row of a.
The latter is a non-correlated subquery. MySQL should be able to execute it once and cache the results for comparison against each row of a.
I would use the latter.
Both queries you list are the equivalent of:
select a.*
from a
inner join b on b.id = a.id
Almost all optimizers will execute them in the same way.
You could post a real execution plan, and someone here might give you a way to speed it up. It helps if you specify what database server you are using.
YMMV, but I've often found using EXISTS instead of IN makes queries run faster.
SELECT a.* FROM a WHERE EXISTS (SELECT 1 FROM b WHERE b.id = a.id)
Of course, without seeing the rest of the query and the context, this may not make the query any faster.
JOINing may be a more preferable option, but if a.id appears more than once in the id column of b, you would have to throw a DISTINCT in there, and you more than likely go backwards in terms of optimization.
I would never use a subquery like this. A join would be much faster.
select a.*
from a
join b on a.id = b.id
Of course don't use select * either (especially never use it when doing a join as at least one field is repeated) and it wastes network resources to send unnneeded data.
Have you looked at the execution plan?
How about
select a.*
from a
inner join b
on a.id = b.id
presumably the id fields are primary keys?
Select a.* from a
inner join (Select distinct id from b) c
on a.ID = c.AssetID
I tried all 3 versions and they ran about the same. The execution plan was the same (inner join, IN (with and without where clause in subquery), Exists)
Since you are not selecting any other fields from B, I prefer to use the Where IN(Select...) Anyone would look at the query and know what you are trying to do (Only show in a if in b.).
your problem is most likely in the seven tables within "a"
make the FROM table contain the "a.id"
make the next join: inner join b on a.id = b.id
then join in the other six tables.
you really need to show the entire query, list all indexes, and approximate row counts of each table if you want real help

Tool to find out why an SQL select does not return any data

Is there a tool which tells you (or gives you a hint) why a particular select statement dose not return any rows given the current data in your database.
eg if you had the following 4 table join
select *
from a, b, c, d
where a.b_id = b.id
and b.c_id = c.id
and c.d_id = d.id
If there were rows which satisfied the conditions a.b_id = b.id also rows which satisfied b.c_id = c.id but no rows which satisfied the condition c.d_id = d.id it would highlight c.d_id = d.id as the problem.
Ie it would brake up the where clause and find out which of the sub conditions returned true and highlight those which do not return true.
It would not work well for complex querys but many select statements are simple joins over lots of tables.
This would be useful when creating test data to exercise a peace of application code or debugging a problem with a live system.
Graphical explain tools (that show the plan of the actual exiection path) come close but they show too much info and do not highlight the missing link in the select stament.
I am using postgres, sqllight and mysql but would be interested in how tools for other databases/platforms work.
Im also interested in any manula techniques.
Does anybody else have this problem?
Would anybody be interested if I wrote such a tool?
I never have this problem, but I also use explicit joins so it's usually as simple as running parts of the query until I find out which one is restricting my results incorrectly.
In your case
SELECT *
FROM a -- First run just to here, are there records?
INNER JOIN b
ON a.b_id = b.id -- Then run just to here, is it OK?
INNER JOIN c
ON b.c_id = c.id -- Then run just to here, is it OK?
INNER JOIN d
ON c.d_id = d.id -- Then run just to here, is it OK?
There isn't a tool to do this per se, because as other posters have pointed out, it's simple enough to just highlight successively larger portions of the query (if you have it formatted well, with one ANDed clause per line) and see how many records are returned. Making the joins explicit is critical here, because most likely, THAT is where you're losing rows, not with your WHERE clauses.
I can see it being an interesting mini-tool, though, to take a SQL query with n predicates as input and return a graph of the count result after appending each separate AND clause to the trunk of the statement ... something like:
part count
-------------- -------------
TRUNK 100
AND clause 1 90
AND clause 2 85
... ...
AND clause n 20
SQL Management Studio might offer ways to plug a little tool like this in as a macro, it might be worth exploring. Post it here if you do! :)
This will get you started...
select count(1) from a, b where a.b_id = b.id
select count(1) from b, c where b.c_id = c.id
select count(1) from c, d where c.d_id = d.id
Note that you are using AND so the overlap of the above queries may not be what you expect.
OR
Using MS-SQL Server Management Studio...
Display the "Execution Plan" and mouse over the nodes for "Actual Number of Rows".
You should be able to study the execution plan (if you are using SQL Server, otherwise a similar feature in your database) to see where the joins produce an empty set.
I would normally use the approach described by Cade Roux
But theoretically you could use the following query:
SELECT a.id, b.id, c.id, d.id
FROM a
LEFT JOIN b
ON a.b_id = b.id
LEFT JOIN c
ON b.c_id = c.id
LEFT JOIN d
ON c.d_id = d.id
The rows that return all NULL values would point you to the table without matching data.
E.g. if all c.id were null that would mean that there was no matching records in c table.
Of course all other tables that depend on the records in table c would have no matching records as well.
So the first column with all nulls will be the one to start with.