• Shaarli
  • Tag cloud
  • Picture wall
  • Daily
  • RSS
  • Login
4252 shaares
Filters

Best Practices for Writing Good SQL Code

QRCode

5. Modularize Code with Common Table Expressions

CTEs create a temporary table that allow you to “query a query.”
https://www.essentialsql.com/introduction-common-table-expressions-ctes/

The advantage of a CTE (your second statement) over a derived table is that they can reference themselves and be used for recursion.

with avg_female_salary as (
   SELECT       AVG(salary) as avg_salary
   FROM       salaries
   WHERE gender = "Female"
)
SELECT name,  salary
FROM People
WHERE  salary >= (SELECT avg_salary FROM avg_female_salary)

7. Simplify Code using Temporary Functions

https://cloud.google.com/bigquery/docs/reference/standard-sql/user-defined-functions

CREATE TEMPORARY FUNCTION seniority(tenure INT64) AS (
   CASE WHEN tenure < 1 THEN "analyst"
        WHEN tenure BETWEEN 1 and 3 THEN "associate"
        WHEN tenure BETWEEN 3 and 5 THEN "senior"
        WHEN tenure > 5 THEN "vp"
        ELSE "n/a"
   END
);
SELECT name
       , seniority(tenure) as seniority
FROM employees
https://towardsdatascience.com/8-best-practices-for-writing-top-tier-sql-code-e1023996e459
April 23, 2022 at 9:59:25 AM EDT *
sql mssql
FILLER
Shaarli · The personal, minimalist, super fast, database-free, bookmarking service by the Shaarli community · Documentation
Fold Fold all Expand Expand all Are you sure you want to delete this link? Are you sure you want to delete this tag? The personal, minimalist, super fast, database-free, bookmarking service by the Shaarli community