Quantcast
Channel: formatter | ThatJeffSmith
Viewing all articles
Browse latest Browse all 19

Formatting your SQL Queries, Indented Predicates on New Lines

$
0
0

Someone asked in our forums how to format their code the way they want it.

Specifically, they have code like so:

SELECT t1.col1 ,
  t1.col2 ,
  t1.col3 ,
  t1.col4 ,
  t1.col5 ,
  t1.otp ,
  t2.fid ,
  t2.pid
FROM table_1 t1 ,
  table_2 t2 ,
  table_3 t3
WHERE t1.rid = in_rid
AND t1.col5  = t2.lid
AND t1.col1  = t3.loid
AND t1.atp NOT LIKE 'ABC%'
AND NOT EXISTS
  (SELECT t4.*
  FROM table_4 t4,
    table_5 t5
  WHERE t4.tid  = t5.tid
  AND t5.active = 'Y'
  AND t4.flag   = CC_FLAG
  AND t4.anw   IS NULL
  )
ORDER BY t1.col3;

They don’t want this:

Hard to read?

Hard to read?

The user doesn’t want the first predicate on the same line as the ‘WHERE’ keyword, and doesn’t want the additional predicate clauses to be on the same vertical position as the WHERE keyword as well.

Thankfully there are 2 Formatter preferences that make this easy to fix.

So the AFTER FORMAT looks like this:

SELECT
  t1.col1 ,
  t1.col2 ,
  t1.col3 ,
  t1.col4 ,
  t1.col5 ,
  t1.otp ,
  t2.fid ,
  t2.pid
FROM
  table_1 t1 ,
  table_2 t2 ,
  table_3 t3
WHERE
  t1.rid      = in_rid
  AND t1.col5 = t2.lid
  AND t1.col1 = t3.loid
  AND t1.atp NOT LIKE 'ABC%'
  AND NOT EXISTS
  (SELECT
    t4.*
  FROM
    table_4 t4,
    table_5 t5
  WHERE
    t4.tid        = t5.tid
    AND t5.active = 'Y'
    AND t4.flag   = CC_FLAG
    AND t4.anw   IS NULL
  )
ORDER BY
  t1.col3;

predicates2

The Preferences

Neither of these are on by default.

Neither of these are on by default.

Not sure if you’re playing around with the ‘right’ preference? The code preview to the right updates AS you tweak the preference. That means you don’t have to guess.


Viewing all articles
Browse latest Browse all 19

Trending Articles