Tips for writing sql

Posted: November 27, 2012 in Database
Tags: , , , , , ,

These are the few points that need to be taken care of when we write sql statements. I furnish details upto my knowledge , any suggestions and improvements are most welcome.

1. Try to write sql in aligned format. Type of alignment differ from people to people . The alignment that i follow is

select
  a.field1,
  a.field2,
  b.field1,
  b.field2
from 
  table1 a,
  table2a
where
  a.fieldx=b.fieldx and
  a.fieldy=xxx and
  b.fieldz=ttt;

keywords align in the left side whereas the content will be a one tab space from the left margin. Alignment improves readability. Editing and making comparison can be done easily.

2. The next part is the order in which we use table. Try to keep the order descending. if table1 is bigger than table2 , then the order should be table1,table2.

3. As we follow the order for table names, we need to follow the order for conditions too. For example if table a is bigger than b then finish off all the conditions related to a and then start b and so on.

4. Be careful when you use alias. setting keywords as alias will end you in trouble.

Advertisements

Comments are closed.