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
Where to put commas in SQL Query
Select School, College, University, From CollegeTable;
Select School ,College, ,University From CollegeTable;
The commas ‘,’ in left is good practice. You can spot error in SQL Query quickly.
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.
- Column Name
- Data Types
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) ) ;
- 12 Frequently Asked Python Interview Questions
- SQL Ideas on How to Insert Using SELECT
- Beginners Tutorial on Embedding SQL
- How to Use NOT NULL Column Constraint Correctly
- Subquery in SELECT Top Ideas How to Write it Quickly
Top References to Format SQL