-- Pets Table
id INT, type VARCHAR);
CREATE TABLE pets(1, 'dog');
INSERT INTO pets VALUES(2, 'bird');
INSERT INTO pets VALUES(3, 'cat');
INSERT INTO pets VALUES(4, 'monkey');
INSERT INTO pets VALUES(
-- -- -- -- -- -- -- -- -- -- -- -- --
-- Owner Table
id INT, name VARCHAR, pet_id INT);
CREATE TABLE owner(1, 'Sarah', 1);
INSERT INTO owner VALUES(2, 'Bob', 2);
INSERT INTO owner VALUES(3, 'Emily', 3);
INSERT INTO owner VALUES(4, 'John', NULL); INSERT INTO owner VALUES(
Postgresql JOIN USING vs JOIN ON 🥞
sql
postgresql
I recently learnt that we can directly use USING()
clause as shorthand when joining tables in Postgresql. Here is the an excerpt from the documentation.
[Click on the image to check the full documentation]
Let’s use the tables above as an example. Say we want to merge pet_id
from both of the tables to find the pet type for each person listed in Owner
table.
An option is to use USING(pet_id)
clause. This is similar to JOIN ... ON owner.pet_id = pets.pet_id
but will combine all resulting unique ids from both table.
-- JOIN with USING
type, name
SELECT pet_id,
FROM owner; FULL JOIN pets USING(pet_id)
We can get the same result if above it we use normal JOIN ON...
with CASE
clause.. but this is definitely more wordy…
-- Normal JOIN ON... with CASE
SELECT CASE
WHEN o.pet_id IS NULL THEN p.pet_id
ELSE o.pet_id
END AS pet_id,type, o.name
p.
FROM OWNER AS o
FULL JOIN pets AS p= p.pet_id ON o.pet_id