How to Format SQL Queries: Best Practices

Here’re the best practices to format SQL query. You need hands-on experience to format SQL query correctly. Experience is the prime thing to format. You can understand SQL query quickly. Often software developers miss the formatting technique.

SQL Formatting Best Practices

1. Indentation

  • 1. Wrong Format

2. Where to put commas in SQL Query

Select School,
       College,
       University,
From CollegeTable;
  • 2. Correct Format

Select School
       ,College,
       ,University
From CollegeTable; 

The Benefits

The commas ‘,’ in left ending is good practice. The reason is you can spot error quickly.

3. Sort Correctly

  • 3. Correct Way of Sorting

To sort the result, you need to use ‘ORDER BY’. The default is Ascending. If you give number in ORDER BY, it sorts that number column.

Example is ORDER BY 2, means, it sorts the result based on second column.

All the NULL values placed lost during Ascending Sort. The DESC is for Descending sort.

4. Major Vs. Minor Sort

  • 4. Major Vs Minor Sort

If you mentions two columns in ORDER BY, The sorting on FIRST column is MAJOR sort. The sort on SECOND column is called Minor sort.

  • The ORDER BY clause sorts the result based on Alphabetical Order.
  • To carry flexible sorting, you can use CASE in ORDER BY. So that you can sort based on CASE Condition.

5. Use Alias to Simplify Naming

  • 5. Alias – rather than Column Name

You can use alias for actual column names. Example is ‘School S’. S is here Alias. So that you can save time and identify quickly during debugging.

SQL Elements

  1. Column Name
  2. Data Types
  3. Constraints

Make sure that, all the SQL elements must be formatted Correctly. So that you can trace error easily.

Example of neatly formatted SQL

CREATE TABLE CUSTOMER (
   CustomerID     INTEGER          NOT NULL,
   FirstName      CHAR (15),
   LastName       CHAR (20)        NOT NULL,
   Street         CHAR (25),
   City           CHAR (20),
   State          CHAR (2),
   Zipcode        CHAR (10),
   Phone          CHAR (13) ) ;

Recent Posts

References

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.

Comments are closed.