Joinen in Snowflake

Introductie tot Snowflake SQL

George Boorman

Senior Curriculum Manager, DataCamp

JOINS

  • INNER JOIN
  • OUTER JOINS
    • LEFT OUTER JOIN of LEFT JOIN
    • RIGHT OUTER JOIN of RIGHT JOIN
    • FULL OUTER JOIN of FULL JOIN
  • CROSS JOINS
  • SELF JOINS
  • NATURAL JOIN
  • LATERAL JOIN
Introductie tot Snowflake SQL

Pizzadataset

Diagram van pizzaschemadatabase

Introductie tot Snowflake SQL

NATURAL JOIN

  • NATURAL JOIN matcht automatisch kolommen en verwijdert dubbele

Syntaxis:

SELECT ...
FROM <table_one> [
                     {
                       | NATURAL [ { LEFT | RIGHT | FULL } [ OUTER ] ]
                     }
                   ]
                   JOIN <table_two>
[ ... ]
Introductie tot Snowflake SQL

NATURAL JOIN

Zonder NATURAL JOIN

SELECT * 
FROM pizzas AS p 
JOIN  pizza_type AS t 
    ON t.pizza_type_id = p.pizza_type_id

Joinresultaat zonder natural join

Met NATURAL JOIN

SELECT *
FROM pizzas AS p 
NATURAL JOIN pizza_type AS t

  Joinresultaat met natural join

Introductie tot Snowflake SQL

NATURAL JOIN

 

NIET TOEGESTAAN

select *
FROM pizzas AS p 
NATURAL JOIN pizza_type AS t
    ON  t.pizza_type_id = p.pizza_type_id

Syntaxisfout-afbeelding

Introductie tot Snowflake SQL

NATURAL JOIN

$$

TOEGESTAAN

  • WHERE-clausule
SELECT *
FROM pizzas AS p 
NATURAL JOIN pizza_type AS t
WHERE pizza_type_id = 'bbq_ckn'
Introductie tot Snowflake SQL

LATERAL JOIN

  • LATERAL JOIN: laat een subquery in FROM kolommen gebruiken uit voorafgaande tabellen of views.

Syntaxis:

SELECT ...
FROM <left_hand_expression> , -- 
LATERAL 
(<right_hand_expression>)

  • left_hand_expression - Tabel, view of subquery

  • right_hand_expression - Inline view of subquery

Introductie tot Snowflake SQL

LATERAL JOIN met een subquery

SELECT 
    p.pizza_id, 
    lat.name, 
    lat.category 
FROM pizzas AS p,

LATERAL -- Trefwoord LATERAL ( SELECT * FROM pizza_type AS t
-- Verwijzing naar kolom buitenste query: p.pizza_type_id WHERE p.pizza_type_id = t.pizza_type_id
) AS lat
Introductie tot Snowflake SQL

Waarom LATERAL JOIN?

SELECT 
    *
FROM orders AS o,
LATERAL (
   -- Subquery die total_spent berekent
    SELECT 
        SUM(p.price * od.quantity) AS total_spent
    FROM order_details AS od
    JOIN pizzas AS p 
          ON od.pizza_id = p.pizza_id
    WHERE o.order_id = od.order_id
) AS t
ORDER BY o.order_id
Introductie tot Snowflake SQL

Laten we oefenen!

Introductie tot Snowflake SQL

Preparing Video For Download...