SQL Syntax Notes

An ever-growing list of SQL syntax tricks I've collected! Mostly applicable to Spark SQL. Please comment if you have any tips you'd like to share, or any corrections.


Basic Functions to be Aware Of

Conditions on Aggregate Values

Having:
select 
    CATEGORY, sum(VALUE) as sumValues
from TABLE
where CATEGORY = 'a'
having sumValues > 0
;

Window Functions

Rank, Partition, Qualify
select
    rank() over (partition by USER_ID order by VALUE desc) as ranking
from TABLE
qualify  ranking = 1
;

Other window functions:
  • row_num(): If you don't want ties like rank will give you, use a row num
  • percent_rank(): Returns a value between 0 (lowest val) and 1 (highest val), if there are multiple highest vals, none of them will get a 1. Ties get the same percent_rank val.

Querying Off json Objects

For Spark SQL:
get_json_object(JSON_COL_HERE, '$.JSON_PATH_HERE') like '%3%'


Neat Techniques

Pivoting Tables w Case Statements

Pivot and Sum a Numerical Value
select
    CATEGORY
    , sum(case when VAL_ID = 1 then VALUE end) as sumVal1
    , sum(case when VAL_ID = 2 then VALUE end) as sumVal2
    , sum(case when VAL_ID = 3 then VALUE end) as sumVal3
from table
group by 1


Pivot and Count Occurrences
select
    CATEGORY
    , sum(case when VAL_ID = 1 then 1 else 0 end) as occurVal1
    , sum(case when VAL_ID = 2 then 1 else 0 end) as occurVal2
    , sum(case when VAL_ID = 3 then 1 else 0 end) as occurVal3
from table
group by 1


Pivot Text on a Lookup Table (only useful if you want to avoid a gazillion joins)
select
    CATEGORY
    , max(case when VAL_ID = 1 then VAL_DESC end) as valDesc1
    , max(case when VAL_ID = 2 then VAL_DESC end) as valDesc2
    , max(case when VAL_ID = 3 then VAL_DESC end) as valDesc3
from table
where VAL_ID in (1,2,3)
group by 1


Querying Dates

Basic Date Functions

  • year(DATE_COL)
  • month(DATE_COL)
  • weekofyear(DATE_COL)
  • to_date(STRING_COL_TO_CONVERT)

Dates "n" Months Ago

  • first day of the prev month: trunc(add_months(CURRENT_DATE(),-1), 'mon')
  • last day of the prev month: trunc(CURRENT_DATE(),'mon')-1

Comments

Popular posts from this blog

Making Predictions with a Tensorflow/Keras Model on a Webpage

Basic Python Functions