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

10 Quick SQL Tips After Writing Daily in SQL for 3 Years

QRCode

4. CTE > Sub-queries

In most situations you want to use a CTE (common table expression) instead of a sub-query.

5. Using SUM and CASE WHEN Together

select 
     sum(case when allergies = 'Penicillin' and city = 'Burlington' then 1 else 0 end) as allergies_burl
   , sum(case when allergies = 'Penicillin' and city = 'Oakville' then 1 else 0 end)   as allergies_oak

from patients

Start where clause with true

where 1=1
and ...
and ...
and...

7. Don’t Forget About Window Functions

select
    p.*
  , MAX(weight) over (partition by city) as maxwt_by_city
 from patients p

Window functions are a great way to keep all of the data rows and then append another column with important aggregate details.

https://towardsdatascience.com/10-quick-sql-tips-after-writing-daily-in-sql-for-3-years-37bdba0637d0
April 4, 2022 at 9:49:14 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