Skip to content

Instantly share code, notes, and snippets.

@gusalbukrk
Last active August 7, 2023 17:47
Show Gist options
  • Save gusalbukrk/152563c4bf5037bc9ff514e50a3c22c8 to your computer and use it in GitHub Desktop.
Save gusalbukrk/152563c4bf5037bc9ff514e50a3c22c8 to your computer and use it in GitHub Desktop.
#sql
-- model inheritance in database
-- table per type
-- https://stackoverflow.com/a/190306
CREATE TABLE users (
id SERIAL,
email VARCHAR(50) NOT NULL,
password VARCHAR(20) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE employees (
id INTEGER,
cpf CHAR(11) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (id) REFERENCES users (id)
);
INSERT INTO users (email, password) VALUES (
'j@gmail.com',
'pass1234'
);
INSERT INTO employees VALUES (
1,
'01234567890'
);
CREATE TABLE employers (
id INTEGER,
cnpj CHAR(11) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (id) REFERENCES users (id)
);
INSERT INTO users (email, password) VALUES (
'k@gmail.com',
'pass1234'
);
INSERT INTO employers VALUES (
2,
'98765432101'
);
-- select all users (both employees and employers)
SELECT users.id, email, password, cpf, cnpj FROM users
LEFT JOIN employees ON users.id = employees.id
LEFT JOIN employers ON users.id = employers.id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment