· 6 years ago · Aug 05, 2019, 07:00 PM
1create table if not exists endereco
2(
3 id serial not null
4 constraint endereco_id_pk
5 primary key,
6 rua text not null,
7 numero integer,
8 bairro text,
9 cidade text not null,
10 pessoa_id bigint NOT NULL
11 constraint endereco_pessoa_id_fkey
12 references pessoa (id)
13 on delete cascade
14);
15
16create table if not exists pessoa
17(
18 id serial not null
19 constraint pessoa_id_pk
20 primary key,
21 nome text not NULL,
22 idade integer,
23 ativo boolean default false not null,
24 chefe_id bigint
25 constraint chefe_pessoa_id_fkey
26 references pessoa (id)
27 on delete cascade
28);
29
30INSERT INTO pessoa(nome, idade, ativo, chefe_id)
31values ('Henrique Mota', 26, TRUE, null);
32insert into endereco(rua, numero, bairro, cidade, pessoa_id)
33values ('Av Rep. Líbano', 0, 'Setor Aeroporto', 'Goiânia', 1);
34
35INSERT INTO pessoa(nome, idade, ativo, chefe_id)
36values ('Luiz Henrique', 27, TRUE, null);
37insert into endereco(rua, numero, bairro, cidade, pessoa_id)
38values ('Av Rep. Líbano', 0, 'Setor Aeroporto', 'Goiânia', 3);
39
40INSERT INTO pessoa(nome, idade, ativo, chefe_id)
41values ('Igor Duarte', 25, TRUE, 1);
42insert into endereco(rua, numero, bairro, cidade, pessoa_id)
43values ('Av dos Alpes suiços', 0, 'St funcionarios', 'Goiânia', 4);
44
45INSERT INTO pessoa(nome, idade, ativo, chefe_id)
46values ('Kaio Ferreira', 20, TRUE, 1);
47insert into endereco(rua, numero, bairro, cidade, pessoa_id)
48values ('Rua Marechal Deodoro', 0, 'Jardim Nova Goiânia', 'Goiânia', 5);
49
50INSERT INTO pessoa(nome, idade, ativo, chefe_id)
51values ('João Gabriel', 20, TRUE, 3);
52insert into endereco(rua, numero, bairro, cidade, pessoa_id)
53values ('Rua T59', 0, 'Bueno', 'Goiânia', 7);
54
55INSERT INTO pessoa(nome, idade, ativo, chefe_id)
56values ('Matheus Silva', 20, TRUE, 3);
57insert into endereco(rua, numero, bairro, cidade, pessoa_id)
58values ('Rua 3045', 0, 'Jardim das Oliveiras', 'Goiânia', 8);
59
60
61select *
62from pessoa;
63select *
64from endereco;
65
66
67SELECT MAX(idade)
68FROM pessoa;
69
70
71SELECT min(idade)
72from pessoa
73WHERE ativo is TRUE;
74
75
76SELECT AVG(idade)::float AS media_idade
77FROM pessoa;
78
79
80select *
81from pessoa
82where ativo is true
83 AND (nome like '%Luiz%' OR nome like '%Henrique%')
84order by idade;
85
86SELECT t1.id, t1.nome, e.cidade, e.rua, chefe.id as id_chefe, chefe.nome as nome_chefe
87from pessoa t1
88 join endereco e on t1.id = e.pessoa_id
89 left join pessoa chefe ON t1.chefe_id = chefe.id
90order by e.cidade;
91
92
93
94SELECT idade, count(idade) as quantidade
95from pessoa
96group by idade