Skip to content

Instantly share code, notes, and snippets.

@ifindev
Created September 17, 2022 16:44
Show Gist options
  • Save ifindev/67abff13eb2900e51d3e36de9856822e to your computer and use it in GitHub Desktop.
Save ifindev/67abff13eb2900e51d3e36de9856822e to your computer and use it in GitHub Desktop.
SQL Challenges
CREATE TABLE IF NOT EXISTS USERS (
ID serial primary key not null,
UserName varchar(200)null,
Parent int not null
);
INSERT INTO USERS (UserName, Parent) VALUES ('Ali', 2)
INSERT INTO USERS (UserName, Parent) VALUES ('Budi', 0)
INSERT INTO USERS (UserName, Parent) VALUES ('Cecep', 1)
CREATE INDEX idx_id_user
ON USERS(ID);
EXPLAIN
SELECT u.ID, u.UserName,
CASE
WHEN us.UserName is NULL THEN ''
ELSE us.UserName
END ParentUserName
FROM USERS u
LEFT JOIN USERS us
ON u.Parent = us.ID
ORDER BY u.ID ASC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment