51 points · by rachbelaid · 13y ago · 83 comments
SELECT field1
, field2
, field3
, another_field
FROM ...
By placing the comma at the beginning of the line, instead of at the end, we can very easily reorganize the sequence without fiddling with commas most of the time: SELECT field1
, field3
, another_field
, field2
FROM ...For example multiple lines in this query would cause an error:
SELECT a.field1,
a.field2,
-- b.field1,
-- b.field2,
c.field1,
-- b.field3
FROM a,
-- b,
c
WHERE --a.field1 = b.field1
AND a.field2 = c.field1
This query would not cause an error (Note that DUAL is a dummy table in Oracle that contains 1 column and row): SELECT 0
, a.field1
, a.field2
--, b.field1
--, b.field2
, c.field1
--, b.field3
FROM dual
, a
--, b
, c
WHERE 0=0
-- AND a.field1 = b.field1
AND a.field2 = c.field1
It does add a 0 column to the result set but that can be dealt with or removed after development. select
site.name
, site.plan
, site.status
, domain.domain
, subscription.updated_at
from
subscription
inner join site on subscription.site_id = site.id
inner join domain on domain.site_id = site.id
where
subscription.status = 'inactive'
and subscription.plan = 'pro'
and domain.created_at <= '2012-04-01'
order by
subscription.updated_at desc
When I was writing a lot of sql I found it a lot easier to work with (when you're commenting things out a lot during development for example). Also, I'm a geek, so I like stuff lined up.I understand the arguments for putting commas at the end of the line. For example, Google say in their style guide that when reading, having the comma at the end alerts the reader to the continuation on the next line. In languages that allow trailing commas (Python, php, C# etc) that's what I do. I put them at the front otherwise.
It's certainly not worth an overreaction though. Having commas on either end of the line isn't going to kill anyone. I've written 1000s of lines of sql in both styles and the world hasn't imploded yet.
As always, be consistent with the surrounding code - that's more important than any other rules (especially ones with a purely subjective basis).
WHERE 1=1
AND ...
--AND ...
AND ...
I do not like having commas at the beginning of the lines though.ORM frameworks frequently use this when they create SQL.
To this day we still give that dev (the team lead) a hard time about the trailing comma. We since implemented mandatory linting on all JS.
myClass::myClass(int aa,int bb)
: a(aa)
, b(bb)
, p(new int[aa])
, c(17)
{}
Yes, that looks weird at first, but you get used to it (and, to be honest, everything in C looks weird at first).Having the comma in the proper place has such a negligible cost (oh no I might have to delete the comma on the last element and add it to the formerly-last element!), and having it like this looks so god awful and doesn't really save you anything if you're swapping the first element instead of the last one.
Being very dogmatic, and in a discussion of ideas saying "that's the worst thing in the world" is easily worse than comma placement. So surely commas as indentation isn't the worst thing in the world.
select
Field1,
Field2,
AnotherField
from
Table1
So clean, so consistent! No all-uppercase that adds almost no benefit at significant cost. Fields lined up for easy reading and editing.The comma controversy could be eliminated if the SQL standard was like Go's, where even the last line would have a comma.
Seriously, though, hideous syntax is bad. It makes life miserable for everyone who has to work on your code after you. Don't do it, no matter what good reasons you think you have.
Changed formatting is a shock the first time. But it does not take long to retrain yourself to find it aesthetically more pleasing.
When you're making a quick fix to a batch job that does not hit the problematic query for 30 minutes, the cost of messing up the comma is 30 minutes. (Yeah, I know, it all should be properly factored out, and unit tested. But there is a lot of lightly tested code in the real world that behaves just like I said.) Because SQL is stored as plain text, there is real value in making your mental compiler have to do no work to notice stupid syntactical stuff.
The solution should not be hideous syntax.
Comma first seems more consistent to me.... unless you write your WHERE clauses like this:
WHERE a=b AND
a=d AND
e=f
Because it makes your SQL more legible.
In english, commas go after the previous word, not before the next word. The syntax is the same for all programming languages. The fact that most compilers and interpreters don't require it is not an excuse for abusing it.
First, most of my SQL scripts are multiple statements, typically 6+, ranging up as high as 100. When I'm reading and trying to digset such scripts, the long format described by the author, particularly putting each column on its own row, makes it difficult to easily digest the script. I'm forced to scroll constantly to make sense of the statements in relation to one another. Instead, I prefer to my SQL to be more compact, so I can view as much of the total script as possible.
To accomplish this, and to maintain readability, I structure each statement something like this:
CREATE/INSERT/UPDATE line SELECT line FROM line JOINS (if present) ON (if present) WHERE (if present) AND (if present) Additional SQL (qualify, group by, order by) ;
If I have a lot of columns, the select portion will get split into several lines, usually where there is a case when, column operations, or when the line is 200ish characters long.
This makes the most sense to me, as each command (create, update, insert, select, from, join, on, where, and, group by) is on its own line, followed by the information relevevant to it.
You don't agree?
What is the difference between coding in that language and SQL? I submit that it is only the amount of it you write.
I spent several years of my life focusing on reporting, and spending more time writing/maintaining SQL than writing any other language. In that time I discovered that complex SQL queries are a language like anything else. For "hello world" you can get away with anything. But as soon as you are doing complex stuff, the layout matters.
Did you know that it can make a difference whether a condition is in your ON or your WHERE? It can. (Think left joins.) Did you know that the location/order of the ON statements can make a difference? It does. Is it visually obvious where this particular condition is? It should be. Did you know that the order you put things in in your query can have performance impacts? It shouldn't, but it does (particularly for MySQL - MySQL is stupid).
If you've got 200ish character lines and you are unwilling to format, well, I'm glad that I don't work with you. Because I'm likely to be asked to figure it out at some point, and I don't want to maintain crap like that.
For example (i've added \ as line break in case those get lost again):
select \ a., \ b.column1, \ b.column2, \ b.column3 \ from \ my_table a \ left join \ my_other_table b \ on \ a.col = b.col \ and \ a.col2 = b.col2 \ where \ a.col = condition \ group by \ column1, column2 \ ;
vs.
select a.
, b.column1, b.column2, b.column3 \ from my_table a \ left join my_other_table b \ on a.col = b.col \ and a.col2 = b.col2 \ where a.col = condition \ group by column1, column2 \ ;I'll take the 2nd approach any day, particularly when I have statements above and below that reference that statement, because I can more easily understand the context of the entire script. I also prefer this, because in my mind, there is greater continuity, my_table is related to from, so it makes sense that it should follow it. I read left to right, and don't need to move down to a new line.
However what happens when your list of columns is long? What happens if you want to include a CASE statement in a field?
I use vim and personally solve the scrolling problem with :split. This is particularly important in making sure that the SELECT and GROUP BY match up. (I am perpetually annoyed that the GROUP BY is not inferred from the SELECT. Unfortunately multiple databases have invented different inconsistent behavior for missing stuff in a GROUP BY, so there is absolutely no possibility of getting agreement on the convenient default of grouping on all non-aggregate functions that appear in the SELECT and HAVING clauses.)
See http://bentilly.blogspot.com/2011/02/sql-formatting-style.ht... for what this looks like in practice.
BTW, I can't imagine any of the below is legible, but I find myself enjoying these types of things.
with bgu as
(select
protocol_code,
application_code,
description,
lab,
proj."seqno",
proj."project",
proj."protocol",
'false' "nexttag",
'true' "materialtag"
from
protocol,
xmltable('for $a in /*
for $n at $nidx in //*/MATERIAL
return <result>
<project>{fn:data($n/@project)}</project>
<protocol>{fn:data($n/@protocol)} </protocol>
</result>'
passing xmltype(protocol.xml)
columns
"seqno" for ordinality,
"project" varchar2(100),
"protocol" varchar2(100)) proj
where
active = 'Y'
union
select
protocol_code,
application_code,
description,
lab,
proj."seqno",
proj."project",
proj."protocol",
'true' "nexttag",
'false' "materialtag"
from
protocol,
xmltable('for $a in /*
for $n at $nidx in //*/NEXT
return <result>
<project>{fn:data($n/@project)}</project>
<protocol>{fn:data($n/@protocol)}</protocol>
</result>'
passing xmltype(protocol.xml)
columns
"seqno" for ordinality,
"project" varchar2(100),
"protocol" varchar2(100)) proj
where
active='Y'
order by 1,2,4 )
select
*
from
(select distinct
protocol_code,
sys_connect_by_path(protocol_code,'||||'),
connect_by_isleaf "isleaf"
from bgu
where protocol_code like 'PROTNAME%'
connect by nocycle prior "protocol" = protocol_code)
where "isleaf"=1I am almost always working with legacy schemas, many generated by long-extinct tools or developers, and being a genuinely curious person, wandering down strange code paths to see if I can satisfy random reporting requests.
This might have been what you're looking for if it was still updated. Still some funny stuff there though.
But I don't think all queries should be written in several lines. If a query is simple enough (e.g. no aggregation, group by, having and at maximum one where condition and few fields to select), it can be written in one line, like:
SELECT field FROM table WHERE value = @value
That's easy and straightforward to understand and readable (which was initially part of SQL's goals, although we can discuss at a later date how successful that was). Complicated SQL queries - which are bound to happen - follow - in my style - a more straightforward approach:
There are new lines after every grouping (FROM, WHERE, GROUP BY, SORT BY, HAVING, etc.) and indenting. In fact, I prefer to indent my fields twice, because I consider FROM, WHERE, etc. to be subject to SELECT (even if part of an INSERT). I also tend to avoid extra keywords such as 'OUTER' in 'LEFT OUTER JOIN' (there is no such thing as 'LEFT INNER JOIN'). And then I follow each JOIN statement (indented compared to the ground table in from) by the table name, a new line, an indent and the ON condition. If another table relies on that table being joined, I indent it further to indicate that, so I can quickly look at my code to see what tables goes through which (which is useful if you have a lot of relationship tables).
Should be noted, however, I most commonly write towards Sybase at work, which tends to have no preference - style wise - on whether you write the keywords in upper case. My co-workers do not, so I don't either. But when I write my own projects against MySQL/MariaDB, I use upper case. But I generally follow the same style.
select blah, blha, blah
from dual
where ...
I find that even for short ones, lines quickly get very long and illegiable if you're shmushing them all onto one line.Per the SQL spec, explicit JOIN-style syntax binds more tightly than FROM-list elements, which can not only constrain the query planner in the choices it can make, but can actually yield a different result.
Also, why are
wine_tags as (
SELECT DISTINCT
unnest(tags) as tag,
wine_id
FROM
app_rating
GROUP BY
wine_id, tags),
wine_detail as (
SELECT
app_wine.name as name,
app_wine.id,
app_winery.name as winery
FROM
app_wine,
app_winery
WHERE app_wine.winery_id = app_winery.id
)
handling closing parentheses differently? This affects how you organize nested parentheses.Not everyone knows that AND binds more tightly. Nor should they have to.
My general rule-of-thumb is that trivial things can have syntax constraints relaxed, as long as it makes them more readable, not less. I may adopt the style of the article for a complex query, but for something simpler I may go with:
SELECT foo, bar, baz
FROM my_table
WHERE foo=1 AND bar > 10
GROUP BY bar
ORDER BY baz
But that becomes less readable after more than a couple fields or conditions for each line. Until that point, I think it's fairly concise and efficient.That said, if your SQL is intermixed with code whose sole purpose isn't to deal with that SQL, you are probably in for hurt later on anyway. If it is safely quarantined into data access routines of some sort, the size doesn't really matter, since the function or method containing the query should really be about that query.
Other than that, I use a variant of this style, where I put things on one line if possible (especially GROUP BY and ORDER BY). And I tend to line up my joins like so:
FROM foo
JOIN bar ON b.foo_id = f.id
LEFT JOIN baz ON ...I'm not a web developer - I spend more of my time in raw-sql-land, so this discussion is largely academic to me :-). That said, even if you're using an ORM, it's presumably not exactly free for the ORM to produce an object out of the thousands of distinct rows you can end up getting if you have multiple one to many relationships.
In general, the availability of arrays for the purposes of data transport - less so actual storage - in postgres is rather helpful for these sort of problems. I find working with other DBs to do object storage quite constricting by comparison.
* No use of spaces.
* Obscure use of aliases. If you have 4 tables all aliased as a,b,c,d then you are making life hard for someone else.
* Not capitalizing operations or reserved words.
SELECT
avg(rating),
wine_id
FROM
app_wine
GROUP BY
wine_id;
The query should be against the app_rating table. It does get corrected later on, but I was confused for a while. ...
Inner join a on a.... = main..
Inner join b on b... = a...
Inner join c on c... = b...
Inner join x on x... = a...
The syntax of SQL is a real basket case, readers need all the help you can give them.Its a huge help when analyzing bad queries that newrelic might spit out.
It allow to break down the logic and composite the result.
Any idea if it's standard SQL?
MSSQL has a similar construct with Common Table Expressions (CTE's) though, so it' not unique to PG.
MSSQL makes it so that people pick up bad habits over the years and often you'll find missing semicolons at the end of statements. While the parser will intelligently handle missing semicolons for the majority of of scripts, it will bomb 100% of the time (at least up to 2008R2) on WITH.