Você está na página 1de 19

Introduo

 SQL = LDD + LMD + LCD


 Principais comandos:
 LDD:
 CREATE SCHEMA / TABLE / VIEW
 DROP SCHEMA / TABLE / VIEW
 ALTER TABLE

 LMD:
 SELECT, INSERT, UPDATE, DELETE

 LCD:
 GRANT, REVOKE

 Do ponto de vista de consulta, SQL uma linguagem


relacionalmente completa, ou seja, possui o mesmo poder
de expresso da lgebra e do clculo relacional

Definio de Dados em SQL


 Comando CREATE SCHEMA
 CREATE SCHEMA COMPANY AUTORIZATION JS;

 Comando CREATE TABLE


 CREATE TABLE <nome da tabela>
(<definies de colunas>
<definio da chave primria>
<definies de chaves alternativas>
<definies de chaves estrangeiras>);
 CREATE TABLE <esquema>.<nome da tabela>

Apostilas Ideal

Definio de Dados em SQL


Exemplo de um comando CREATE TABLE
CREATE TABLE EMPLOYEE
(FNAME
VARCHAR(15) NOT NULL,
MINIT
CHAR,
LNAME
VARCHAR(15) NOT NULL,
SSN
CHAR(9)
NOT NULL,

SUPERSSN
CHAR(9),
DNO
INT
NOT NULL,
PRIMARY KEY (SSN),
FOREIGN KEY (SUPERSSN) REFERENCES EMPLOYEE (SSN)
ON DELETE SET NULL,
FOREIGN KEY (DNO) REFERENCES DEPARTMENT (DNUMBER));

Definio de Dados em SQL


 Comando CREATE DOMAIN
CREATE DOMAIN TIPO_SSN AS CHAR(9);
CREATE TABLE EMPLOYEE
(...
SSN
TIPO_SSN
NOT NULL,
...);

 Especificao de restries sobre atributos


DNUMBER INT NOT NULL
CHECK (DNUMBER > 0 AND DNUMBER < 21)

Alternativamente:
CREATE DOMAIN D_NUMBER AS INTEGER
CHECK (D_NUMBER > 0 AND D_NUMBER < 21);
CREATE TABLE DEPARTMENT
(DNAME
VARCHAR(15) NOT NULL,
DNUMBER
D_NUMBER
NOT NULL,
...);

Apostilas Ideal

Definio de Dados em SQL


 Opes de remoo (clusula ON DELETE):
 CASCADE (propagao)
 SET NULL (substituio por nulos)
 SET DEFAULT (substituio por um valor default)
 Opo default: bloqueio (RESTRICT)

 As mesmas opes se aplicam clusula ON


UPDATE
Entretanto esta clusula NO deve ser utilizada para
se evitar que as chaves primrias sejam modificadas

Definio de Dados em SQL


Restrio de Integridade Referencial
FOREIGN KEY (SUPERSSN) REFERENCES EMPLOYEE(SSN)
ON DELETE SET NULL

FOREIGN KEY (DNO) REFERENCES DEPARTMENT(DNUMBER)


FOREIGN KEY (MGRSSN) REFERENCES EMPLOYEE(SSN)

FOREIGN KEY (DNUMBER) REFERENCES DEPARTMENT(DNUMBER)


ON DELETE CASCADE

FOREIGN KEY (DNUM) REFERENCES DEPARTMENT(DNUMBER)

FOREIGN KEY (ESSN) REFERENCES EMPLOYEE(SSN)

FOREIGN KEY (PNO) REFERENCES PROJECT(PNUMBER)

FOREIGN KEY (ESSN) REFERENCES EMPLOYEE(SSN)


ON DELETE CASCADE

Apostilas Ideal

Definio de Dados em SQL


Restrio de Integridade Referencial

Definio de Dados em em SQL


Restrio de Integridade Referencial
CREATE TABLE EMPLOYEE
(
SSN
CHAR(9)
NOT NULL,

SUPERSSN
CHAR(9),
DNO INT NOT NULL DEFAULT 1,
PRIMARY KEY (SSN),
FOREIGN KEY (SUPERSSN) REFERENCES
EMPLOYEE (SSN) ON DELETE SET NULL,
FOREIGN KEY (DNO) REFERENCES
DEPARTMENT (DNUMBER) ON DELETE SET DEFAULT
ON UPDATE CASCADE);

Apostilas Ideal

Definio de Dados em em SQL


Restrio de Integridade Referencial
CREATE TABLE EMPLOYEE
(,
DNO INT NOT NULL DEFAULT 1,
CONSTRAINT EMPPK
PRIMARY KEY (SSN),
CONSTRAINT EMPSUPERFK
FOREIGN KEY (SUPERSSN) REFERENCES
EMPLOYEE (SSN) ON DELETE SET NULL,
CONSTRAINT EMPDEPTFK
FOREIGN KEY (DNO) REFERENCES
DEPARTMENT (DNUMBER) ON DELETE SET DEFAULT
ON UPDATE CASCADE);

Definio de Dados em SQL


Comandos para Modificao de Esquema
 Comandos DROP SCHEMA e DROP TABLE
 DROP SCHEMA COMPANY CASCADE;
 DROP TABLE DEPENDENT CASCADE;

 Comando ALTER TABLE


 ALTER TABLE COMPANY.EMPLOYEE
ADD JOB VARCHAR(12);
 ALTER TABLE COMPANY.EMPLOYEE
DROP ADDRESS CASCADE;

Apostilas Ideal

Consultas Bsicas em SQL


 Formato bsico do comando SELECT:
SELECT <lista de atributos>
FROM <lista de tabelas>
WHERE <condio>;

 Exemplo:
SELECT BDATE, ADDRESS
FROM EMPLOYEE
WHERE FNAME=John AND
MINIT=B AND
LNAME=Smith;

Consultas Bsicas em SQL


 SELECT FNAME, LNAME, ADDRESS
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME=Research AND DNO=DNUMBER;
condio de seleo

condio de juno

 SELECT PNUMBER, DNUM, LNAME, ADDRESS, BDATE


FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE PLOCATION=Stafford AND
DNUM=DNUMBER AND MGRSSN=SSN;

Apostilas Ideal

Consultas Bsicas em SQL


 Atributos ambguos e pseudnimos (alias)
SELECT DNAME, DLOCATION
FROM DEPARTMENT, DEPT_LOCATIONS
WHERE DEPARTMENT.DNUMBER =
DEPT_LOCATIONS.DNUMBER;
SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME
FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.SUPERSSN=S.SSN;

Consultas Bsicas em SQL


 Consultas sem a clusula WHERE
SELECT SSN, LNAME, SALARY
FROM EMPLOYEE;
SELECT LNAME, DNAME
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER;
Ateno: A ausncia da clusula WHERE torna a
consulta acima um produto cartesiano das tabelas
EMPLOYEE e DEPARTMENT.

Apostilas Ideal

Consultas Bsicas em SQL


 Manipulando tabelas como conjuntos
SELECT SALARY
FROM EMPLOYEE;
No elimina linhas (tuplas) duplicatas
SELECT DISTINCT SALARY
FROM EMPLOYEE;
(SELECT PNUMBER
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNUM=DNUMBER AND MGRSSN=SSN AND
LNAME=Smith)
UNION
(SELECT PNUMBER
FROM PROJECT, WORKS_ON, EMPLOYEE
WHERE PNUMBER=PNO AND ESSN=SSN AND
LNAME=Smith);

Consultas Complexas em SQL


 Consultas aninhadas
SELECT FNAME, LNAME, ADDRESS
FROM EMPLOYEE
WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME=Research);

equivalente consulta
SELECT FNAME, LNAME, ADDRESS
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME=Research;

Apostilas Ideal

Consultas Complexas em SQL


 Comparao de conjuntos
