Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any published coding style guidelines for SQL?

Often I will end up with very complex SQL statements and I wondered if there was style guideline out there that dictates a common way of laying various aspects of a query out.

I am look for something descriptive along the lines of Python's PEP8 or Zend Frameworks guidelines and not code by example.

Most of my queries are written for MySQL.

So do you know of a universal style guide? Perhaps you have written one yourself. Please share your guidelines.

like image 370
Treffynnon Avatar asked May 10 '11 14:05

Treffynnon


People also ask

What are coding standards in SQL?

General GuidelinesThe indentation must consist of three spaces. Every nested statement must begin with new level of indentation. All database reserved words will be in uppercase. The length of lines should not exceed 80 characters.

Is there coding in SQL?

SQL is a fourth-generation language, meaning it is a scripting language that does not require compiling to run. Like most fourth-generation languages, SQL requires an interpreter that translates rather than compiles code. As with all languages, SQL has rules for issuing commands and queries.

What is ANSI SQL standard?

SQL is a popular relational database language first standardized in 1986 by the American National Standards Institute (ANSI). Since then, it has been formally adopted as an International Standard by the International Organization for Standardization (ISO) and the International Electrotechnical Commission (IEC).

What is SQL script format?

What is SQL Scripts? A SQL script is a set of SQL commands saved as a file in SQL Scripts. A SQL script can contain one or more SQL statements or PL/SQL blocks. You can use SQL Scripts to create, edit, view, run, and delete script files.


2 Answers

Since asking this question I have written a public SQL style guide that is compatible with Joe Celko's SQL Programming Style book under the Creative Commons Attribution-ShareAlike licence.

It is available over at www.sqlstyle.guide or as markdown directly from the GitHub repo.

like image 152
Treffynnon Avatar answered Oct 17 '22 16:10

Treffynnon


Here are some SQL programming guidelines and best practices we collected:

  • Do not use SELECT * in your queries.
  • Always use table aliases when your SQL statement involves more than one source.
  • Use the more readable ANSI-Standard Join clauses instead of the old style joins.
  • Do not use column numbers in the ORDER BY clause.
  • Always use a column list in your INSERT statements.
  • Don't ever use double quotes in your T-SQL code.
  • Do not prefix your stored procedure names with “sp_”.
  • Always use a SQL formatter to format your SQL like Instant SQL Formatter (free and online)

You can check detailed explanation of those best practices in this blog post.

like image 6
James Wang Avatar answered Oct 17 '22 14:10

James Wang