Escolar Documentos
Profissional Documentos
Cultura Documentos
Apostila 1
Apostila 1
D17108BP10
Produo 1.0
Junho 2004
D39572
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Autor
Nancy Greenberg
Wayne Abbott
Christian Bauwens
Perry Benson
Brian Boxx
Zarko Cesljas
Dairy Chan
Laszlo Czinkoczki
Marjolein Dekkers
Matthew Gregory
Stefan Grenstad
Joel Goodman
Rosita Hanoman
Sushma Jagannath
Angelika Krupp
Christopher Lawless
Marcelo Manzano
Isabelle Marchand
Malika Marghadi
Valli Pataballa
Elspeth Payne
Ligia Jasmin Robayo
Bryan Roberts
Helen Robertson
Lata Shivaprasad
John Soltani
Priya Vennapusa
Ken Woolfe
Editor
Nita K. Brozowski
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Revisores e
Colaboradores Tcnicos
Contedo
Introduo
Objetivos da Lio I-2
Metas do Curso I-3
Oracle10g I-4
Banco de Dados Oracle 10g I-6
Oracle Application Server 10g I-7
Oracle Enterprise Manager 10g Grid Control I-8
Sistemas de Gerenciamento de Banco de Dados Relacional e Banco de Dados
Relacional de Objeto I-9
Plataforma Oracle para a Internet I-10
Ciclo de Vida de Desenvolvimento do Sistema I-11
Armazenamento de Dados em Diferentes Mdias I-13
Conceito de Banco de Dados Relacional I-14
Definio de um Banco de Dados Relacional I-15
Modelos de Dados I-16
Modelo de Relacionamento entre Entidades I-17
Convenes de Modelagem de Relacionamento entre Entidades I-19
Relacionando Vrias Tabelas I-21
Terminologia do Banco de Dados Relacional I-23
Propriedades do Banco de Dados Relacional I-25
Comunicando-se com um RDBMS por Meio de SQL I-26
Sistema de Gerenciamento de Banco de Dados Relacional da Oracle I-27
Instrues SQL I-28
Tabelas Usadas no Curso I-29
Sumrio I-30
1
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Prefcio
iv
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
v
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
vii
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Manipulando Dados
Objetivos 8-2
Data Manipulation Language 8-3
Adicionando uma Nova Linha a uma Tabela 8-4
Sintaxe da Instruo INSERT 8-5
Inserindo Novas Linhas 8-6
Inserindo Linhas com Valores Nulos 8-7
Inserindo Valores Especiais 8-8
Inserindo Valores de Data Especficos 8-9
Criando um Script 8-10
Copiando Linhas de Outra Tabela 8-11
Alterando Dados de uma Tabela 8-12
Sintaxe da Instruo UPDATE 8-13
Atualizando Linhas de uma Tabela 8-14
Atualizando Duas Colunas com uma Subconsulta 8-15
Atualizando Linhas com Base em Outra Tabela 8-16
Removendo uma Linha de uma Tabela 8-17
Instruo DELETE 8-18
Deletando Linhas de uma Tabela 8-19
Deletando Linhas com Base em Outra Tabela 8-20
Instruo TRUNCATE 8-21
Usando uma Subconsulta em uma Instruo INSERT 8-22
Transaes de Banco de Dados 8-24
Vantagens das Instrues COMMIT e ROLLBACK 8-26
Controlando Transaes 8-27
Fazendo Rollback de Alteraes at um Marcador 8-28
Processamento de Transao Implcita 8-29
Estado dos Dados antes de COMMIT ou ROLLBACK 8-31
Estado dos Dados aps COMMIT 8-32
Submetendo Dados a Commit 8-33
Estado dos Dados aps ROLLBACK 8-34
Rollback no Nvel de Instruo 8-36
Consistncia de Leitura 8-37
Implementao da Consistncia de Leitura 8-38
Sumrio 8-39
Exerccio 8: Viso Geral 8-40
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
ix
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
x
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Sinnimos 10-37
Criando e Removendo Sinnimos 10-39
Sumrio 10-40
Exerccio 10: Viso Geral da Parte 2 10-41
Prefcio
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Perfil
Antes de Iniciar o Curso
Antes de iniciar este curso, voc dever ser capaz de usar uma GUI (interface grfica do
usurio). Como pr-requisito, necessrio que o aluno tenha familiaridade com os conceitos
e as tcnicas de processamento de dados.
Organizao deste Curso
O curso Banco de Dados Oracle 10g: Fundamentos de SQL I orientado por instrutor e
inclui palestras e exerccios prticos. As sesses de demonstrao on-line e os exerccios
reforam as tcnicas e os conceitos apresentados.
Prefcio-3
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Publicaes Relacionadas
Publicaes Oracle
Ttulo
Part Number
(Nmero do Componente)
B10755-01
B10743-01
Publicaes Adicionais
Arquivos readme
Oracle Magazine
Prefcio-4
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Convenes Tipogrficas
A seguir, so fornecidas duas listas de convenes tipogrficas usadas especificamente
no texto ou no cdigo.
Convenes Tipogrficas do Texto
Objeto ou Termo
Exemplo
Use o comando SELECT para exibir
informaes armazenadas na coluna
LAST_NAME da tabela EMPLOYEES.
o nome da atribuio
a ser criada.
Itlico
Aspas
Livros, nomes de
cursos e
manuais,
palavras ou frases
enfatizadas
Prefcio-5
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Conveno
Letras
maisculas
Comandos,
functions
SELECT employee_id
FROM employees;
. . .
OG_ACTIVATE_LAYER
(OG_GET_LAYER (prod_pie_layer))
. . .
SELECT last_name
FROM employees;
Negrito
Texto a ser
CREATE USER scott
especificado por um IDENTIFIED BY tiger;
usurio
Prefcio-6
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Introduo
Objetivos da Lio
Ao concluir esta lio, voc ser capaz de:
Objetivos
Nesta lio, voc compreender o RDBMS (Relational Database Management System) e o
ORDBMS (Object Relational Database Management System). Tambm sero apresentadas
informaes sobre:
Instrues SQL especficas do Oracle
O iSQL*Plus, que um ambiente usado para executar instrues SQL e para fins de
formatao e gerao de relatrios
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-2
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Metas do Curso
Metas do Curso
Este curso apresenta a tecnologia de banco de dados Oracle 10g. No curso, voc aprender
os conceitos bsicos de bancos de dados relacionais e a avanada linguagem de
programao SQL. O curso fornece as habilidades essenciais em SQL que permitem criar
consultas em uma ou mais tabelas, manipular dados em tabelas, criar objetos de banco de
dados e consultar metadados.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-3
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Oracle10g
Confiabilidade
Modelo de
desenvolvimento
nico
Gerenciamento
unificado
Conjuntos de
recursos comuns
Recursos do Oracle10g
A release Oracle10g oferece uma infra-estrutura completa e de alto desempenho
que inclui:
Escalabilidade de departamentos at sites de e-business da empresa
Arquitetura segura, disponvel, confivel e avanada
Um modelo de desenvolvimento; opes de disponibilizao fcil
Aproveitamento do conjunto de recursos atuais de uma organizao por meio da
plataforma Oracle (incluindo SQL, PL/SQL, Java e XML)
Uma interface de gerenciamento para todas as aplicaes
Tecnologias padro do setor; sem bloqueios proprietrios
Alm de oferecer as vantagens relacionadas acima, a release Oracle10g contm o banco de
dados para a grade. A computao em grade pode diminuir drasticamente o custo de
computao, aumentar a disponibilidade dos recursos de computao e proporcionar mais
produtividade e qualidade.
A idia bsica da computao em grade a noo de computao como um servio
pblico, em analogia rede de energia eltrica ou rede telefnica. Como cliente da
grade, voc no se importa com o local onde os dados so mantidos ou onde realizada a
computao. Voc deseja que a computao seja concluda e que as informaes sejam
fornecidas quando especificado. No lado servidor, a grade refere-se a virtualizao e
provisionamento. Voc agrupa todos os recursos, provisiona-os dinamicamente com base
nas necessidades da sua empresa e, como conseqncia, obtm maior eficincia na
utilizao desses recursos.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-4
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Um
fornecedor
Escalabilidade
Oracle10g
Estes so os trs produtos da infra-estrutura em grade da release Oracle10g:
Oracle Database 10g
Oracle Application Server 10g
Oracle Enterprise Manager 10g Grid Control
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-5
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Oracle10g
Documentos
Mensagens
Multimdia
Aplicaes transacionais
Integrao
Estrutura de
desenvolvimento
de aplicaes
Servidor de
aplicaes
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-7
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Business intelligence
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-9
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Lgica de
negcios
e dados
Bancos
de dados
Lgica de
apresentao
e negcios
Servidores de
aplicaes
Servios de rede
SQL
PL/SQL
Java
Ferramentas de desenvolvimento
Gerenciamento do sistema
Qualquer
Qualquer
Qualquer
browser cliente de e-mail cliente FTP
Estratgia
e anlise
Desenvolvimento
e documentao
Transio
Produo
Projeto
Estratgia
e anlise
Desenvolvimento
e documentao
Transio
Produo
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-12
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Projeto
Planilha
eletrnica
Armrio de arquivo
Banco de dados
Armazenando Informaes
Toda organizao tem necessidades de informaes. Uma biblioteca mantm uma lista de
membros, livros, datas de vencimento e multas. Uma empresa precisa guardar informaes
sobre funcionrios, departamentos e salrios. Essas informaes so chamadas de dados.
As organizaes podem armazenar dados em vrias mdias e em formatos diferentes; por
exemplo, um documento impresso em um armrio de arquivo ou dados armazenados em
planilhas eletrnicas ou em bancos de dados.
Um banco de dados um conjunto organizado de informaes.
Para gerenciar bancos de dados, necessrio um DBMS (Database Management System).
Um DBMS um programa que armazena, recupera e modifica dados de bancos de dados
sob demanda. Existem quatro tipos principais de bancos de dados: hierrquico, de rede,
relacional e (recentemente) relacional de objeto.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-13
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Armazenamento de Dados
em Diferentes Mdias
Modelo Relacional
Os princpios do modelo relacional foram descritos primeiramente pelo Dr. E. F. Codd em
um trabalho de junho de 1970 intitulado "A Relational Model of Data for Large Shared
Data Banks". Nesse trabalho, o Dr. Codd propunha o modelo relacional para sistemas de
banco de dados.
Os modelos comuns usados na poca eram o hierrquico e o de rede, ou at mesmo
estruturas de dados simples de flat files. Logo depois, o RDBMS (Relational Database
Management System) tornou-se muito popular, especialmente pela facilidade de uso e
flexibilidade em termos de estrutura. Alm disso, vrios fornecedores inovadores, como a
Oracle, complementaram o RDBMS com um conjunto de produtos eficientes para usurios
e desenvolvedores de aplicaes, que compunham uma soluo integral.
Componentes do Modelo Relacional
Conjuntos de objetos ou relaes que armazenam os dados
Um conjunto de operadores que age sobre as relaes para produzir outras relaes
Integridade de dados para preciso e consistncia
Para obter mais informaes, consulte An Introduction to Database Systems, Eighth Edition
(Addison-Wesley: 2004), escrito por Chris Date.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-14
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Nome da tabela:
EMPLOYEES
Nome da tabela:
DEPARTMENTS
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-15
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Servidor
Oracle
Modelo de
sistema
imaginado
pelo cliente
Modelo de entidade
do modelo do cliente
Modelo de tabela
do modelo de entidade
Servidor
Oracle
Tabelas em disco
Copyright 2004, Oracle. Todos os direitos reservados.
Modelos de Dados
Os modelos constituem a base do projeto. Os engenheiros desenvolvem o modelo de um
carro para aperfeioar os detalhes antes de produzi-lo. Da mesma forma, os designers de
sistemas desenvolvem modelos para explorar idias e compreender melhor o projeto do
banco de dados.
Finalidade dos Modelos
Os modelos ajudam a comunicar os conceitos imaginados pelas pessoas. possvel us-los
com os seguintes objetivos:
Comunicar
Categorizar
Descrever
Especificar
Investigar
Desenvolver
Analisar
Imitar
O objetivo produzir um modelo que atenda a vrios desses usos, seja compreendido por
um usurio final e contenha detalhes suficientes para que um desenvolvedor crie um sistema
de banco de dados.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-16
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Modelos de Dados
DEPARTMENT
#*
number
*
name
composto de o
location
designado a
Cenrio
Modelagem de ER
Em um sistema eficiente, os dados so divididos em entidades ou categorias discretas. Um
modelo de ER (Entity Relationship) uma ilustrao de vrias entidades em uma empresa e
dos relacionamentos entre elas. Um modelo de ER derivado de especificaes de negcios
ou narrativas e criado durante a fase de anlise do ciclo de vida de desenvolvimento do
sistema. Os modelos de ER separam as informaes necessrias a uma empresa das
atividades realizadas por ela. Embora as empresas possam mudar de atividades, o tipo de
informaes tende a permanecer constante. Portanto, as estruturas de dados tambm tendem
a permanecer constantes.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-17
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Modelagem de ER (continuao)
Vantagens da Modelagem de ER
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-18
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Componentes Principais
Convenes de Modelagem de
Relacionamento entre Entidades
EMPLOYEE
#*
number
*
name
o
job title
Atributo
Nome singular
Letras minsculas
Obrigatrio marcado com *
Opcional marcado com "o"
DEPARTMENT
#*
number
*
name
composto de o
location
designado a
Convenes da Modelagem de ER
Entidades
Para representar uma entidade em um modelo, use as seguintes convenes:
Nome de entidade exclusivo, singular
Nome de entidade em maisculas
Caixa editvel
Nomes de sinnimos opcionais em maisculas entre parnteses: ( )
Atributos
Para representar um atributo em um modelo, use as seguintes convenes:
Nome singular em minsculas
Tag de asterisco (*) para atributos obrigatrios (isto , valores que devem ser
conhecidos)
Tag de letra "o" para atributos opcionais (isto , valores que podem ser conhecidos)
Relacionamentos
Smbolo
Descrio
Linha tracejada
Linha slida
P-de-galinha
Linha nica
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-19
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Entidade
Convenes de Modelagem de
Relacionamento entre Entidades
EMPLOYEE
#*
number
*
name
o
job title
Atributo
Nome singular
Letras minsculas
Obrigatrio marcado com *
Opcional marcado com "o"
DEPARTMENT
#*
number
*
name
composto de o
location
designado a
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-20
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Entidade
Chave primria
Chave estrangeira
Chave primria
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-21
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-22
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
4
5
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-23
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
6. Um campo pode no conter um valor. Nesse caso, seu valor nulo. Na tabela
EMPLOYEES, somente os funcionrios com a atribuio de representante de vendas
possuem um valor no campo COMMISSION_PCT (comisso).
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-24
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-25
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
A instruo enviada
ao servidor Oracle.
Servidor
Oracle
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-26
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT department_name
FROM
departments;
Tabelas de usurios
Dicionrio
de dados
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-27
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Servidor
Oracle
SELECT
INSERT
UPDATE
DELETE
MERGE
CREATE
ALTER
DROP
RENAME
TRUNCATE
COMMENT
COMMIT
ROLLBACK Controle de transaes
SAVEPOINT
GRANT
REVOKE
Instrues SQL
O Oracle SQL adota os padres aceitos pelo setor. Para assegurar a compatibilidade
futura com os padres em desenvolvimento, a Oracle Corporation mantm ativamente
uma equipe especializada nos comits de padres SQL. Os comits aceitos pelo setor so
o ANSI (American National Standards Institute) e o ISO (International Standards
Organization). Os dois comits aceitam SQL como a linguagem padro para os bancos de
dados relacionais.
Instruo
Descrio
SELECT
INSERT
UPDATE
DELETE
MERGE
CREATE
ALTER
DROP
RENAME
TRUNCATE
COMMENT
COMMIT
ROLLBACK
SAVEPOINT
GRANT
REVOKE
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-28
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Instrues SQL
DEPARTMENTS
JOB_GRADES
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-29
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
EMPLOYEES
Sumrio
Os sistemas de gerenciamento de banco de dados relacional so compostos de objetos
ou relaes. Eles so gerenciados por operaes e regidos por constraints de integridade de
dados.
A Oracle Corporation cria produtos e servios para atender s suas necessidades de
RDBMS. Os principais produtos so:
Oracle Database 10g, com o qual voc armazena e gerencia informaes por meio de
SQL
Oracle Application Server 10g, com o qual voc executa todas as aplicaes
Oracle Enterprise Manager 10g Grid Control, usado para gerenciar e automatizar
tarefas administrativas nos conjuntos de sistemas de um ambiente de grade.
SQL
O servidor Oracle suporta instrues SQL com o padro ANSI e contm extenses. Com a
linguagem SQL, possvel estabelecer comunicao com o servidor para acessar, manipular
e controlar dados.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I I-30
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Sumrio
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Objetivos
Ao concluir esta lio, voc ser capaz de:
Listar os recursos das instrues SQL SELECT
Executar uma instruo SELECT bsica
Diferenciar instrues SQL de comandos iSQL*Plus
Objetivos
Para extrair dados do banco de dados, necessrio usar a instruo SQL (Structured Query
Language) SELECT. Talvez voc precise restringir as colunas exibidas. Esta lio descreve
todas as instrues SQL necessrias para executar essas aes. Voc pode criar instrues
SELECT para usar mais de uma vez.
Esta lio tambm aborda o ambiente iSQL*Plus no qual as instrues SQL so executadas.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-2
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Projeo
Seleo
Tabela 1
Tabela 1
Join
Tabela 1
Tabela 2
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-3
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-5
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT *
FROM
departments;
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-6
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-7
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
iSQL*Plus:
SQL*Plus:
alinhados esquerda
Expresses Aritmticas
Crie expresses com dados de nmero e data usando
operadores aritmticos.
Descrio
Somar
Subtrair
Multiplicar
Dividir
Expresses Aritmticas
Talvez voc precise modificar a forma como os dados so exibidos, realizar clculos ou
examinar cenrios hipotticos. Todas essas aes so possveis com o uso de expresses
aritmticas. Uma expresso aritmtica pode conter nomes de colunas, valores numricos
constantes e operadores aritmticos.
Operadores Aritmticos
O slide lista os operadores aritmticos disponveis em SQL. Voc pode usar operadores
aritmticos em qualquer clusula de uma instruo SQL (exceto na clusula FROM).
Observao: Nos tipos de dados DATE e TIMESTAMP, s possvel usar os operadores de
adio e subtrao.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-9
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Operador
Precedncia de Operadores
SELECT last_name, salary, 12*salary+100
FROM
employees;
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-11
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Valores Nulos
Se, em uma coluna especfica, uma linha no contiver um valor de dados, o valor ser nulo
ou conter um valor nulo.
Um valor nulo no est disponvel nem designado e no conhecido ou aplicvel. Um valor
nulo diferente de zero ou de um espao. Zero um nmero e um espao um caractere.
As colunas de qualquer tipo de dados podem conter valores nulos. No entanto, algumas
constraints (NOT NULL e PRIMARY KEY) impedem o uso de valores nulos em colunas.
Na coluna COMMISSION_PCT da tabela EMPLOYEES, observe que apenas um gerente de
vendas ou um representante de vendas pode receber comisso. Os outros funcionrios no
tm direito a comisses. Um valor nulo representa essa situao.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-12
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Valores Nulos
em Expresses Aritmticas
As expresses aritmticas que contm um valor nulo
so avaliadas como nulas.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-13
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Apelidos de Colunas
Quando exibe o resultado de uma consulta, o iSQL*Plus geralmente usa o nome da coluna
selecionada como seu cabealho. Como esse cabealho pode no ser descritivo, talvez seja
difcil compreend-lo. Para alterar um cabealho de coluna, use um apelido.
Especifique o apelido aps a coluna na lista SELECT usando um espao como separador.
Por default, os cabealhos de apelidos aparecem em maisculas. Se o apelido contiver
espaos ou caracteres especiais (como # ou $), ou se fizer distino entre maisculas e
minsculas, delimite-o por aspas duplas (" ").
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-14
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
til em clculos
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-15
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Operador de Concatenao
last_name||job_id AS "Employees"
employees;
Operador de Concatenao
Voc pode vincular uma coluna a outras colunas, expresses aritmticas ou valores de
constantes para criar uma expresso de caracteres usando o operador de concatenao (||).
As colunas nos dois lados do operador so combinadas para formar uma nica coluna de
sada.
No exemplo, LAST_NAME e JOB_ID so concatenadas e recebem o apelido Employees.
Observe que o sobrenome do funcionrio e o cdigo do cargo so combinados para formar
uma nica coluna de sada.
A palavra-chave AS antes do apelido facilita a leitura da clusula SELECT.
Valores Nulos com o Operador de Concatenao
Se voc concatenar um valor nulo com uma string de caracteres, o resultado ser uma string
de caracteres. LAST_NAME || NULL resulta em LAST_NAME.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-16
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Um operador de concatenao:
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-17
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-18
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-19
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Linhas Duplicadas
A exibio default de consultas mostra todas as linhas,
inclusive as linhas duplicadas.
Linhas Duplicadas
A menos que seja feita outra especificao, o iSQL*Plus exibe os resultados de uma
consulta sem eliminar as linhas duplicadas. O primeiro exemplo do slide exibe todos os
nmeros de departamentos da tabela EMPLOYEES. Observe que os nmeros de
departamentos so repetidos.
Para eliminar linhas duplicadas do resultado, inclua a palavra-chave DISTINCT na clusula
SELECT logo aps a palavra-chave SELECT. No segundo exemplo do slide, a tabela
EMPLOYEES contm, na verdade, 20 linhas, mas existem apenas sete nmeros de
departamentos exclusivos na tabela.
Voc pode especificar vrias colunas aps o qualificador DISTINCT. Esse qualificador
afeta todas as colunas selecionadas e o resultado so todas as combinaes distintas das
colunas.
SELECT DISTINCT department_id, job_id
FROM employees;
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-20
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT department_id
FROM
employees;
Instrues SQL
Servidor
Oracle
Comandos
iSQL*Plus
Resultados de consultas
Relatrio formatado
Cliente
SQL e iSQL*Plus
SQL uma linguagem de comandos para a comunicao com o servidor Oracle a partir de
qualquer ferramenta ou aplicao. O Oracle SQL contm vrias extenses.
iSQL*Plus uma ferramenta Oracle que reconhece e submete instrues SQL ao servidor
Oracle para execuo e contm sua prpria linguagem de comandos.
Recursos de SQL
Pode ser usada por vrios usurios, incluindo aqueles com pouca ou nenhuma
experincia em programao
uma linguagem no procedural
uma linguagem semelhante ao idioma ingls
Recursos de iSQL*Plus
acessado de um browser
Aceita instrues SQL
Possibilita a edio on-line para modificar instrues SQL
Controla definies de ambiente
Formata resultados de consultas em um relatrio bsico
Acessa bancos de dados locais e remotos
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-21
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Browser de
Internet
SQL
Uma linguagem
Padro ANSI
No possvel abreviar
palavras-chave.
As instrues
manipulam dados e
definies de tabelas no
banco de dados.
iSQL*Plus
Um ambiente
Propriedade Oracle
possvel abreviar palavraschave.
Os comandos no permitem
a manipulao de valores no
banco de dados.
Executado em um browser
Carregado centralmente; no
precisa ser implementado em
cada mquina
Instrues
SQL
Comandos
iSQL*Plus
iSQL*Plus
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-22
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
iSQL*Plus
O iSQL*Plus um ambiente no qual voc pode:
Executar instrues SQL para recuperar, modificar, adicionar e remover dados no
banco de dados
Formatar, armazenar e imprimir resultados de consultas na forma de relatrios, bem
como realizar clculos com base nesses resultados
Criar arquivos de script a fim de armazenar instrues SQL para uso futuro
possvel dividir os comandos iSQL*Plus nestas principais categorias:
Categoria
Objetivo
Ambiente
Formato
Manipulao de
arquivos
Execuo
Edio
Interao
Diversos
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-23
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-24
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
No ambiente de browser:
Ambiente iSQL*Plus
Ambiente iSQL*Plus
No browser, a pgina Workspace do iSQL*Plus tem as seguintes reas principais:
1. Caixa de texto: rea em que voc digita os comandos iSQL*Plus e as instrues SQL
2. Boto Execute: Clique neste boto para executar os comandos e as instrues da caixa
de texto
3. Boto Load Script: Exibe um form que permite identificar um caminho e um nome de
arquivo, ou um URL, com os comandos SQL, PL/SQL ou SQL*Plus a serem inseridos
na caixa de texto
4. Boto Save Script: Salva o contedo da caixa de texto em um arquivo
5. Boto Cancel: Interrompe a execuo do comando na caixa de texto
6. Boto Clear Screen: Clique neste boto para remover o texto contido na caixa
7. cone Logout: Clique nele para encerrar a sesso do iSQL*Plus e retornar pgina
Login do iSQL*Plus
8. cone Preferences: Clique nele para alterar a configurao da interface, a
configurao do sistema ou a senha
9. cone Help: Permite acesso documentao de ajuda do iSQL*Plus
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-25
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-26
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
DESC[RIBE] tablename
Descrio
NUMBER(p,s)
VARCHAR2(s)
DATE
CHAR(s)
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-27
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
DESCRIBE employees
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-28
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-29
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-30
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
D:\TEMP\emp_data.sql
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-31
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-32
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-33
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
2
3
Preferncias do iSQL*Plus
Para definir preferncias relativas sesso do iSQL*Plus, clique no cone Preferences.
As preferncias so divididas em categorias. possvel definir preferncias
relacionadas formatao e execuo de scripts, bem como administrao de banco
de dados. Voc tambm pode alterar sua senha.
Quando voc escolhe uma categoria de preferncia, um form exibido e permite
definir as preferncias dessa categoria.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-34
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-35
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Definindo a Preferncia de
Localizao da Sada
Sumrio
Nesta lio, voc aprendeu a:
Criar uma instruo SELECT que:
descritivos
Instruo SELECT
Nesta lio, voc aprendeu a recuperar dados de uma tabela do banco de dados com a
instruo SELECT.
SELECT
FROM
Na sintaxe:
SELECT
*
DISTINCT
column|expression
alias
FROM table
iSQL*Plus
iSQL*Plus um ambiente de execuo que permite enviar instrues SQL ao servidor de
banco de dados, bem como editar e salvar essas instrues. possvel executar as instrues
no prompt SQL ou em um arquivo de script.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-36
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Usando o iSQL*Plus
Alguns exerccios podem ser antecedidos pelas expresses "Se tiver tempo" ou "Se quiser
tomar parte em mais um desafio". Faa esses exerccios somente quando terminar todos os
outros no tempo designado e se desejar mais um desafio para testar suas habilidades.
Desenvolva os exerccios devagar e com preciso. Como teste, voc pode salvar e executar
arquivos de comandos Em caso de dvidas, consulte o instrutor.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-37
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 1
Parte 1
Verdadeiro/Falso
4. Esta instruo SELECT executada com xito:
SELECT *
FROM
job_grades;
Verdadeiro/Falso
5. H quatro erros de codificao na instruo a seguir. Voc consegue identific-los?
SELECT
sal x 12
FROM
employee_id, last_name
ANNUAL SALARY
employees;
Parte 2
Observe o seguinte local dos arquivos de laboratrio:
E:\labs\\SQL1\labs
Se voc receber uma solicitao para salvar esses arquivos, salve-os nesse local
Para iniciar o iSQL*Plus, inicie o browser. necessrio informar um URL para acessar o
iSQL*Plus. O URL requer o nome do host, que ser fornecido pelo instrutor. Informe o
comando a seguir, substituindo o nome do host pelo valor fornecido pelo instrutor:
http://<HOSTNAME:5561>/isqlplus
Voc foi admitido como programador SQL da Acme Corporation. Sua primeira tarefa
criar alguns relatrios com base nos dados das tabelas de recursos humanos.
6. Sua primeira tarefa determinar a estrutura da tabela DEPARTMENTS e seu
contedo.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-38
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-39
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 1 (continuao)
9. O departamento de recursos humanos precisa de uma consulta para exibir todos os
cdigos de cargo exclusivos da tabela EMPLOYEES.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-40
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 1 (continuao)
8. Teste a consulta no arquivo lab_01_07.sql para verificar se executada
corretamente.
11. O departamento de recursos humanos solicitou um relatrio de todos os funcionrios
e os respectivos IDs de cargo. Exiba o sobrenome concatenado com o ID do cargo
(separado por uma vrgula e um espao) e nomeie a coluna como Employee and
Title.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-41
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 1 (continuao)
Parte 3
Se tiver tempo, faa os seguintes exerccios:
10. O departamento de recursos humanos deseja cabealhos de coluna mais
descritivos em seu relatrio sobre funcionrios. Copie a instruo de
lab_01_07.sql para a caixa de texto do iSQL*Plus. Nomeie os cabealhos
de coluna como Emp #, Employee, Job e Hire Date, respectivamente.
Execute a consulta novamente.
Exerccio 1 (continuao)
Se quiser tomar parte em mais um desafio, faa este exerccio:
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 1-42
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
12. Para se familiarizar com os dados da tabela EMPLOYEES, crie uma consulta para
exibir todos os dados dessa tabela. Separe cada sada de coluna com uma vrgula.
Nomeie o ttulo da coluna como THE_OUTPUT.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Objetivos
Ao concluir esta lio, voc ser capaz de:
Limitar as linhas recuperadas por uma consulta
Classificar as linhas recuperadas por uma consulta
Usar a substituio com E comercial no iSQL*Plus
para restringir e classificar a sada em runtime
Objetivos
Durante a recuperao de dados do banco de dados, talvez seja necessrio:
Restringir as linhas de dados a serem exibidas
Especificar a ordem de exibio das linhas
Esta lio explica as instrues SQL usadas para executar essas aes.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-2
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
"recuperar todos
os funcionrios do
departamento 90"
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-3
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
EMPLOYEES
Nome de coluna
Condio de comparao
Nome de coluna, constante ou lista de valores
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-4
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-5
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-6
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Condies de Comparao
Significado
Igual a
>
Maior que
>=
<
Menor que
<=
<>
Diferente de
BETWEEN
...AND...
IN(set)
LIKE
Corresponde a qualquer
valor
de uma lista
Corresponde
a um padro de
IS NULL
caractere
um valor nulo
Condies de Comparao
As condies de comparao so usadas em condies que comparam uma expresso a
outro valor ou expresso. Elas so usadas na clusula WHERE no seguinte formato:
Sintaxe
... WHERE expr operator value
Exemplo
... WHERE hire_date='01-JAN-95'
... WHERE salary >=6000
... WHERE last_name='Smith'
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-7
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Operador
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-8
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-9
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Usando a Condio IN
Use a condio de associao IN para testar os valores
de uma lista:
Usando a Condio IN
Para testar os valores de um conjunto de valores especificado, use a condio IN. Essa
condio tambm conhecida como condio de associao.
O exemplo do slide exibe nmeros de funcionrios, sobrenomes, salrios e nmeros de
funcionrio de gerentes relativos a todos os funcionrios cujo nmero de funcionrio do
gerente seja 100, 101 ou 201.
possvel usar a condio IN com qualquer tipo de dados. O exemplo a seguir retorna uma
linha da tabela EMPLOYEES para cada funcionrio cujo sobrenome est includo na lista de
nomes da clusula WHERE:
SELECT employee_id, manager_id, department_id
FROM employees
WHERE last_name IN ('Hartstein', 'Vargas');
Se forem usados caracteres ou datas na lista, eles devero ser delimitados por aspas simples
('').
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-10
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
first_name
employees
first_name LIKE 'S%' ;
Descrio
A instruo SELECT do slide retorna, com base na tabela EMPLOYEES, os nomes de todos
os funcionrios que comeam com a letra S. Observe o S maisculo. Os nomes que
comeam com s no so retornados.
possvel usar a condio LIKE como um atalho para algumas comparaes BETWEEN. O
exemplo a seguir exibe os sobrenomes e as datas de admisso de todos os funcionrios
admitidos entre janeiro de 1995 e dezembro de 1995:
SELECT last_name, hire_date
FROM employees
WHERE hire_date LIKE '%95';
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-11
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
A opo ESCAPE identifica a barra invertida (\) como o caractere de escape. No padro, o
caractere de escape precede o sublinhado (_). Isso faz com que o Oracle Server interprete o
sublinhado literalmente.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-12
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT last_name
FROM
employees
WHERE last_name LIKE '_o%' ;
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-13
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Condies Lgicas
Significado
AND
OR
NOT
Condies Lgicas
Uma condio lgica combina o resultado de duas condies componentes para produzir
um nico resultado com base nessas condies, ou inverte o resultado de uma nica
condio. S ser retornada uma linha se o resultado geral da condio for verdadeiro.
Trs operadores lgicos esto disponveis em SQL:
AND
OR
NOT
Todos os exemplos at ento especificaram apenas uma condio na clusula WHERE. Voc
pode usar vrias condies em uma clusula WHERE com os operadores AND e OR.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-14
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Operador
TRUE
TRUE
FALSE
NULL
FALSE
FALSE
FALSE
FALSE
NULL
NULL
FALSE
NULL
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-15
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
FROM
WHERE
AND
Usando o Operador OR
OR exige que uma das condies seja verdadeira:
employee_id, last_name, job_id, salary
employees
salary >= 10000
job_id LIKE '%MAN%' ;
Usando o Operador OR
No exemplo, uma das duas condies poder ser verdadeira para que sejam selecionados
registros. Portanto, os funcionrios cujos IDs de cargo contiverem a string 'MAN' ou que
receberem US$ 10.000 ou mais sero selecionados.
Tabela de Valores Verdadeiros com OR
A tabela a seguir mostra os resultados da combinao de duas expresses com OR:
OR
TRUE
FALSE
NULL
TRUE
TRUE
TRUE
TRUE
FALSE
TRUE
FALSE
NULL
NULL
TRUE
NULL
NULL
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-16
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
FROM
WHERE
OR
TRUE
FALSE
FALSE
TRUE
NULL
NULL
Observao: Tambm possvel usar o operador NOT com outros operadores SQL, como
BETWEEN, LIKE e NULL.
...
...
...
...
WHERE
WHERE
WHERE
WHERE
job_id
NOT IN ('AC_ACCOUNT', 'AD_VP')
salary
NOT BETWEEN 10000 AND 15000
last_name NOT LIKE '%A%'
commission_pct IS
NOT NULL
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-17
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Regras de Precedncia
Operadores aritmticos
Operador de concatenao
Condies de comparao
[NOT] BETWEEN
Diferente de
Condio lgica OR
Regras de Precedncia
As regras de precedncia determinam a ordem de avaliao e clculo das expresses. A
tabela relaciona a ordem de precedncia default. Voc pode sobrepor a ordem default
usando parnteses para delimitar as expresses a serem calculadas primeiro.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-18
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Operador Significado
Regras de Precedncia
last_name, job_id, salary
employees
job_id = 'SA_REP'
job_id = 'AD_PRES'
salary > 15000;
SELECT
FROM
WHERE
OR
AND
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-19
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
FROM
WHERE
OR
AND
Na sintaxe:
ORDER BY
ASC
DESC
expr
table
condition(s)]
{column, expr, numeric_position} [ASC|DESC]];
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-20
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Classificao
SELECT
last_name, job_id, department_id, hire_date
FROM employees
1
ORDER BY hire_date DESC;
Variveis de Substituio
Desejo
consultar
valores
diferentes.
Variveis de Substituio
At o momento, foram apresentados exemplos codificados. Em uma aplicao concluda, o
usurio acionaria o relatrio, que seria executado sem outros prompts. A faixa de dados
seria predeterminada pela clusula WHERE fixa no arquivo de script do iSQL*Plus.
Com o iSQL*Plus, possvel criar relatrios que solicitam aos usurios seus prprios
valores para restringir a faixa de dados retornados com variveis de substituio. possvel
incorporar variveis de substituio a um arquivo de comandos ou a uma nica instruo
SQL. Uma varivel pode ser considerada como um container no qual os valores so
armazenados temporariamente. Quando a instruo executada, o valor substitudo.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-22
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
... salary = ?
department_id = ?
... last_name = ? ...
Variveis de Substituio
Condies WHERE
Clusulas ORDER BY
Expresses de coluna
Nomes de tabelas
Instrues SELECT inteiras
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-23
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Descrio
&user_variable
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-24
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
1
2
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-25
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
101
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-26
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
salary
last_name
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-27
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-28
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
employee_id, last_name, job_id, &&column_name
FROM
employees
ORDER BY &column_name ;
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-29
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SET VERIFY ON
SELECT employee_id, last_name, salary, department_id
FROM
employees
WHERE employee_id = &employee_num;
old
new
3: WHERE
3: WHERE
employee_id = &employee_num
employee_id = 200
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-30
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Sumrio
Nesta lio, voc aprendeu a:
Usar a clusula WHERE para restringir as linhas
da sada:
Sumrio
Nesta lio, voc aprendeu a restringir e classificar as linhas retornadas pela instruo
SELECT. Voc tambm aprendeu a implementar diversos operadores e condies.
Com as variveis de substituio do iSQL*Plus, possvel obter mais flexibilidade nas
instrues SQL. Voc pode consultar usurios durante o runtime e permitir que
especifiquem critrios.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-31
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-32
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 2
O departamento de recursos humanos precisa da sua ajuda para criar algumas consultas.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-33
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 2 (continuao)
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-34
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 2 (continuao)
7. O departamento de recursos humanos precisa de um relatrio que exiba o sobrenome
e a data de admisso de todos os funcionrios admitidos em 1994.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-35
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 2 (continuao)
11. O departamento de recursos humanos deseja executar relatrios baseados em um
gerente. Crie uma consulta que solicite um ID de gerente ao usurio e gere o ID de
funcionrio, o sobrenome, o salrio e o departamento dos funcionrios desse
gerente. O departamento de recursos humanos deseja ter permisso para classificar o
relatrio em uma coluna selecionada. Voc pode testar os dados com os seguintes
valores:
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-36
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 2 (continuao)
Se tiver tempo, faa os seguintes exerccios:
12. Exiba todos os sobrenomes dos funcionrios cuja terceira letra do nome seja a.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 2-37
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Objetivos
Objetivos
As functions tornam o bloco bsico da consulta mais eficiente e so usadas para manipular
valores de dados. Esta a primeira das duas lies que descrevem o uso de functions. Ela
concentra-se em functions de caractere, nmero e data de uma nica linha, bem como em
functions que convertem os dados de um tipo em outro (por exemplo, dados de caractere em
dados numricos).
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-2
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Functions SQL
Entrada
Sada
Function
arg 2
Valor
resultante
arg n
Functions SQL
As functions constituem um recurso eficiente de SQL. possvel us-las com os seguintes
objetivos:
Executar clculos em dados
Modificar itens individuais de dados
Manipular a sada de grupos de linhas
Formatar datas e nmeros para exibio
Converter tipos de dados de colunas
As functions SQL s vezes aceitam argumentos e sempre retornam um valor.
Observao: A maioria das functions descritas nesta lio so especficas da verso de
SQL do Oracle.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-3
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
A function
executa a ao
arg 1
Functions de
uma nica linha
Functions de
vrias linhas
Retornam um resultado
por linha
Retornam um resultado
por conjunto de linhas
Functions
o nome da function
um argumento a ser usado pela function. Pode ser
representado por um nome de coluna ou uma expresso.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-5
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Functions de
uma nica linha
Converso
Nmero
Data
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-6
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Geral
Functions de Caractere
Functions de manipulao
de maisculas e minsculas
Functions de
manipulao de caracteres
LOWER
UPPER
INITCAP
CONCAT
SUBSTR
LENGTH
INSTR
LPAD | RPAD
TRIM
REPLACE
Functions de Caractere
As functions de caractere de uma nica linha aceitam dados de caractere como entrada e
podem retornar valores numricos ou de caractere. possvel dividir as functions de
caractere em:
Functions de manipulao de maisculas e minsculas
Functions de manipulao de caracteres
Function
Objetivo
LOWER(column|expression)
UPPER(column|expression)
INITCAP(column|expression)
CONCAT(column1|expression1,
column2|expression2)
SUBSTR(column|expression,m[
,n])
Functions de
caractere
Objetivo
LENGTH(column|expression)
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-8
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
INSTR(column|expression,
string, [,m], [n] )
Functions de Manipulao
de Maisculas e Minsculas
Function
Resultado
LOWER('SQL Course')
sql course
UPPER('SQL Course')
SQL COURSE
INITCAP('SQL Course')
Sql Course
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-9
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
O nome na sada aparece como foi armazenado no banco de dados. Para exibir o nome
apenas com a primeira letra maiscula, use a function UPPER na instruo SELECT.
SELECT employee_id, UPPER(last_name), department_id
FROM employees
WHERE INITCAP(last_name) = 'Higgins';
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-10
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Function
Resultado
CONCAT('Hello', 'World')
HelloWorld
SUBSTR('HelloWorld',1,5)
Hello
LENGTH('HelloWorld')
10
INSTR('HelloWorld', 'W')
LPAD(salary,10,'*')
*****24000
24000*****
REPLACE
('JACK and JUE','J','BL')
elloWorld
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-11
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Usando as Functions de
Manipulao de Caracteres
1
2
3
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-12
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Functions de Nmero
ROUND: Arredonda o valor at o decimal especificado
TRUNC: Trunca o valor at o decimal especificado
MOD: Retorna o resto da diviso
Function
Resultado
ROUND(45.926, 2)
45.93
TRUNC(45.926, 2)
45.92
MOD(1600, 300)
100
Functions de Nmero
As functions de nmero aceitam a entrada numrica e retornam valores numricos. Esta
seo descreve algumas functions de nmero.
Function
Objetivo
ROUND(column|expression, n)
TRUNC(column|expression, n)
MOD(m,n)
Observao: Esta lista contm somente algumas das functions de nmero disponveis.
Para obter mais informaes, consulte "Number Functions" no manual Oracle SQL
Reference.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-13
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Function ROUND
A function ROUND arredonda a coluna, a expresso ou o valor at n casas decimais. Se o
segundo argumento for 0 ou no estiver presente, o valor ser arredondado at zero casas
decimais. Se o segundo argumento for 2, o valor ser arredondado at duas casas decimais.
Por outro lado, se o segundo argumento for -2, o valor ser arredondado at duas casas
decimais esquerda (arredondado para a unidade mais prxima de 10).
Tambm possvel usar a function ROUND com functions de data. So fornecidos exemplos
posteriormente nesta lio.
Tabela DUAL
A tabela DUAL pertence ao usurio SYS e pode ser acessada por todos os usurios. Ela
contm uma coluna, DUMMY, e uma linha com o valor X. A tabela DUAL til quando voc
deseja retornar um valor apenas uma vez (por exemplo, o valor de uma constante, de uma
pseudocoluna ou de uma expresso no derivado de uma tabela com dados do usurio). A
tabela DUAL usada geralmente para completar a sintaxe da clusula SELECT, pois as
clusulas SELECT e FROM so obrigatrias e diversos clculos no precisam de selees
das tabelas reais.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-14
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Function TRUNC
A function TRUNC trunca a coluna, a expresso ou o valor at n casas decimais.
Essa function opera com argumentos semelhantes aos da function ROUND. Se o segundo
argumento for 0 ou no estiver presente, o valor ser truncado at zero casas decimais. Se o
segundo argumento for 2, o valor ser truncado at duas casas decimais. Por outro lado, se o
segundo argumento for -2, o valor ser truncado at duas casas decimais esquerda. Se o
segundo argumento for -1, o valor ser truncado at uma casa decimal esquerda.
Assim como a function ROUND, possvel usar a function TRUNC com functions de data.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-15
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Function MOD
A function MOD localiza o resto do primeiro argumento dividido pelo segundo argumento. O
exemplo do slide calcula o resto do salrio aps a diviso por 5.000 para todos os
funcionrios cujo ID de cargo SA_REP.
Observao: A function MOD usada com freqncia para determinar se o valor par ou
mpar.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-16
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-17
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
YEAR
MONTH
DAY
HOUR
MINUTE
19
43
87
06
17
17
10
O tipo de dados DATE sempre armazena internamente as informaes sobre o ano como um
nmero de quatro dgitos: dois dgitos para o sculo e dois para o ano. Por exemplo, o banco
de dados Oracle armazena o ano como 1987 ou 2004, e no apenas como 87 ou 04.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-18
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Quando um registro com uma coluna de data inserido em uma tabela, as informaes
sobre o sculo so obtidas da function SYSDATE. No entanto, quando a coluna de data
exibida na tela, o componente de sculo no mostrado (por default).
Function SYSDATE
SYSDATE uma function de data que retorna a data e o horrio atuais do servidor de banco
de dados. Voc pode usar SYSDATE como qualquer outro nome de coluna. Por exemplo,
para exibir a data atual, selecione SYSDATE em uma tabela. comum selecionar
SYSDATE em uma tabela fictcia denominada DUAL.
Exemplo
Exiba a data atual usando a tabela DUAL.
SELECT SYSDATE
FROM
DUAL;
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-19
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Resultado
Descrio
data + nmero
data nmero
Data
Data
data data
data + nmero/24
Nmero de dias
Data
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-20
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-21
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Functions de Data
Function
MONTHS_BETWEEN
Resultado
ADD_MONTHS
NEXT_DAY
LAST_DAY
ROUND
Arredonda a data
TRUNC
Trunca a data
Functions de Data
As functions de data operam em datas Oracle. Todas as functions de data retornam um valor
do tipo de dados DATE, com exceo de MONTHS_BETWEEN, que retorna um valor
numrico.
MONTHS_BETWEEN(date1, date2): Obtm o nmero de meses entre date1 e
date2. O resultado pode ser positivo ou negativo. Se date1 for posterior a date2,
o resultado ser positivo; caso contrrio, o resultado ser negativo. A parte decimal do
resultado representa uma parte do ms.
ADD_MONTHS(date, n): Adiciona n meses do calendrio data. O valor n deve
ser inteiro e pode ser negativo.
NEXT_DAY(date, 'char'): Obtm a data do prximo dia especificado da
semana ('char') aps a data em questo. O valor de char pode ser um nmero
que represente um dia ou uma string de caracteres.
LAST_DAY(date): Obtm a data do ltimo dia do ms que contm a data em
questo.
ROUND(date[,'fmt']): Retorna a data arredondada at a unidade especificada
pelo modelo de formato fmt. Se o modelo de formato fmt for omitido, a data ser
arredondada at o dia mais prximo.
TRUNC(date[, 'fmt']): Retorna a data com a parte do horrio do dia truncada
at a unidade especificada pelo modelo de formato fmt. Se o modelo de formato fmt
for omitido, a data ser truncada at o dia mais prximo.
A lista um subconjunto de functions de data disponveis. Os modelos de formato so
abordados posteriormente nesta lio. Os exemplos de modelos de formato so month e
year.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-22
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
ltimo dia do ms
Function
Resultado
MONTHS_BETWEEN
('01-SEP-95','11-JAN-94')
19.6774194
ADD_MONTHS ('11-JAN-94',6)
'11-JUL-94'
NEXT_DAY
('01-SEP-95','FRIDAY')
'08-SEP-95'
LAST_DAY
('01-FEB-95')
'28-FEB-95'
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-23
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Function
ROUND(SYSDATE,'MONTH')
Resultado
01-AUG-03
ROUND(SYSDATE ,'YEAR')
01-JAN-04
TRUNC(SYSDATE ,'MONTH')
TRUNC(SYSDATE ,'YEAR')
01-JUL-03
01-JAN-03
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-24
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-25
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Functions de Converso
Converso de
tipos de dados
Converso explcita
de tipos de dados
Functions de Converso
Alm dos tipos de dados do Oracle, possvel definir as colunas das tabelas de um banco de
dados Oracle usando os tipos de dados ANSI, DB2 e SQL/DS. No entanto, o servidor
Oracle converte internamente esses tipos de dados nos tipos de dados do Oracle.
Em alguns casos, ele usa dados de um tipo diferente do esperado. Quando isso acontece, o
servidor Oracle pode convert-los automaticamente no tipo de dados esperado. Essa
converso de tipo de dados pode ser efetuada implicitamente pelo servidor Oracle ou
explicitamente pelo usurio.
As converses implcitas de tipos de dados funcionam de acordo com as regras explicadas
nos prximos dois slides.
As converses explcitas de tipos de dados so feitas por meio das functions de converso.
As functions de converso convertem um valor de um tipo de dados em outro. Em geral, a
forma dos nomes das functions segue a conveno tipo de dados TO tipo de
dados. O primeiro tipo de dados o da entrada, e o segundo, o da sada.
Observao: Embora a converso implcita de tipos de dados esteja disponvel,
recomendvel usar a converso explcita para garantir a confiabilidade das instrues SQL.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-26
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Converso implcita
de tipos de dados
De
VARCHAR2 ou CHAR
Em
NUMBER
VARCHAR2 ou CHAR
DATE
NUMBER
VARCHAR2
DATE
VARCHAR2
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-27
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
De
VARCHAR2 ou CHAR
Em
NUMBER
VARCHAR2 ou CHAR
DATE
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-28
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
NUMBER
TO_DATE
CHARACTER
TO_CHAR
DATE
TO_CHAR
Objetivo
TO_NUMBER
CHARACTER
NUMBER
TO_CHAR
DATE
TO_CHAR
Objetivo
TO_CHAR(number|date,[
fmt], [nlsparams])
TO_NUMBER(char,[fmt],
[nlsparams])
TO_DATE(char,[fmt],[nls
params])
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-30
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
TO_NUMBER
Para obter mais informaes, consulte "Conversion Functions" no manual Oracle SQL
Reference.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-31
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
O modelo de formato:
Deve ser delimitado por aspas simples
Faz distino entre maisculas e minsculas
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-32
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Resultado
YEAR
MM
MONTH
MON
DY
DAY
DD
Dia numrico do ms
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-33
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Nome completo do ms
Descrio
SCC ou CC
YYY ou YY ou Y
Y.YYY
SYEAR ou YEAR
BC ou AD
B.C. ou A.D.
Trimestre do ano
MM
MONTH
MON
RM
Ms em numeral romano
WW ou W
Semana do ano ou ms
DDD ou DD ou D
DAY
DY
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-34
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Anos em datas YYYY ou Ano; o servidor prefixa a data A.C. com SYYYY
15:45:32 PM
12 of OCTOBER
fourteenth
Descrio
AM or PM
Indicador de meridiano
A.M. or P.M.
HH or HH12 or HH24
MI
Minuto (059)
SS
Segundo (059)
SSSSS
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-35
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Outros Formatos
Elemento
Descrio
/ . ,
Elemento
Descrio
TH
SP
SPTH or THSP
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-36
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
of the
String entre aspas reproduzida no resultado.
Especificando Sufixos para Influenciar a Exibio de Nmeros
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-37
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT last_name,
TO_CHAR(hire_date, 'fmDD Month YYYY')
AS HIREDATE
FROM
employees;
Elemento
9
Resultado
Representa um nmero
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-38
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Elemento
Descrio
Exemplo
Resultado
999999
1234
099999
001234
$999999
$1234
L999999
FF1234
99,99
99D99
999999,99
1234,00
9.999
Retorna o separador de grupos na posio
especificada. Voc pode especificar vrios
separadores de grupos em um modelo de formato
numrico.
9G999
999.999
1.234
MI
999999MI
1234-
PR
999999PR
<1234>
EEEE
99,999EEEE
1,234E+03
U9999
1234
9999V99
123400
S9999
-1234 ou
+1234
B9999,99
1234,00
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-39
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Diretrizes
O servidor Oracle exibe uma string de smbolos de nmero (#) no lugar de um nmero
inteiro cujos dgitos ultrapassam o nmero de dgitos fornecido no modelo de formato.
O servidor Oracle arredonda o valor decimal armazenado at o nmero de casas
decimais do modelo de formato.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-40
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
possvel converter uma string de caracteres em um nmero ou uma data. Para realizar essa
tarefa, use a function TO_NUMBER ou TO_DATE. O modelo de formato escolhido baseia-se
nos elementos de formato demonstrados anteriormente.
O modificador fx especifica a correspondncia exata para o argumento de caractere e o
modelo de formato de data de uma function TO_DATE:
A pontuao e o texto no argumento de caractere devem corresponder exatamente
(exceto em relao a maisculas e minsculas) s partes associadas do modelo de
formato.
O argumento de caractere no pode conter espaos em branco adicionais. Sem fx, o
Oracle ignora os espaos em branco adicionais.
Os dados numricos no argumento de caractere devem ter o mesmo nmero de dgitos
do elemento correspondente no modelo de formato. Sem fx, os nmeros no argumento
de caractere podem omitir os zeros esquerda.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-41
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
TO_NUMBER(char[, 'format_model'])
Exemplo
Exiba o nome e a data de admisso de todos os funcionrios admitidos em 24 de maio de
1999. Como o modificador fx usado, uma correspondncia exata necessria e os
espaos aps a palavra May no so reconhecidos:
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-42
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Formato de Data RR
Ano Atual
1995
1995
2001
2001
Data Especificada
27.10.95
27.10.17
27.10.17
27.10.95
Formato RR
1995
2017
2017
1995
Formato YY
1995
1917
2017
2095
Se os dois
A data retornada
dgitos do
estar contida no
049 sculo atual
ano atual
forem:
A data retornada
estar contida no
5099 sculo imediatamente
posterior ao atual
5099
A data retornada
estar contida no
sculo imediatamente
anterior ao atual
A data retornada
estar contida no
sculo atual
O formato de data RR semelhante ao elemento YY, mas pode ser usado para especificar
sculos diferentes. Use o elemento de formato de data RR, em vez de YY, para que o
sculo do valor retornado varie de acordo com o ano de dois dgitos especificado e com
os ltimos dois dgitos do ano atual. A tabela do slide resume o comportamento do
elemento RR.
Ano Atual
Data Especificada
Interpretao (RR)
Interpretao (YY)
1994
27-OUT-95
1995
1995
1994
27-OUT-17
2017
1917
2001
27-OUT-17
2017
2017
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-43
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
049
Para localizar os funcionrios admitidos antes de 1990, voc poder usar o formato RR.
Como o ano atual maior que 1999, o formato RR interpretar a parte da data relativa ao
ano de 1950 a 1999.
O comando a seguir, por outro lado, no resultar na seleo de linhas porque o formato YY
interpretar a parte da data relativa ao ano de acordo com o sculo atual (2090).
SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-yyyy')
FROM employees
WHERE TO_DATE(hire_date, 'DD-Mon-yy') < '01-Jan-1990';
no rows selected
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-44
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Aninhando Functions
Etapa 1 = Resultado 1
Etapa 2 = Resultado 2
Etapa 3 = Resultado 3
Aninhando Functions
possvel aninhar as functions de uma nica linha em quantos nveis forem necessrios. As
functions aninhadas so avaliadas do nvel mais interno para o nvel mais externo. Veja a
seguir alguns exemplos que mostram a flexibilidade dessas functions.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-45
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
F3(F2(F1(col,arg1),arg2),arg3)
Aninhando Functions
TO_CHAR(NEXT_DAY(ADD_MONTHS
(hire_date, 6), 'FRIDAY'),
'fmDay, Month DDth, YYYY')
"Next 6 Month Review"
FROM employees
ORDER BY hire_date;
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-46
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT last_name,
UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8), '_US'))
FROM
employees
WHERE department_id = 60;
Functions Gerais
As functions a seguir agem com qualquer tipo de
dados e esto relacionadas ao uso de valores nulos:
NVL (expr1, expr2)
NVL2 (expr1, expr2, expr3)
NULLIF (expr1, expr2)
COALESCE (expr1, expr2, ..., exprn)
Functions Gerais
Essas functions agem com qualquer tipo de dados e esto relacionadas ao uso de valores
nulos na lista de expresses.
Function
Descrio
NVL
NVL2
NULLIF
COALESCE
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-47
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Function NVL
NVL(commission_pct,0)
NVL(hire_date,'01-JAN-97')
NVL(job_id,'No Job Yet')
Function NVL
Na sintaxe:
expr1 o valor de origem ou a expresso que poder conter um valor nulo
expr2 o valor de destino para a converso do valor nulo
Voc pode usar a function NVL para converter qualquer tipo de dados, mas o valor
retornado sempre igual ao do tipo de dados de expr1.
Converses NVL de Vrios Tipos de Dados
Tipo de Dados
Exemplo de Converso
NUMBER
NVL(number_column,9)
DATE
NVL(date_column, '01-JAN-95')
CHAR or VARCHAR2
NVL(character_column, 'Unavailable')
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-48
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Observe que a remunerao anual calculada apenas para os funcionrios que recebem
comisso. Se o valor de uma coluna da expresso for nulo, o resultado ser nulo. Para
calcular valores relativos a todos os funcionrios, converta o valor nulo em um nmero
antes de aplicar o operador aritmtico. No exemplo do slide, a function NVL usada para
converter valores nulos em zero.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-49
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
1
SELECT last_name, salary, NVL(commission_pct, 0),
(salary*12) + (salary*12*NVL(commission_pct, 0)) AN_SAL
FROM employees;
Na sintaxe:
expr1 o valor de origem ou a expresso que poder conter um valor nulo
expr2 o valor retornado quando expr1 no nulo
expr3 o valor retornado quando expr2 nulo
No exemplo mostrado no slide, a coluna COMMISSION_PCT examinada. Se for
detectado um valor, a segunda expresso SAL+COMM ser retornada. Se a coluna
COMMISSION_PCT contiver um valor nulo, a terceira expresso SAL ser retornada.
possvel expressar o argumento expr1 em qualquer tipo de dados. Os argumentos
expr2 e expr3 podem ser expressos em qualquer tipo de dados, exceto LONG. Se os tipos
de dados de expr2 e expr3 forem diferentes, o servidor Oracle converter expr3 no
tipo de dados de expr2 antes de compar-los, a menos que expr3 seja uma constante
nula. No ltimo caso, no ser necessria uma converso de tipo de dados. O tipo de dados
do valor retornado ser sempre igual ao tipo de dados de expr2, a menos que expr2 seja
expresso em dados de caractere; nesse caso, o tipo de dados do valor retornado ser
VARCHAR2.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-50
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
A function NULLIF compara duas expresses. Se elas forem iguais, a function retornar um
valor nulo. Se elas forem diferentes, a function retornar a primeira expresso. No
possvel especificar o literal NULL para a primeira expresso.
Sintaxe
NULLIF (expr1, expr2)
Na sintaxe:
expr1 o valor de origem comparado a expr2
expr2 o valor de origem comparado a expr1 (Se ele no for igual a expr1,
expr1 ser retornado.)
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-51
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Na sintaxe:
expr1 retornar essa expresso se ela no for nula
expr2 retornar essa expresso se ela no for nula e a primeira expresso for nula
exprn retornar essa expresso se as expresses anteriores forem nulas
Todas as expresses devem ter o mesmo tipo de dados.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-52
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
No exemplo mostrado no slide, se o valor de MANAGER_ID no for nulo, ele ser exibido.
Se o valor de MANAGER_ID for nulo, COMMISSION_PCT ser exibido. Se os valores de
MANAGER_ID e COMMISSION_PCT forem nulos, ser exibido o valor 1.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-53
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT last_name,
COALESCE(manager_id,commission_pct, -1) comm
FROM
employees
ORDER BY commission_pct;
Expresses Condicionais
Expresses Condicionais
Os dois mtodos usados para implementar o processamento condicional (a lgica IF-THENELSE) em uma instruo SQL so a expresso CASE e a function DECODE.
Observao: A expresso CASE est de acordo com o padro ANSI SQL. A function
DECODE especfica da sintaxe do Oracle.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-54
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Expresso CASE
Function DECODE
Expresso CASE
Expresso CASE
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-55
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-56
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Function DECODE
Function DECODE
A function DECODE decodifica uma expresso de maneira semelhante lgica IF-THENELSE usada em vrias linguagens. Essa function decodifica a expresso depois de
compar-la a cada valor da pesquisa. Se a expresso for igual da pesquisa, o
resultado ser retornado.
Se o valor default for omitido, um valor nulo ser retornado quando um valor da pesquisa
no corresponder a nenhum dos valores do resultado.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-57
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
'IT_PROG'
'ST_CLERK'
'SA_REP'
= salary
THEN
THEN
THEN
salary = salary*1.10
salary = salary*1.15
salary = salary*1.20
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-58
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Este slide mostra outro exemplo com a function DECODE. Nesse exemplo, determinamos a
alquota de imposto de cada funcionrio do departamento 80 com base no salrio mensal.
As alquotas de imposto so as seguintes:
Faixa de Salrio Mensal
Alquota de Imposto
00%
09%
20%
30%
40%
42%
44%
US$14.000,00 ou mais
45%
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-59
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Sumrio
Nesta lio, voc aprendeu a:
Sumrio
possvel aninhar as functions de uma nica linha em quantos nveis forem necessrios. As
functions de uma nica linha podem manipular:
Dados de caractere: LOWER, UPPER, INITCAP, CONCAT, SUBSTR, INSTR,
LENGTH
Dados de nmero: ROUND, TRUNC, MOD
Dados de data: MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY,
ROUND, TRUNC
Lembre-se do seguinte:
Os valores de data tambm podem usar operadores aritmticos.
As functions de converso podem converter valores numricos, de caractere e data:
TO_CHAR, TO_DATE, TO_NUMBER
Vrias functions esto relacionadas ao uso de valores nulos, incluindo NVL, NVL2,
NULLIF e COALESCE.
possvel aplicar a lgica IF-THEN-ELSE em uma instruo SQL com a expresso
CASE ou a function DECODE.
SYSDATE e DUAL
SYSDATE uma function de data que retorna a data e o horrio atuais. comum selecionar
SYSDATE em uma tabela fictcia denominada DUAL.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-60
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
A Parte 2 do exerccio desta lio contm vrias atividades que utilizam diferentes functions
disponveis para os tipos de dados de caractere, nmero e data. Faa as questes de 7 a 14
relativas a essa parte.
Lembre-se de que, nas functions aninhadas, os resultados so avaliados da function mais
interna para a mais externa.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-61
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 3
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-62
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Parte 1
1. Crie uma consulta para exibir a data atual. Atribua o label Date coluna.
Exerccio 3 (continuao)
Recrie a consulta para que o usurio seja solicitado a informar a letra inicial do
sobrenome. Por exemplo, se o usurio informar H quando uma letra for solicitada, a
sada dever mostrar todos os funcionrios cujos sobrenomes comeam com a letra
H.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-63
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
5. Crie uma consulta que exiba o sobrenome (com a primeira letra maiscula e todas as
outras minsculas) e o tamanho do sobrenome de todos os funcionrios cujos nomes
comecem com a letra J, A ou M. Atribua um label apropriado a cada coluna.
Classifique os resultados pelos sobrenomes dos funcionrios.
Exerccio 3 (continuao)
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-64
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 3 (continuao)
Parte 2
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-65
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 3 (continuao)
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-66
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 3 (continuao)
12. Crie uma consulta que exiba os oito primeiros caracteres dos sobrenomes dos
funcionrios e indique os valores dos salrios com asteriscos. Cada asterisco
representa mil dlares. Classifique os dados em ordem decrescente de salrio.
Atribua o label EMPLOYEES_AND_THEIR_SALARIES coluna.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 3-67
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
11. Crie uma consulta que exiba os sobrenomes e as comisses dos funcionrios. Se um
funcionrio no ganhar comisso, a informao "No Commission" dever ser
exibida. Atribua o label COMM coluna.
Exerccio 3 (continuao)
13. Com a function DECODE, crie uma consulta que exiba o nvel de todos os
funcionrios com base no valor da coluna JOB_ID. Use estes dados:
Cargo
Nvel
AD_PRES
A
ST_MAN
B
IT_PROG
C
SA_REP
D
ST_CLERK
E
Nenhuma das opes anteriores 0
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Objetivos
Ao concluir esta lio, voc ser capaz de:
Identificar as functions de grupo disponveis
Descrever o uso de functions de grupo
Agrupar dados com a clusula GROUP BY
Incluir ou excluir linhas agrupadas com a clusula
HAVING
Objetivos
Esta lio aborda o uso de functions com mais detalhes. Ela concentra-se na obteno de
informaes sumariadas (como mdias) relativas a grupos de linhas. A lio mostra como
agrupar as linhas de uma tabela em conjuntos menores e como especificar critrios de
pesquisa para grupos de linhas.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-2
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Salrio mximo na
tabela EMPLOYEES
Functions de Grupo
Diferentemente das functions de uma nica linha, as functions de grupo operam em
conjuntos de linhas para fornecer um resultado por grupo. Esses conjuntos podem abranger
a tabela inteira ou a tabela dividida em grupos.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-3
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
EMPLOYEES
Functions
de Grupo
MIN
STDDEV
SUM
VARIANCE
Descrio
COUNT({*|[DISTINCT|ALL]expr
})
MAX([DISTINCT|ALL]expr)
MIN([DISTINCT|ALL]expr)
STDDEV([DISTINCT|ALL]x)
SUM([DISTINCT|ALL]n)
VARIANCE([DISTINCT|ALL]x)
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-4
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-5
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
FROM
[WHERE
[GROUP BY
[ORDER BY
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-6
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Observao: S possvel usar as functions AVG, SUM, VARIANCE e STDDEV com tipos
de dados numricos. MAX e MIN no podem ser usadas com o tipo de dados LOB ou LONG.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-7
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT COUNT(commission_pct)
FROM
employees
WHERE department_id = 80;
Function COUNT
A function COUNT tem trs formatos:
COUNT(*)
COUNT(expr)
COUNT(DISTINCT expr)
COUNT(*) retorna o nmero de linhas de uma tabela que atendem aos critrios da
instruo SELECT, incluindo as linhas duplicadas e as linhas com valores nulos de qualquer
uma das colunas. Se uma clusula WHERE estiver includa na instruo SELECT,
COUNT(*) retornar o nmero de linhas que atendem condio especificada nessa
clusula.
Por outro lado, COUNT(expr) retorna o nmero de valores no nulos na coluna
identificada por expr.
COUNT(DISTINCT expr) retorna o nmero de valores exclusivos e no nulos na coluna
identificada por expr.
Exemplos
1. O exemplo do slide mostra o nmero de funcionrios do departamento 50.
2. O exemplo do slide mostra o nmero de funcionrios do departamento 80 que podem
receber comisso.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-8
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT COUNT(*)
FROM
employees
WHERE department_id = 50;
Palavra-chave DISTINCT
Use a palavra-chave DISTINCT para suprimir a contagem de valores duplicados em uma
coluna.
O exemplo do slide mostra os valores de nmeros de departamentos distintos da tabela
EMPLOYEES.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-9
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
FROM
employees;
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-10
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
3500
6400
Salrio mdio
na tabela
EMPLOYEES
para cada
departamento
10033
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-11
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
9500
Clusula GROUP BY
Voc pode usar a clusula GROUP BY para dividir as linhas de uma tabela em grupos.
Depois, pode usar as functions de grupo para retornar informaes sumariadas de cada
grupo.
Na sintaxe:
group_by_expression
Diretrizes
Se incluir uma function de grupo em uma clusula SELECT, voc no poder
selecionar resultados individuais, a menos que a coluna individual aparea na clusula
GROUP BY. Se no conseguir incluir a lista de colunas na clusula GROUP BY, voc
receber uma mensagem de erro.
Com uma clusula WHERE, voc poder excluir linhas antes de dividi-las em grupos.
Inclua as colunas na clusula GROUP BY.
No possvel usar um apelido de coluna na clusula GROUP BY.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-12
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
column, group_function(column)
FROM
table
[WHERE
condition]
[GROUP BY group_by_expression]
[ORDER BY column];
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-13
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
department_id, AVG(salary)
FROM
employees
GROUP BY department_id ;
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-14
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
AVG(salary)
FROM
employees
GROUP BY department_id ;
Adicione os
salrios tabela
EMPLOYEES
para cada cargo,
agrupados por
departamento
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-15
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
EMPLOYEES
SELECT
department_id dept_id, job_id, SUM(salary)
FROM
employees
GROUP BY department_id, job_id ;
Consultas Invlidas
Usando Functions de Grupo
Qualquer coluna ou expresso da lista SELECT que no
seja uma function agregada dever estar na clusula
GROUP BY:
Qualquer coluna ou expresso da lista SELECT que no seja uma function agregada dever
estar na clusula GROUP BY.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-17
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Consultas Invlidas
Usando Functions de Grupo
SELECT
FROM
WHERE
GROUP BY
department_id, AVG(salary)
employees
AVG(salary) > 8000
department_id;
WHERE
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-18
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
O salrio
mximo por
departamento
quando for
maior que
US$ 10.000
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-19
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
EMPLOYEES
column, group_function
table
condition]
group_by_expression]
group_condition]
column];
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-20
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
1. As linhas so agrupadas.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-21
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
FROM
GROUP BY
HAVING
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-22
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
job_id, SUM(salary) PAYROLL
FROM employees
WHERE
job_id NOT LIKE '%REP%'
GROUP BY job_id
HAVING
SUM(salary) > 13000
ORDER BY SUM(salary);
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-23
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
MAX(AVG(salary))
FROM
employees
GROUP BY department_id;
Sumrio
Nesta lio, voc aprendeu a:
Usar as functions de grupo COUNT, MAX, MIN e AVG
Criar consultas que utilizam a clusula GROUP BY
Criar consultas que utilizam a clusula HAVING
SELECT
FROM
[WHERE
[GROUP BY
[HAVING
[ORDER BY
column, group_function
table
condition]
group_by_expression]
group_condition]
column];
Sumrio
Vrias functions de grupo esto disponveis em SQL, como estas:
AVG, COUNT, MAX, MIN, SUM, STDDEV e VARIANCE
Para criar subgrupos, use a clusula GROUP BY. possvel restringir grupos com a
clusula HAVING.
Especifique as clusulas HAVING e GROUP BY aps a clusula WHERE em uma instruo.
A ordem na qual voc especifica essas clusulas aps a clusula WHERE no importante.
Informe a clusula ORDER BY por ltimo.
O servidor Oracle avalia as clusulas na seguinte ordem:
1. Se a instruo contiver uma clusula WHERE, o servidor estabelecer as linhas
candidatas.
2. O servidor identifica os grupos especificados na clusula GROUP BY.
3. A clusula HAVING restringe os grupos de resultados que no atendem aos critrios de
grupo especificados na clusula HAVING.
Observao: Para obter uma lista completa das functions de grupo, consulte o manual
Oracle SQL Reference.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-24
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-25
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 4
Determine a validade das trs instrues a seguir. Circule Verdadeiro ou Falso.
1. As functions de grupo trabalham com vrias linhas para produzir um resultado por
grupo.
Verdadeiro/Falso
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-26
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 4 (continuao)
8. Descubra a diferena entre o salrio mais alto e o mais baixo. Atribua o label
DIFFERENCE coluna.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-27
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
6. Crie uma consulta para exibir o nmero de pessoas com o mesmo cargo.
Exerccio 4 (continuao)
Se quiser tomar parte em mais um desafio, faa estes exerccios:
11. Crie uma consulta matriz que exiba o cargo, o salrio relativo a esse cargo com base
no nmero do departamento e o salrio total desse cargo para os departamentos 20,
50, 80 e 90, atribuindo um cabealho apropriado a cada coluna.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 4-28
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
10. Crie uma consulta que exiba o nmero total de funcionrios e, desse total, mostre o
nmero de funcionrios admitidos em 1995, 1996, 1997 e 1998. Crie cabealhos de
colunas apropriados.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exibindo Dados
de Vrias Tabelas
Objetivos
Objetivos
Esta lio explica como obter dados de mais de uma tabela. Uma join usada para exibir
informaes de vrias tabelas. Portanto, voc pode juntar tabelas para exibir informaes de
mais de uma tabela.
Observao: Para obter informaes sobre joins, consulte "SQL Queries and Subqueries:
Joins" no manual Oracle SQL Reference.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-2
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
DEPARTMENTS
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-3
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Tipos de Join
Estas so as joins compatveis com o padro
SQL:1999:
Joins cruzadas
Joins naturais
Clusula USING
Joins externas integrais (ou de dois lados)
Condies arbitrrias de join para joins externas
Tipos de Join
Para juntar tabelas, voc pode usar a sintaxe de join compatvel com o padro SQL:1999.
Observao: Antes da release Oracle9i, a sintaxe de join era diferente dos padres ANSI. A
sintaxe de join compatvel com o SQL:1999 no oferece benefcios de desempenho em
relao sintaxe de join de propriedade Oracle existente nas releases anteriores. Para obter
informaes detalhadas sobre a sintaxe de join proprietria, consulte o Apndice C.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-4
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
table1.column, table2.column
FROM
table1
[NATURAL JOIN table2] |
[JOIN table2 USING (column_name)] |
[JOIN table2
ON (table1.column_name = table2.column_name)]|
[LEFT|RIGHT|FULL OUTER JOIN table2
ON (table1.column_name = table2.column_name)]|
[CROSS JOIN table2];
Definindo Joins
Na sintaxe:
table1.column indica a tabela e a coluna das quais os dados so recuperados
NATURAL JOIN junta duas tabelas com base no mesmo nome de coluna
JOIN table USING column_name executa uma operao de equijoin com base no
nome da coluna
JOIN table ON table1.column_name executa uma operao de equijoin com
base na condio da clusula ON, = table2.column_name
LEFT/RIGHT/FULL OUTER executa joins externas
CROSS JOIN retorna um produto cartesiano das duas tabelas
Para obter mais informaes, consulte "SELECT" no manual Oracle SQL Reference.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-5
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-6
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
department_id, department_name,
location_id, city
FROM
departments
NATURAL JOIN locations
WHERE
department_id IN (20, 50);
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-7
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Clusula USING
As joins naturais usam todas as colunas com nomes e tipos de dados correspondentes para
unir as tabelas. possvel usar a clusula USING para especificar apenas as colunas que
devero ser usadas em uma equijoin. As colunas referenciadas na clusula USING no
devem ter um qualificador (nome ou apelido de tabela) em qualquer ponto da instruo
SQL.
Por exemplo, esta instruo vlida:
SELECT l.city, d.department_name
FROM
locations l JOIN departments d USING (location_id)
WHERE location_id = 1400;
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-8
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Chave estrangeira
Chave primria
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-9
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
EMPLOYEES
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-10
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Se no houver nomes de colunas comuns entre as duas tabelas, no ser preciso qualificar as
colunas. No entanto, o uso do prefixo da tabela melhora o desempenho, pois voc informa
ao servidor Oracle exatamente onde localizar as colunas.
Observao: Ao efetuar uma operao de join com a clusula USING, voc no poder
qualificar uma coluna usada nessa prpria clusula. Alm disso, se essa coluna for usada em
alguma parte da instruo SQL, ela no poder ser utilizada como apelido.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-11
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-12
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Clusula ON
Use a clusula ON para especificar uma condio de join. Assim, voc pode especificar
condies de join separadas de condies de filtro e pesquisa na clusula WHERE.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-13
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-14
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
EMPLOYEES (WORKER)
EMPLOYEES (MANAGER)
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-15
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-16
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-17
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Joins Tridimensionais
Uma join tridimensional uma join de trs tabelas. Na sintaxe compatvel com o padro
SQL:1999, as joins so executadas da esquerda para a direita. Portanto, a primeira join a ser
executada EMPLOYEES JOIN DEPARTMENTS. A primeira condio de join pode fazer
referncia a colunas de EMPLOYEES e DEPARTMENTS, mas no a colunas de
LOCATIONS. A segunda condio de join pode fazer referncia a colunas de todas as trs
tabelas.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-18
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
FROM
JOIN
ON
JOIN
ON
No-Equijoins
JOB_GRADES
No-Equijoins
Uma no-equijoin uma condio de join que contm algo diferente de um operador de
igualdade.
O relacionamento entre as tabelas EMPLOYEES e JOB_GRADES um exemplo de uma
no-equijoin. Em um relacionamento entre as duas tabelas, os valores da coluna SALARY
da tabela EMPLOYEES devem estar compreendidos entre os valores das colunas
LOWEST_SALARY e HIGHEST_SALARY da tabela JOB_GRADES. O relacionamento
obtido com um operador diferente de igualdade (=).
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-19
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
EMPLOYEES
No-Equijoins (continuao)
O exemplo do slide cria uma no-equijoin para avaliar o nvel salarial de um funcionrio. O
salrio deve estar compreendido entre qualquer par de faixas de salrio mais baixo e mais
alto.
importante observar que todos os funcionrios aparecem uma nica vez quando essa
consulta executada. Os funcionrios no so repetidos na lista. Existem dois motivos para
isso:
Nenhuma das linhas da tabela de nveis de cargos contm nveis sobrepostos. Isto , o
valor do salrio de um funcionrio somente pode estar entre os valores de salrio mais
alto e mais baixo de uma das linhas da tabela de nveis salariais.
Os salrios de todos os funcionrios esto compreendidos entre os limites fornecidos
pela tabela de nveis de cargos. Isto , nenhum funcionrio recebe menos que o valor
mais baixo contido na coluna LOWEST_SAL ou mais que o valor mais alto contido na
coluna HIGHEST_SAL.
Observao: possvel usar outras condies (como <= e >=), mas BETWEEN a mais
simples. Quando usar BETWEEN, lembre-se de informar primeiro o valor mais baixo e
depois o valor mais alto.
Foram especificados apelidos de tabelas no exemplo do slide por questes de desempenho,
e no para evitar uma possvel ambigidade.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-20
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Joins Externas
EMPLOYEES
No h funcionrios no
departamento 190.
Copyright 2004, Oracle. Todos os direitos reservados.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-21
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
DEPARTMENTS
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-22
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-23
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-24
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-25
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Produtos Cartesianos
Produtos Cartesianos
Quando uma condio de join invlida ou completamente omitida, o resultado um
produto cartesiano, no qual todas as combinaes de linhas so exibidas. Todas as linhas da
primeira tabela so unidas a todas as linhas da segunda tabela.
Um produto cartesiano tende a gerar um grande nmero de linhas e o resultado raramente
til. Inclua sempre uma condio de join vlida, a menos que exista uma necessidade
especfica de combinar todas as linhas de todas as tabelas.
Os produtos cartesianos so teis em alguns testes quando necessrio gerar muitas linhas
para simular um volume razovel de dados.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-26
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
DEPARTMENTS (8 linhas)
Produto cartesiano:
20 x 8 = 160 linhas
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-27
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-28
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Sumrio
Nesta lio, voc aprendeu a usar joins para exibir
dados de vrias tabelas por meio de:
Equijoins
No-equijoins
Joins externas
Auto-joins
Joins cruzadas
Joins naturais
Joins externas integrais (ou de dois lados)
Sumrio
H vrias maneiras de unir tabelas.
Tipos de Join
Equijoins
No-equijoins
Joins externas
Auto-joins
Joins cruzadas
Joins naturais
Joins externas integrais (ou de dois lados)
Produtos Cartesianos
Um produto cartesiano resulta na exibio de todas as combinaes de linhas. Para obter
esse resultado, omita a clusula WHERE ou especifique a clusula CROSS JOIN.
Apelidos de Tabelas
Os apelidos de tabelas aceleram o acesso ao banco de dados.
Eles podem ajudar a reduzir o cdigo SQL, preservando a memria.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-29
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-30
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 5
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-31
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 5 (continuao)
4. Crie um relatrio para exibir o sobrenome e o nmero dos funcionrios, bem como o
sobrenome e o nmero dos respectivos gerentes. Atribua s colunas os labels
Employee, Emp#, Manager e Mgr#, respectivamente. Inclua a instruo SQL no
arquivo de texto lab_05_04.sql.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-32
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
6. Crie um relatrio para o departamento de recursos humanos que exiba os
sobrenomes e os nmeros de departamento dos funcionrios, bem como todos os
funcionrios que trabalham no mesmo departamento como um funcionrio
especfico. Atribua um label apropriado a cada coluna. Salve o script no arquivo
lab_05_06.sql.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-33
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 5 (continuao)
5. Modifique lab_05_04.sql para exibir todos os funcionrios, inclusive King, que
no possui gerente. Ordene os resultados pelo nmero do funcionrio. Inclua a
instruo SQL no arquivo de texto lab_05_05.sql. Execute a consulta em
lab_05_05.sql.
Exerccio 5 (continuao)
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-34
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 5 (continuao)
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 5-35
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Usando Subconsultas
para Solucionar Consultas
Objetivos
Ao concluir esta lio, voc ser capaz de:
Definir subconsultas
Objetivos
Nesta lio, voc conhecer os recursos mais avanados da instruo SELECT. possvel
criar subconsultas na clusula WHERE de outra instruo SQL para obter valores baseados
em um valor condicional desconhecido. Esta lio aborda subconsultas de uma nica linha e
de vrias linhas.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-2
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Subconsulta:
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-3
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Sintaxe da Subconsulta
select_list
table
expr operator
(SELECT
FROM
select_list
table);
Sintaxe da Subconsulta
Uma subconsulta uma instruo SELECT incorporada a uma clusula de outra instruo
SELECT. possvel criar instrues complexas a partir de instrues simples usando
subconsultas. Elas podero ser muito teis quando for necessrio selecionar linhas de uma
tabela com uma condio que dependa dos dados da prpria tabela.
possvel inserir a subconsulta em vrias clusulas SQL, inclusive nestas:
Clusula WHERE
Clusula HAVING
Clusula FROM
Na sintaxe:
operator inclui uma condio de comparao, como >, = ou IN
Observao: As condies de comparao esto includas em duas classes: operadores
de uma nica linha (>, =, >=, <, <>, <=) e de vrias linhas (IN, ANY, ALL).
Em geral, a subconsulta denominada instruo SELECT interna, sub-SELECT ou
SELECT aninhada. A subconsulta normalmente executada primeiro e o seu resultado
usado para concluir a condio da consulta principal (ou externa).
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-4
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
FROM
WHERE
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-5
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT last_name
11000
FROM
employees
WHERE salary >
(SELECT salary
FROM
employees
WHERE last_name = 'Abel');
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-6
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Tipos de Subconsultas
retorna
ST_CLERK
retorna
ST_CLERK
SA_MAN
Tipos de Subconsultas
Subconsultas de uma nica linha: consultas que retornam somente uma linha da
instruo SELECT interna
Subconsultas de vrias linhas: consultas que retornam mais de uma linha da instruo
SELECT interna
Observao: H tambm subconsultas de vrias colunas, ou seja, consultas que retornam
mais de uma coluna da instruo SELECT interna. Elas so abordadas no curso Banco de
Dados Oracle 10g: Fundamentos de SQL II.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-7
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Subconsulta
Igual a
>
Maior que
>=
<
Menor que
<=
<>
Diferente de
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-8
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Operador Significado
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-9
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Usando Functions de
Grupo em uma Subconsulta
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-10
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
department_id, MIN(salary)
employees
department_id
2500
MIN(salary) >
(SELECT MIN(salary)
FROM
employees
WHERE department_id = 50);
Exemplo
Localize o cargo com o menor salrio mdio.
SELECT
job_id, AVG(salary)
FROM employees
GROUP BY job_id
HAVING
AVG(salary) = (SELECT
MIN(AVG(salary))
FROM employees
GROUP BY job_id);
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-11
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
ERROR at line 4:
ORA-01427: single-row subquery returns more than
one row
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-12
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
no rows selected
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-13
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Significado
IN
ANY
ALL
Exemplo
Localize os funcionrios cujo salrio igual ao salrio mnimo em cada departamento.
A consulta interna executada primeiro e produz um resultado. O bloco de consulta
principal processado depois e usa os valores retornados pela consulta interna para concluir
sua condio de pesquisa. Na verdade, a consulta principal aparece para o servidor Oracle
da seguinte forma:
SELECT last_name, salary, department_id
FROM employees
WHERE salary IN (2500, 4200, 4400, 6000, 7000, 8300,
8600, 17000);
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-14
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-15
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-16
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
IN
(SELECT mgr.manager_id
FROM
employees mgr);
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-17
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
no rows selected
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-18
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Sumrio
select_list
table
expr operator
(SELECT select_list
FROM
table);
Sumrio
Nesta lio, voc aprendeu a usar subconsultas. Uma subconsulta uma instruo SELECT
incorporada a uma clusula de outra instruo SQL. As subconsultas so teis quando uma
consulta se baseia em um critrio de pesquisa com valores intermedirios desconhecidos.
As subconsultas apresentam as seguintes caractersticas:
Podem passar uma linha de dados para uma instruo principal que contm um
operador de uma nica linha, como =, <>, >, >=, < ou <=
Podem passar vrias linhas de dados para uma instruo principal que contm um
operador de vrias linhas, como IN
So processadas primeiro pelo servidor Oracle. Em seguida, a clusula WHERE ou
HAVING utiliza os resultados
Podem conter functions de grupo
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-19
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-20
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 6
3. Crie uma consulta que exiba o nmero e o sobrenome de todos os funcionrios que
trabalham em um departamento com funcionrios cujos sobrenomes contm a letra
u. Inclua a instruo SQL no arquivo de texto lab_06_03.sql. Execute a
consulta.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-21
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 6 (continuao)
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 6-22
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Objetivos
Ao concluir esta lio, voc ser capaz de:
Objetivos
Nesta lio, voc aprender a criar consultas com os operadores de conjunto.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-2
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Operadores de Conjunto
A
UNION/UNION ALL
INTERSECT
MINUS
Operadores de Conjunto
Os operadores de conjunto combinam os resultados de duas ou mais consultas componentes
em um resultado. As consultas que contm operadores de conjunto so denominadas
consultas compostas.
Operador
Retorna
UNION
UNION ALL
INTERSECT
MINUS
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-3
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-4
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
DESCRIBE employees
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-5
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
DESCRIBE job_history
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-6
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
FROM employees;
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-7
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Operador UNION
B
Operador UNION
O operador UNION retorna todas as linhas selecionadas pelas consultas. Utilize-o para
retornar todas as linhas de vrias tabelas e eliminar linhas duplicadas.
Diretrizes
O nmero de colunas e os tipos de dados das colunas selecionadas devem ser idnticos
em todas as instrues SELECT usadas na consulta. Os nomes das colunas no
precisam ser idnticos.
UNION opera em todas as colunas selecionadas.
Os valores nulos no so ignorados durante a verificao de valores duplicados.
O operador IN tem precedncia em relao ao operador UNION.
Por default, a sada classificada em ordem crescente da primeira coluna da clusula
SELECT.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-8
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-9
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
FROM
UNION
SELECT
FROM
Na sada anterior, o funcionrio 200 aparece trs vezes. Por qu? Observe os valores de
DEPARTMENT_ID relativos a esse funcionrio. O valor de DEPARTMENT_ID em uma
linha 90, em outra 10 e na terceira 90. Em funo dessas combinaes exclusivas de
IDs de cargo e IDs de departamento, cada linha relativa ao funcionrio 200 exclusiva e,
por isso, no considerada duplicada. Observe que a sada classificada em ordem
crescente da primeira coluna da clusula SELECT (nesse caso, EMPLOYEE_ID).
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-10
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-11
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
A consulta anterior retorna 29 linhas. Isso porque ela elimina a seguinte linha (j que ela
duplicada):
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-12
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Operador INTERSECT
B
Operador INTERSECT
Use o operador INTERSECT para retornar todas as linhas comuns a vrias consultas.
Diretrizes
O nmero de colunas e os tipos de dados das colunas selecionadas pelas instrues
SELECT nas consultas devem ser idnticos em todas as instrues SELECT usadas na
consulta. Os nomes das colunas no precisam ser idnticos.
O resultado no alterado quando invertida a ordem das tabelas de interseo.
INTERSECT no ignora valores nulos.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-13
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Operador MINUS
B
Operador MINUS
Use o operador MINUS para exibir as linhas retornadas pela primeira consulta que no esto
presentes na segunda consulta (a primeira instruo SELECT subtrada da segunda instruo
SELECT).
Diretrizes
O nmero de colunas e os tipos de dados das colunas selecionadas pelas instrues
SELECT nas consultas devem ser idnticos em todas as instrues SELECT usadas na
consulta. Os nomes das colunas no precisam ser idnticos.
Todas as colunas da clusula WHERE devem estar presentes na clusula SELECT para
que o operador MINUS seja executado.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-15
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Operador MINUS
Exiba os IDs dos funcionrios que nunca mudaram
de cargo.
employee_id,job_id
employees
employee_id,job_id
job_history;
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-16
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
FROM
MINUS
SELECT
FROM
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-18
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-19
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-20
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT
FROM
UNION
SELECT
FROM
Em que OPTION :
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-22
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Sumrio
Sumrio
O operador UNION retorna todas as linhas selecionadas pelas consultas. Utilize-o para
retornar todas as linhas de vrias tabelas e eliminar linhas duplicadas.
Use o operador UNION ALL para retornar todas as linhas de vrias consultas. Ao
contrrio do que ocorre com o operador UNION, as linhas duplicadas no so
eliminadas e, por default, a sada no classificada.
Use o operador INTERSECT para retornar todas as linhas comuns a vrias consultas.
Use o operador MINUS para exibir as linhas retornadas pela primeira consulta que no
esto presentes na segunda consulta.
Lembre-se de usar a clusula ORDER BY somente no final da instruo composta.
Certifique-se de que as expresses correspondentes nas listas SELECT coincidem em
nmero e tipo de dados.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-23
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-24
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 7
3.
Produza uma lista de cargos dos departamentos 10, 50 e 20, nessa ordem. Exiba o ID
de cargo e o ID de departamento usando operadores de conjunto.
4. Crie um relatrio que liste os IDs de funcionrio e os IDs de cargo dos funcionrios
que, no momento, esto no mesmo cargo que ocupavam quando foram admitidos
pela empresa (ou seja, eles mudaram de cargo, mas agora voltaram para o cargo
original).
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-25
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 7 (continuao)
5. O departamento de recursos humanos precisa de um relatrio com as seguintes
especificaes:
Sobrenome e ID do departamento de todos os funcionrios da tabela
EMPLOYEES, mesmo que no pertenam a um departamento
ID e nome de todos os departamentos da tabela DEPARTMENTS, mesmo que no
tenham funcionrios
Crie uma consulta composta para isso.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 7-26
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Manipulando Dados
Objetivos
Ao concluir esta lio, voc ser capaz de:
Objetivo
Nesta lio, voc aprender a usar instrues DML para inserir linhas em uma tabela,
atualizar as linhas existentes em uma tabela e deletar as linhas existentes de uma tabela.
Voc tambm aprender a controlar transaes com as instrues COMMIT, SAVEPOINT e
ROLLBACK.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-2
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-3
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
DEPARTMENTS
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-4
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
INSERT INTO
VALUES
o nome da tabela
o nome da coluna da tabela a ser preenchida
o valor correspondente da coluna
Observao: Esta instruo com a clusula VALUES adiciona somente uma linha por vez a
uma tabela.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-5
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
departments
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-6
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
INSERT INTO
Descrio
Implcito
Omita a coluna da
lista de colunas.
Especifique a palavra-chave NULL na lista VALUES;
especifique a string vazia ('') na lista VALUES para strings de
caracteres e datas.
Explcito
Certifique-se de que a coluna de destino permita valores nulos verificando o status Null?
com o comando DESCRIBE do iSQL*Plus.
O servidor Oracle impe automaticamente todos os tipos de dados, faixas de dados e
constraints de integridade de dados. Todas as colunas no listadas explicitamente obtm um
valor nulo na nova linha.
Erros comuns que podem ocorrer durante a entrada do usurio:
Valor obrigatrio ausente para uma coluna NOT NULL
Constraint de exclusividade violada por valor duplicado
Constraint de chave estrangeira violada
Constraint CHECK violada
Incompatibilidade de tipo de dados
Valor muito extenso para caber na coluna
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-7
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
departments (department_id,
department_name
VALUES
(30, 'Purchasing');
1 row created.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-8
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Verifique a adio.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-9
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Criando um Script
1 row created.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-10
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
VALUES
Na sintaxe:
table
column
subquery
o nome da tabela
o nome da coluna da tabela a ser preenchida
a subconsulta que retorna linhas para a tabela
Para obter mais informaes, consulte "SELECT" (seo "subqueries") no manual Oracle
Database SQL Reference.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-11
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
4 rows created.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-12
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
EMPLOYEES
UPDATE
SET
[WHERE
table
column = value [, column = value, ...]
condition];
Atualizando Linhas
possvel modificar linhas existentes com a instruo UPDATE.
Na sintaxe:
table
column
value
condition
o nome da tabela
o nome da coluna da tabela a ser preenchida
o valor correspondente ou a subconsulta da coluna
identifica as linhas a serem atualizadas e composta de nomes
de colunas, expresses, constantes, subconsultas e operadores
de comparao
Para confirmar a operao de atualizao, consulte a tabela para exibir as linhas atualizadas.
Para obter mais informaes, consulte "UPDATE" no manual Oracle Database SQL
Reference.
Observao: Em geral, use a chave primria para identificar uma nica linha. O uso de
outras colunas pode resultar na atualizao inesperada de vrias linhas. Por exemplo,
identificar uma nica linha da tabela EMPLOYEES por nome perigoso, pois mais de um
funcionrio pode ter o mesmo nome.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-13
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
UPDATE
copy_emp
SET
department_id = 110;
22 rows updated.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-14
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
UPDATE employees
SET
department_id = 70
WHERE employee_id = 113;
1 row updated.
=
(SELECT
column
FROM table
WHERE condition)
[ ,
column
[WHERE
(SELECT
column
FROM table
WHERE condition)]
condition] ;
Observao: Se nenhuma linha for atualizada, a mensagem "0 rows updated" ser
exibida.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-15
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
UPDATE
SET
UPDATE
SET
copy_emp
department_id
WHERE
job_id
(SELECT department_id
FROM employees
WHERE employee_id = 100)
(SELECT job_id
FROM employees
WHERE employee_id = 200);
1 row updated.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-16
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-17
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
DEPARTMENTS
Instruo DELETE
possvel remover as linhas existentes de uma tabela
com a instruo DELETE:
table
condition];
Deletando Linhas
possvel remover linhas existentes com a instruo DELETE.
Na sintaxe:
table
condition
o nome da tabela
identifica as linhas a serem deletadas e composta de nomes
de colunas, expresses, constantes, subconsultas e operadores
de comparao
Observao: Se nenhuma linha for deletada, a mensagem "0 rows deleted" ser
exibida.
Para obter mais informaes, consulte "DELETE" no manual Oracle Database SQL
Reference.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-18
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
DELETE [FROM]
[WHERE
Se voc omitir a clusula WHERE, todas as linhas da tabela sero deletadas. O segundo
exemplo do slide deleta todas as linhas da tabela COPY_EMP porque nenhuma clusula
WHERE foi especificada.
Exemplo
Remova as linhas identificadas na clusula WHERE.
DELETE FROM employees WHERE employee_id = 114;
1 row deleted.
DELETE FROM departments WHERE department_id IN (30, 40);
2 rows deleted.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-19
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-20
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Sintaxe:
Exemplo:
Instruo TRUNCATE
Um mtodo mais eficiente de esvaziar uma tabela a utilizao da instruo TRUNCATE.
possvel usar essa instruo para remover rapidamente todas as linhas de uma tabela ou
cluster. A remoo de linhas com a instruo TRUNCATE mais rpida do que com a
instruo DELETE pelos seguintes motivos:
A instruo TRUNCATE uma instruo DDL (Data Definition Language) e no gera
informaes de rollback. As informaes de rollback so abordadas posteriormente
nesta lio.
Truncar uma tabela no dispara os triggers de deleo dessa tabela.
Se a tabela for me de uma constraint de integridade referencial, voc no poder
trunc-la. necessrio desativar a constraint antes de executar a instruo TRUNCATE.
A desativao de constraints abordada em uma lio posterior.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-21
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Instruo TRUNCATE
INSERT INTO
(SELECT employee_id, last_name,
email, hire_date, job_id, salary,
department_id
FROM
employees
WHERE department_id = 50)
VALUES (99999, 'Taylor', 'DTAYLOR',
TO_DATE('07-JUN-99', 'DD-MON-RR'),
'ST_CLERK', 5000, 50);
1 row created.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-22
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-23
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Descrio
DML (Data
Manipulation
Language)
(Data Definition
Language)
DCL (Data Control
Language)
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-24
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
automtico).
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-25
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-26
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Controlando Transaes
Horrio COMMIT
Transao
DELETE
SAVEPOINT A
ROLLBACK
UPDATE
SAVEPOINT B
INSERT
ROLLBACK at o
PONTO DE SALVAMENTO A
ROLLBACK at o
PONTO DE SALVAMENTO B
Copyright 2004, Oracle. Todos os direitos reservados.
Descrio
COMMIT
SAVEPOINT name
ROLLBACK
ROLLBACK TO
SAVEPOINT name
INSERT
UPDATE...
SAVEPOINT update_done;
Savepoint created.
INSERT...
ROLLBACK TO update_done;
Rollback complete.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-28
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Fazendo Rollback de
Alteraes at um Marcador
Automatic rollback
Circunstncias
A instruo DDL ou DCL executada.
O iSQL*Plus foi encerrado normalmente, sem a execuo
explcita dos comandos COMMIT ou ROLLBACK.
Encerramento anormal do iSQL*Plus ou falha do sistema.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-29
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
No iSQL*Plus, para sair normalmente da sesso, voc deve clicar no boto Exit. No
SQL*Plus, para executar essa mesma ao, voc deve digitar o comando EXIT no prompt.
O fechamento da janela interpretado como uma sada anormal.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-30
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-31
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-32
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Efetue as alteraes:
COMMIT;
Commit complete.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-33
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-34
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
SELECT * FROM
test WHERE
No rows selected.
id = 100;
COMMIT;
Commit complete.
Exemplo
Ao tentar remover um registro da tabela TEST, voc poder esvaziar a tabela
acidentalmente. possvel corrigir o erro, reexecutar a instruo correta e tornar a alterao
de dados permanente.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-35
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-36
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Consistncia de Leitura
Os usurios acessam o banco de dados de duas maneiras:
Operaes de leitura (instruo SELECT)
Operaes de gravao (instrues INSERT, UPDATE, DELETE)
A consistncia de leitura necessria para permitir que:
Os usurios que efetuam operaes de leitura e gravao no banco de dados tenham
uma view consistente dos dados.
Os usurios que efetuam operaes de leitura no vejam dados que esto sendo
alterados.
Os usurios que efetuam operaes de gravao tenham certeza de que as alteraes no
banco de dados so feitas de maneira consistente.
As alteraes feitas por usurios que efetuam operaes de gravao no interrompam
umas s outras nem sejam conflitantes.
O objetivo da consistncia de leitura garantir que cada usurio veja os dados no estado em
que se encontravam no momento do ltimo commit, antes de ser iniciada uma operao
DML.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-37
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Consistncia de Leitura
Blocos
de dados
SELECT *
FROM userA.employees; Imagem
com leitura
consistente
Usurio B
Dados
alterados e
inalterados
Antes da
alterao
(dados
antigos)
Segmentos
de undo
Sumrio
Function
Descrio
INSERT
UPDATE
DELETE
COMMIT
SAVEPOINT
ROLLBACK
Sumrio
Nesta lio, voc aprendeu a manipular dados no banco de dados Oracle com as instrues
INSERT, UPDATE e DELETE, bem como controlar alteraes nos dados com as instrues
COMMIT, SAVEPOINT e ROLLBACK.
O servidor Oracle garante uma view consistente dos dados em todos os momentos.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-39
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-40
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 8
O departamento de recursos humanos deseja criar instrues SQL para inserir, atualizar
e deletar dados de funcionrios. Como prottipo, use a tabela MY_EMPLOYEE antes de
fornecer as instrues ao departamento de recursos humanos.
Insira dados na tabela MY_EMPLOYEE.
1. Execute a instruo no script lab_08_01.sql para criar a tabela MY_EMPLOYEE
a ser usada no exerccio.
3. Crie uma instruo INSERT para adicionar a primeira linha de dados tabela
MY_EMPLOYEE usando estes dados de amostra. No liste as colunas na clusula
INSERT. No informe todas as linhas ainda.
ID
LAST_NAME
FIRST_NAME
USERID
SALARY
Patel
Ralph
rpatel
895
Dancs
Betty
bdancs
860
Biri
Ben
bbiri
1100
Newman
Chad
cnewman
750
Ropeburn
Audrey
aropebur
1550
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-41
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 8 (continuao)
6. Crie uma instruo insert no arquivo de script dinmico reutilizvel loademp.sql
para carregar linhas na tabela MY_EMPLOYEE. Concatene a primeira letra do
primeiro nome e os sete primeiros caracteres do sobrenome para gerar o ID do
usurio. Salve esse script no arquivo lab_08_06.sql.
7. Para preencher a tabela com as prximas duas linhas dos dados de amostra, execute
a instruo insert no script criado.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-42
OracleWDP_ww@oracle.com if you have not received your personalized eKit.
Exerccio 8 (continuao)
15. Submeta todas as alteraes pendentes a commit.
Controle a transao de dados na tabela MY_EMPLOYEE.
16. Preencha a tabela com a ltima linha dos dados de amostra usando as instrues no
script criado na etapa 6. Execute as instrues no script.
Development Program (WDP) eKit materials are provided for WDP in-class use only. Copying eKit materials is strictly prohibited and is in
violation of Oracle copyright. All WDP students must receive an eKit watermarked with their name and email. Contact
Banco de Dados Oracle 10g: Fundamentos de SQL I 8-43
OracleWDP_ww@oracle.com if you have not received your personalized eKit.