SELECT DISTINCT PNUMBER
FROM PROJECT
WHERE PNUMBER IN (SELECT PNUMBER
FROM PROJECT, DEPARTMENT,
EMPLOYEE
WHERE DNUM =DNUMEBR AND
MGRSSN=SSN AND
LNAME=Smith)
OR
PNUMBER IN (SELECT PNO
FROM WORKS_ON, EMPLOYEE
WHERE ESSN=SSN AND
LNAME=Smith);

Consultas Complexas em SQL


 Comparao de conjuntos
SELECT DISTINCT ESSN
FROM WORKS_ON
WHERE (PNO, HOURS) IN (SELECT PNO, HOURS
FROM WORKS_ON
WHERE ESSN=123456789);
SELECT LNAME, FNAME
FROM EMPLOYEE
WHERE SALARY > ALL (SELECT SALARY

FROM EMPLOYEE
WHERE DNO=5);

Apostilas Ideal

10

Consultas Complexas em SQL


 Uso da funo EXISTS
SELECT E.FNAME, E.LNAME
FROM EMPLOYEE AS E
WHERE EXISTS (SELECT *
FROM DEPENDENT
WHERE E.SSN=ESSN AND
E.SEX=SEX AND
E.FNAME=DEPENDENT_NAME);
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE NOT EXISTS (SELECT *
FROM DEPENDENT
WHERE SSN=ESSN);

Consultas Complexas em SQL


 Uso do operador CONTAINS
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE ((SELECT PNO
FROM WORKS_ON
WHERE SSN=ESSN)
CONTAINS
(SELECT PNUMBER
FROM PROJECT
WHERE DNUM=5));
Esta consulta SQL corresponde a uma operao de diviso na
lgebra relacional

Apostilas Ideal

11

Facilidades Adicionais
 Uso do operador JOIN
SELECT FNAME, LNAME, ADDRESS
FROM (EMPLOYEE JOIN DEPARTMENT
ON DNO=DNUMBER)
WHERE DNAME=Research;
SELECT DNAME, DLOCATION
FROM (DEPARTMENT NATURAL JOIN DEPT_LOCATIONS);
SELECT FNAME, LNAME, DEPENDENT_NAME
FROM (EMPLOYEE LEFT OUTER JOIN DEPENDENT
ON SSN=ESSN);

Facilidades Adicionais
 Funes de agregao
SELECT SUM(SALARY), MAX(SALARY), MIN(SALARY),
AVG(SALARY)
FROM EMPLOYEE;
SELECT SUM(SALARY), MAX(SALARY), MIN(SALARY),
AVG(SALARY)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME=Research;
SELECT COUNT(*)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME=Research;

Apostilas Ideal

12

Facilidades Adicionais
 Agrupamento
SELECT DNO, COUNT(*), AVG(SALARY)
FROM EMPLOYEE
GROUP BY DNO;

Facilidades Adicionais
 Agrupamento com a clusula HAVING
SELECT PNUMBER, PNAME, COUNT(*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
HAVING COUNT(*) > 2;

Apostilas Ideal

13

3
3
3
3

Apostilas Ideal

14

Atualizaes em SQL
 Comando INSERT
INSERT INTO EMPLOYEE
VALUES (Richard,K,Marini,653258653,1962-12-30,
98 Oak Forest, Katy, TX,37000,987654321,4);
INSERT INTO EMPLOYEE(FNAME, LNAME, SSN, DNO)
VALUES (Richard,Marini,653258653,4);
INSERT INTO EMPLOYEE(FNAME, LNAME, SSN, DNO)
SELECT * FROM INPUT;

Atualizaes em SQL
 Comando DELETE
DELETE FROM EMPLOYEE
WHERE LNAME=Brown;
DELETE FROM EMPLOYEE
WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME=Research);
DELETE FROM EMPLOYEE;

Apostilas Ideal

15

Atualizaes em SQL
 Comando UPDATE
UPDATE PROJECT
SET PLOCATION=Bellaire, DNUM=5
WHERE PNUMBER=10;
UPDATE EMPLOYEE
SET SALARY=SALARY*1.1
WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME=Research);

