How to format SQL Query to spot errors easily

Posted by

It needs practice to write SQL query correctly. I mean, the experienced developer write in correct format. So that other developers can understand quickly. Essentially, the correct format helps you spot the error quickly.

Very often software developers miss the formatting technique.

In this post I am sharing some SQL formatting Techniques or best practices

Indentation

  • Wrong Format

Where to put commas in SQL Query

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

Select School
       ,College,
       ,University
From CollegeTable; 

The Benefits

The commas ‘,’ in left is good practice. You can spot error in SQL Query quickly.

Sorting Syntax

  • 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.

  • 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.

Use Alias to Simplify Naming

  • 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

Top References to Format SQL

One comment

Comments are closed.