Skip to content

Instantly share code, notes, and snippets.

@gani88
Created June 12, 2024 09:51
Show Gist options
  • Save gani88/34da630b240687541423ecd772793c82 to your computer and use it in GitHub Desktop.
Save gani88/34da630b240687541423ecd772793c82 to your computer and use it in GitHub Desktop.
SQL : Self Join to query parent name
-- Creating Table
CREATE TABLE CensusPeople (
id serial primary key,
name varchar,
parent_id int
);
-- Inserting Data
INSERT INTO CensusPeople (id, name, parent_id)
VALUES (1, 'Zaki', 2),
(2, 'Ilham', NULL),
(3, 'Irwan', 2),
(4, 'Arka', 3);
-- Query
SELECT children.id AS id,
children.name AS name,
parent.name AS parent_name
FROM CensusPeople AS children
LEFT JOIN CensusPeople AS parent
ON parent.id = children.parent_id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment