Skip to content

Instantly share code, notes, and snippets.

@boriscy
Last active August 3, 2016 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boriscy/2fe05e992ed6d0a71f2359f9625be3cd to your computer and use it in GitHub Desktop.
Save boriscy/2fe05e992ed6d0a71f2359f9625be3cd to your computer and use it in GitHub Desktop.
Guide for queries done on PostgreSQL

JSON, JSONB

Select inside a json field with array

select f.id, f.file_name, p->'trade_name' as trade_name, m->'cin_add' as cin_add
from frac_reports f, jsonb_array_elements((f.data->>'products')::jsonb) p,
jsonb_array_elements(p->'materials') m
where f.id = 65933

Get deep path JSON

select * from frac_reports where data->'header'->>'State' = 'West Virginia'

Lateral join

The LATERAL key word can precede a sub-SELECT FROM item. This allows the sub-SELECT to refer to columns of FROM items that appear before it in the FROM list. (Without LATERAL, each sub-SELECT is evaluated independently and so cannot cross-reference any other FROM item.)s

SELECT 
  sum(view_homepage) AS viewed_homepage,
  sum(enter_credit_card) AS entered_credit_card
FROM (
  -- Get the first time each user viewed the homepage.
  SELECT
    user_id,
    1 AS view_homepage,
    min(time) AS view_homepage_time
  FROM event
  WHERE
    data->>'type' = 'view_homepage'
  GROUP BY user_id
) e1 LEFT JOIN LATERAL (
  -- For each (user_id, view_homepage_time) tuple, get the first time that
  -- user did the enter_credit_card event, if one exists within two weeks.
  SELECT
    1 AS enter_credit_card,
    time AS enter_credit_card_time
  FROM event
  WHERE
    user_id = e1.user_id AND
    data->>'type' = 'enter_credit_card' AND
    time BETWEEN view_homepage_time AND (view_homepage_time + 1000*60*60*24*14)
  ORDER BY time
  LIMIT 1
) e2 ON true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment