SQL Standards - PHIntelligence/CodingStandards GitHub Wiki

Formatting

Don't do this. This statement example below is difficult to read and inconsistent.

select [CALL_T] as Call_type, COMPLAINT as Complaint, PATIENTS_AGE as Age, PATIENTS_SEX as sex, DistrictsCode, DistrictsName
from dbo.patients a inner join  dbo.Postcodes b on b.Postcode=a.POSTCODE where YEAR(call_date)=2017

Do this. This the same query as above written in a clearer way.

SELECT	        CallType	= PAT.CALL_T
	       ,ChiefComplaint	= PAT.COMPLAINT
	       ,Age		= PAT.PATIENTS_AGE
	       ,Sex		= PAT.PATIENTS_SEX
	       ,DistrictCode	= PCD.DistrictsCode
	       ,DistrictName	= PCD.DistrictsName
FROM		dbo.patients	  PAT
INNER JOIN	dbo.Postcodes     PCD ON PCD.Postcode = PAT.P_CODE
WHERE		YEAR(PAT.CALL_DATE) = 2017
  • SQL keywords are always in upper case.
  • Column name aliases are written in PascalCase, and are assigned like ColumnAlias = OriginalColumnName, do not use OriginalColumnName AS ColumnAlias.
  • The original column names should be lined up with tab characters as shown above.
  • Table aliases should be a three our four letter abbreviation in upper case, and spaced to align. This makes it easy to see which tables are being referenced and from which tables the columns are taken from.
  • The comma separator should be at the beginning of the line not the end. This makes it easier to comment out a single line when refining a query, e.g.:
SELECT		CallType	= PAT.CALL_T
	       ,ChiefComplaint	= PAT.COMPLAINT
	       --,Age		= PAT.PATIENTS_AGE
	       --,Sex		= PAT.PATIENTS_SEX
	       ,DistrictCode	= PCD.DistrictsCode
	       --,DistrictName	= PCD.DistrictsName
FROM		dbo.patients	  PAT
INNER JOIN	dbo.Postcodes     PCD ON PCD.Postcode = PAT.P_CODE
WHERE		YEAR(PAT.CALL_DATE) = 2017