Vises em SQL
 Uma viso em SQL uma tabela derivada de
tabelas base (definidas no esquema) de um
banco de dados ou de vises previamente
definidas
 Comando CREATE VIEW
 CREATE VIEW <nome da viso> [(<atributos>)]
AS <comando SELECT>;

 Vises simplificam a interface com o usurio e


constituem um mecanismo eficiente de seguraa

Apostilas Ideal

16

Vises em SQL
 Exemplos:
 WORKS_ON1(FNAME, LNAME, PNAME, HOURS)
CREATE VIEW WORKS_ON1
AS SELECT FNAME, LNAME, PNAME, HOURS
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE SSN=ESSN AND PNO=PNUMBER;
 DEPT_INFO (DEPT_NAME, NO_OF_EMPS, TOTAL_SAL)
CREATE VIEW DEPT_INFO (DEPT_NAME, NO_OF_EMPS,
TOTAL_SAL)
AS SELECT DNAME, COUNT(*), SUM(SALARY)
FROM DEPARTMENT, EMPLOYEE
WHERE DNUMBER=DNO
GROUP BY DNAME;

Vises em SQL
 Vises podem ser consultadas como qualquer
outra tabela
SELECT LNAME, HOURS
FROM WORKS_ON1
WHERE PNAME=ProductX;

 Vises sempre refletem o estado do banco de


dados  no so materializadas quando
definidas

Apostilas Ideal

17

Implementao de Vises
 Processamento de uma consulta sobre uma
viso  depende da estratgia adotada para
sua implementao
 Materizalizao da viso (view materialization)
 A consulta executada diretamente sobre a viso
materializada

 Modificao da consulta (query modification)


 A consulta modificada de acordo com a definio
da viso e ento executada sobre o banco de dados

Implementao de Vises
 Estratgia de modificao da consulta
SELECT LNAME, HOURS
FROM WORKS_ON1
WHERE PNAME=ProductX;

SELECT LNAME, HOURS


FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE SSN=ESSN AND
PNO=PNUMBER AND
PNAME=ProductX;

Apostilas Ideal

18

Atualizao de Vises
 Em geral, vises no podem ser atualizadas
 Por exemplo, seja a seguinte operao de
atualizao sobre a viso WORKS_ON1:
UPDATE WORKS_ON1
SET PNAME=ProductY
WHERE LNAME=Smith AND FNAME=John AND
PNAME=ProductX;
Como propagar esta atualizao para as tabelas base?

Atualizao de Vises
 Opes para atualizao de WORKS_ON1
 Opo 1:
UPDATE WORKS_ON
SET PNO=(SELECT PNUMBER FROM PROJECT
WHERE PNAME=ProductY)
WHERE ESSN=(SELECT SSN FROM EMPLOYEE
WHERE LNAME=Smith AND
FNAME=John) AND
PNO=(SELECT PNUMBER FROM PROJECT
WHERE PNAME=ProductX);

 Opo 2 (menos elaborada):


UPDATE PROJECT
SET PNAME=ProductY
WHERE PNAME=ProductX;

Apostilas Ideal

19

Atualizao de Vises
 Vises definidas sobre uma nica tabela so
atualizveis se seus atributos incluem a chave
primria (ou uma das chave alternativas) da
tabela base
 Vises definidas sobre mltiplas relaes
atravs de junes em geral no so
atualizveis
 Vises definidas usando-se agrupamento e
funes de agregao no so atualizveis

Restries de Integridade Gerais


 Comando CREATE ASSERTION
CREATE ASSERTION SALARY-CONSTRAINT
CHECK (NOT EXISTS(SELECT *
FROM EMPLOYEE E, EMPLOYEE M,
DEPARTMENT D
WHERE E.SALARY>M.SALARY AND
E.DNO=D.DNUMBER AND
D.MGRSSN=M.SSN));

 Clusula CHECK
CREATE DOMAIN D_NUMBER AS INTEGER
CHECK (D_NUMBER > 0 AND D_NUMBER < 21);

Apostilas Ideal

20