
上QQ阅读APP看书,第一时间看更新
There's more...
Like a book or a beautiful picture, we also need to take care with how we write a query. We can either use SQLA or Teradata Studio Express for this purpose. The main thing is, our query should be readable and should easily be understood.
Ctrl + Q auto formats the query in SQLA and Teradata Studio Express.
- Keep individual SQL statements small as they are easier to debug and support.
- Always qualify table names with database names; default database assignments can change.
- Use ANSI join syntax with join criteria in the ON clause, not in the WHERE clause. Join the clause on one line, tableA inner join tableB, and use a separate line for each criteria.
- Use a separate line for each table in the form list.
- When using subqueries, indent the subqueries and ensure the parenthesis are aligned.
- If any third-party tool is used to generate the query, remove the additional formatting that comes along with it.
- Change keyword shortcuts (sel, ins, upd, ct, and so on) to their full word equivalents (SELECT, INSERT, UPDATE, CREATE TABLE, and so on).
- Use tabs and spaces to build a block structure where each item of a clause begins in the same column.
- Include an inline comment for any hard coded values. The proper use of the block comment /**COMMENT USE**/:
/** Query to get employee name and invoice sum**/
SELECT oc.Employee_name
, r.WEEK_YEAR
, sum(oc.INVOICE) Invc_Sum
FROM Test01.ORGANIZATION oc INNER JOIN SALES.RETAIL_INVOICE_AGG r
AND oc.start_dt = r.repo_dt
WHERE oc.Dept_no = 'RETAIL'
These are some tips that can be used to maintain the integrity of the SQL codes and make them more readable.