SQL Formatting

I'm tired of seeing poorly formatted SQL statements. I used to be a poor offender of this, but I have seen the light. I'm over the whole "stuff it all into one line" mentality. Less lines is not always better. I've recently turned my attention to my SQL formatting.

Have you ever seen some SQL that looked like this?

select * from my_table where my_primary_key=72;

Of course you have, now how about something like this?

select column_1,column_2,column_3 from my_table, my_other_table where my_primary_key=72 
AND my_table.my_primary_key=my_other_table.my_primary_key;

It's pretty damn unreadable right? Does this look better to you?

SELECT
	column_1,
	column_2,
	column_3 
FROM
	my_table,
	my_other_table 
WHERE
	my_primary_key=72 
	AND
	my_table.my_primary_key=my_other_table.my_primary_key;

SQL is just like any programming language. Readability helps maintainability. From this day forward I've decided to make sure that I do a good job of formatting and *gasp* commenting my SQL.

  • http://www.theicecap.net Articus Penwgin

    Strangely enough i’ve come to my own senses and formatted my SQL in this, pretty much exact way for the last couple of weeks!

    It really does help with debugging, as Mysql gives you a line on which the error occurred. When an error does occur you already know its exact place.

    I found your site through the Jquery mailing list and your jquery plug-in looks to be a very useful widget. I look forward to seeing later versions :)