Created
June 12, 2024 09:51
-
-
Save gani88/34da630b240687541423ecd772793c82 to your computer and use it in GitHub Desktop.
SQL : Self Join to query parent name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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