Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding unused join in a SQL query

I am currently maintaining a significant number of SQL queries. Some of them are created by copy/paste operations, then removing unnecessary fields and sometimes forgetting to remove the tables where these fields come from.

I am looking for a tool (or anything apart from eyes+brain) that, given a SQL query, would analyze which of the joined tables have no field selected in the SELECT part.

Do you know of such a tool?

Thank you

like image 701
Johann Blais Avatar asked Apr 06 '11 14:04

Johann Blais


People also ask

How do you know when to use LEFT join?

You'll use INNER JOIN when you want to return only records having pair on both sides, and you'll use LEFT JOIN when you need all records from the “left” table, no matter if they have pair in the “right” table or not.

How do I find unused views in SQL Server?

Using SQL Server Profiler (or SQL Server Extended Events and/or Auditing) to 'trace' or watch a SQL Server for a given amount of time, and then correlate a list of recently used/accessed objects against a full list of objects in a given database to get a feel for what hasn't been used in a while.


1 Answers

Hypothetically a tool could exist but it would only be guaranteed to be correct if all the following criteria where met for said join

  • Its A LEFT or OUTER JOIN or an INNER JOIN where the cardinality where known to be 1-1 And...
  • Its Not Referenced in a SELECT, HAVING, GROUP BY or WHERE and...
  • It is not a JOIN to function that has a side effect...

Probably why there's no deterministic warnings in SQL parsers the way there is for let's say an unused variable in C#. But it might be worth while to create a SQL checker that looks for some of these conditions and lets the user know that there's a possibility for optimization here.

like image 87
Conrad Frix Avatar answered Nov 14 '22 21:11

Conrad Frix