tags:

views:

147

answers:

5
+5  Q: 

SQL Code Smells

Hi Team,

Could you please list some of the bad practices in SQL, that novice people do?

I have found the use of "WHILE loop" in scenarios which could be resolved using set operations.

Another example is inserting data only if it does not exist. This can be achieved using LEFT OUTER JOIN. Some people go for "IF"

Any other thoughts?

Edit: What I am looking for is specific scenarios (as mentioned in the question) that could be achieved using SQL without using procedural constructs

Thanks

Lijo

+6  A: 

Here are some I have seen:

  • Using cursors instead of equivalent (and faster) set operations (joins etc).
  • Dynamic SQL for everything.
  • Code that is open to SQL Injection attacks.
  • Full outer joins even when they are not needed.
  • Huge stored procedures (hundreds/thousands of lines).
  • No comments.
Oded
(n)Hibernate does outer joins by default -_-
HeavyWave
+1  A: 

Personally for me: anything that is not a plain INSERT, UPDATE, DELETE or SELECT statement

I don't like logic in SQL.

Tungano
That's ironic, given that SQL is founded on predicate logic. Perhaps you should qualify this statement (Did you mean, "No cursors", or something like that?).
Marcelo Cantos
I guess you haven't worked with large datasets in a corporate environment then. Not that I disagree entirely, but sometimes its the best solution.
James Westgate
I think, logic inside SQL is inevitable when working with Reporting.
Lijo
code logic is fine within SQL, I think business logic in SQL is bad...now you're going to ask for an example: Logic normally involves IF statements for example which some people try and avoid in SQL, we for instance convert Guid.Empty values {00000....} to NULL as part of our code generated SQL scripts
Mark Redman
A: 

My biggest beef here is definitely repetitive SQL. As an example, multiple stored procedures that perform the exact same joins but different filters.

Using Views in such cases can make your database MUCH easier to look at and work with

LorenVS
Could you please give an example that can only be achieved using repetitive queries, if we are using Stored Proecure? [The same can be achieved without repetition when used VIEWS]
Lijo
+2  A: 

Placing ODBC or dynamic SQL calls all over the code.

Often it is better to define a data abstraction layer that provides access to the databases. All the SQL code can hide in that layer. This often avoids replication of similar queries, and makes changing data models easier to do.

Ira Baxter
A: 

1) Creating vendor-specific SQL, when generic SQL would do. 2) Creating tables dynamically at runtime (other than TEMPORARY tables). Among other problems, letting your application code have table create privs is a security risk.

Bryce