A Better Way To Write SQL Queries

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5
At a glance
Powered by AI
The key takeaways are about writing SQL queries in a structured way by dividing them into multiple lines and using proper indentation to make them more readable.

Three different ways of writing SQL queries are discussed: 1) Using mixed case, writing the entire query on one line 2) Dividing the query into multiple lines but keeping all conditions on the where clause in one line 3) Dividing the query and conditions into multiple lines with proper indentation.

For the first style, the pros are it separates keywords from columns/tables but the cons are lack of consistency and readability. For the second style, readability is improved but conditions are still on one line. For the third style, readability and identifying source of data is improved by dividing and indenting properly.

Javarevisited

Blog about Java programming language, FIX Protocol, Tibco RV


Search

HostGator© includes a vast array of tools


HostGator© Official and guarantees with each hosting plan.

Home core java spring hibernate collections multithreading design patterns interview questions coding data structure OOP books About Me

Interview Questions
A Better way to write SQL queries
core java interview question (161)
Writing code is art and same applies to SQL
data structure and algorithm (45)
queries. The way you structure your query, the
Coding Interview Question (32)
way you write it goes a long way to
SQL Interview Questions (24)
communicate your intent to the fellow
thread interview questions (20)
developer. When I see SQL queries on emails
database interview questions (18)
from multiple developers, I can see the stark
servlet interview questions (17)
difference in their writing style. Some
collections interview questions (15)
developers write it so neatly and indent their
spring interview questions (9)
query properly, which makes it easy to spot the
Programming interview question (4)
key details e.g. which columns you are
hibernate interview questions (4)
extracting from which table and what are
conditions. Since in real life projects, SQL
queries are hardly one‐liner, learning the right way to write SQL query makes a lot of
difference when you read it yourself later or you share that query to someone for review or
use.

In this article, I am going to show you a couple of styles which I have tried in past, their pros
and cons and what I think is the best way to write SQL query. Unless you have a good reason
not to use my style e.g. you have a better style or you want to stick with the style used in
your project (consistency overrules everything) there is no reason not to use it.

Database Management
WinSQL ­ A Homogeneous Solution for Heterogeneous
Environment. Go to synametrics.com

Pl/sql
Download PL/SQL Developer lots of features, plug­ins &
more Go to allroundautomations.com

Translate this blog

1st way to write SQL query Seleccionar idioma

Con la tecnología de  Traductor de Google
SELECT e.emp_id, e.emp_name, d.dept_name, p.project_name from Employee e  
INNER JOIN Department d ON e.emp_id = d.dept_id INNER JOIN Projects p  
ON e.emp_id = p.project_id Where d.dept_name="finance" and e.emp_name  
like '%A%' and e.salary > 5000;

Pros:
1) mixed case was introduced to separate keyword from column and table names e.g. writing
SELECT in capital case and writing Employee in as it is, but given you are not consistent e.g.
SELECT is in caps but from is in small, there is no benefit of using that style.

Problem:
1) mixed case
2) all query is written on one line which gets unreadable as soon number of tables and
columns increases
3) no flexibility on adding a new condition or running without existing condition

Java Tutorials

date and time tutorial (17)


Database Management FIX protocol tutorial (16)
java collection tutorial (52)
WinSQL ­ A Homogeneous Solution for Heterogeneous java IO tutorial (25)
Environment. Java JSON tutorial (6)
Java multithreading Tutorials (32)
synametrics.com
Java Programming Tutorials (27)
Java xml tutorial (9)

2nd way to write SQL query

SELECT e.emp_id, e.emp_name, d.dept_name, p.project_name 
from Employee e 
INNER JOIN Department d ON e.emp_id = d.dept_id 
INNER JOIN Projects p ON e.emp_id = p.project_id 
Where d.dept_name="finance" and e.emp_name like '%A%' and e.salary > 500;
Search This Blog

Search
Improvement:
1) query is divided into multiple lines which make it more readable

Problems
1) mixed case
2) all conditions on where clause are on the same line, which means excluding them by
commenting is not that easy.

3rd way to write SQL query


select e.emp_id, e.emp_name, d.dept_name, p.project_name 
from Employee e 
inner join Department d on e.emp_id = d.dept_id 
where d.dept_name = 'finance' 
and e.emp_name like '%A%' 
and e.salary > 500;

1) dividing SQL queries into multiple lines makes it more readable


2) using proper indentation makes it easy to spot the source of data i.e. tables and joins
3) having conditions on separate lines allow you to run the query by commenting one of the
condition e.g.

select e.emp_id, e.emp_name, d.dept_name 
from Employee e 
inner join Department d on e.emp_id = d.dept_id, p.project_name 
where d.dept_name = 'finance' 
‐‐ and e.emp_name like '%A%'; 
add e.salary > 5000

