Guest editorial: SQL Code Metrics

,

This editorial was originally published on Feb 17, 2009. It is being re-published as Steve is at SQL in the City in London today. The world has changed a lot and there are better tools, like SQL Prompt with code analysis to help with the issues discussed here.

SQL has a wonderful way of teaching us humility. Just when we think we have it sussed, we realise that there are better ways of doing it. I've never found a routine that can't be improved in some way; particularly in my own work. Writing good SQL code is a fascinating activity, a constant fight against hasty assumptions, outdated rules, and learned procedural programming practices. SQL is very different from any other type of programming.

This truth of this was brought home to me sharply the other day whilst reading about 'code smells' and quality metrics in C#. How wonderful it would be, I thought, if we could use the same techniques in order to detect 'smelly' SQL code in a database system. All we'd need to do is to check on the complexity of the code, the number of lines of code in a procedure, the number of SQL Statements, and possibly the complexity of the execution plan.

The only tool I've found that makes some of this available is SQLTAC. However, a lot more is attainable. For example, we could check for an over-reliance on cursors, the use of the * to insert into a table, the presence of SQL Statements that consistently take a long time to execute, code without comments or documentation, over-use of table variables, tables without a primary key, over-denormalized tables, and so on. It would be deeply satisfying to be able to produce a graphical representation of TSQL code quality, to wave in front of some poor programmer's face when you're checking his work!

Just as quickly as the thought had occurred to me, however, I dismissed it. The trouble is that when I supervise a programmer who is learning SQL, I sometimes learn new ideas that come from a fresh mind being applied to old problems. The code may, in general, stink, but the new ideas are priceless. If we apply 'quality metrics' and 'best practices' without applying our own judgement and intuition, we run the risk of ossifying rules that are merely intended to be guides. Code metrics are a good servant but a very poor master.

Phil Factor.

Rate

5 (2)

Share

Share

Rate

5 (2)