That's all about how to write SQL query which is readable and more maintainable. Freel free
to give your opinion on what do you think of this indentation or styling of SQL queries. It's a
simpler technique but very powerful and goes a long way on improving the readability of your
complex SQL queries.
Follow by Email

Email address... Submit
Some useful books to improve your SQL skills
Ads by Google
SQL Puzzles and Answers by Joe Celko
SQL Performance explained by Markus Winand SQL Queries
SQL Antipatterns SQL Tutorial

Followers

Seguidores (4014) Siguiente
Thanks for reading this article and let me know how do you write SQL queries? which style you
use, or you have your own style?

Seguir

Blog Archive
▼  2017 ( 12 )
▼  January ( 12 )
How public static final variable works in Java?
How to convert double to int in Java?
Difference between OCPJP 8 Upgrade Exams
1Z0‐813 a...
A Better way to write SQL queries
12 Essential Apache Web Server Interview
Questions...
Bucket Sort in Java with Example
You May Like Sponsored Links  by Taboola    
3 Ways to Convert Java 8 Stream to an Array ‐
Now You Can Track Your Car Using Your Smartphone Lamb...
Smart Device Trends Difference between extends and implements
keywords...
Running SQL Queries on Production/live
Databases ‐...
5 College Degrees That Will Be Extinct In 20 Years
"The system cannot find the path specified."
Womensarticle.com
Error...
How to check for NULL values in SQL Query? The
Rig...

Wait till you get to level 24! What is the real use of Method Overloading in


Java...
Soldiers: Free Online Game

►  2016 ( 166 )
►  2015 ( 126 )
This game will keep you up all night! ►  2014 ( 101 )
Vikings: Free Online Game
►  2013 ( 127 )
►  2012 ( 214 )
►  2011 ( 135 )
After Getting Divorced ­ Michael Jordan's New Wife's Is A Total Babe ►  2010 ( 30 )
Rival Share

Pages
The Ultimate Cheap Flights Finder is Here!
Save70.com Privacy Policy

Copyright by Javin Paul 2010‐2016. Powered by


Blogger.
The 19 coolest hotels in the world
Escapism.com

How Organisations are Grappling with the Security “Gap Of Grief”
ARN for RSA

You might like:


Difference between Inheritance and Composition in Java OOPS
Fibonacci series in Java without using Recursion
10 Example Queries of SQL Select Command
How HashMap works in Java

Recommended by 

Posted by Javin Paul +20   Recommend this on Google

Labels: best practices , SQL

4 comments :
Badal Chowdhary said...
Nice post. 1 additional input: make all the sql text lower case and keywords upper case. it can help distinguish
between key words and column/table names.

In SQL Developer, can be easily achieved by:


1. Ctrl + Shift + ' (change case)
2. Ctrl + F7 (Format: keywords are changed to uppercase)

January 12, 2017 at 7:46 AM

Mladen said...
I think upper case sql keywords are not bad. If there is no sql highlighting available (maybe the sql is embedded in
another language or just an email) then it's much easier to read. I also prefer indentation in some cases.

January 14, 2017 at 1:10 AM

Turnkey Solutions said...


You have barely scratched the surface of SQL at this point. What about subqueries?

January 14, 2017 at 7:59 AM

Anonymous said...
I always put the new table name first in a join clause, not second. That way the join looks more consistent if you're
joining to Table c with clauses correlating to Table a and Table b, and if you have a simple join constraint on c, e.g.
"
LEFT JOIN c
ON c.foo = a.foo
AND c.bar = b.bar
AND c.baz LIKE 'A%'​
January 15, 2017 at 5:21 AM

Post a Comment

Enter your comment...

Comment as:  Unknown (Google) Sign out

 
Publish Preview   Notify me

Newer Post Home Older Post

Subscribe to: Post Comments ( Atom )

Related Books for Further Reading

SQL Performance Explained SQL Antipatterns: Avoiding Joe Celko's SQL Puzzles and New Bright R/C F/F Raptor


Everything Developers… the Pitfalls of Database … Answers, Second Edition … with "AA" Batteries (1:10 S…

$39.99 $25.34 $34.95 $60.95 $67.95 $39.99


 (15)  (48)  (14)  (15)

Velocity Toys Speed Wagon 130mm Gold Alloy Dampers Castle Creations Sidewinder Oracle SQL Performance


6X6 Remote Control R… (4) ­ Oil Shocks for 1:10 Rc… 3 Waterproof ESC with Mot… Tuning and Optimization: It…

$44.95 $26.59 $91.78 $111.99 $38.99


 (19)  (1)  (20)  (27)

All Search Amazon Go

Ads by Amazon

You might also like