Você está na página 1de 235

Oracle SQL 11g

Foundations PTB
1

INDICE
Recuperando dados com o SQL SELECT declaração 2,17

Restringindo e Classificando Dados 18,46

Usando Funções Oracle 47,65

Usando Funções de Conversão Expressões Condicionais 66,89

Relatórios com Dados Agregados Usando as Funções de Grupo 90,108

Exibindo Dados a partir de Varias Tabelas 109,124

Usando subconsultas para Resolver Consultas 125,139

Usando o conjunto de operadores 140,149

Manipulando Dados 150,172

Usando Instruções DDL para Criar e Gerenciar Tabelas 173,199

Criação de objetos de SCHEMA 200,217

Usando SQL*Plus 218,223

Executando instruções DML e DDL Operações com o GUI SQL Developer 224

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
2

Recuperando dados com o SQL


SELECT declaração.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
3

Declaração Basica SELECT


SELECT *|{[DISTINCT] column|expression [alias],...}
FROM table;

• SELECT identifica as colunas a serem exibidos.


• FROM identifica a tabela que contém as colunas.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
4

Selecionando todas as colunas

SELECT *
FROM departments;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
5

Selecionando Colunas Específicas

SELECT department_id, location_id


FROM departments;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
6

Expressões Aritméticas

Criar expressões com números e datas de dados usando


operadores aritméticos.

Operator Description

+ Add

- Subtract

* Multiply

/ Divide

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
7

Usando operadores aritméticos

SELECT last_name, salary, salary + 300


FROM employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
8

Precedência de Operadores

SELECT last_name, salary, 12*salary+100


FROM employees; 1


SELECT last_name, salary, 12*(salary+100)
FROM employees; 2

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
9

Definindo Valor nulo

Nulo é um valor que não está disponível, não atribuído,


desconhecido ou inaplicável.
Nulo não é o mesmo que zero ou um espaço em branco.

SELECT last_name, job_id, salary, commission_pct


FROM employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
10

Valores Nulos em Expressões Aritméticas


As expressões aritméticas contendo um valor nulo avaliar
como nulo.

SELECT last_name, 12*salary*commission_pct


FROM employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
11

Usando Alias de coluna

SELECT last_name AS name, commission_pct comm


FROM employees;

SELECT last_name "Name" , salary*12 "Annual Salary"


FROM employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
12

Operador de Concatenação

• É representado por duas barras verticais (||)

SELECT last_name||job_id AS "Employees"


FROM employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
13

Utilizando cadeias de caracteres literais

SELECT last_name ||' is a '||job_id


AS "Employee Details"
FROM employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
14

Operador Alternativo

SELECT department_name || ' Department' ||


q'['s Manager Id: ]'
|| manager_id
AS "Department and Manager"
FROM departments;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
15

Linhas Duplicadas

SELECT department_id
FROM employees; 1


SELECT DISTINCT department_id
FROM employees; 2

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
16

Mostrar a Estrutura da Tabela

Usar o DESCRIBE comando para mostrar a estrutura de


uma tabela.

DESC[RIBE] tablename

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
17

Usando o Comando DESCRIBE

DESCRIBE employees

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
18

Restringindo e Classificando
Dados

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
19

Limitando Linhas utilizando o


Comando Select

EMPLOYEES


“retrieve all
employees in department 90”

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
20

Limitando as linhas que são selecionadas

• Restringir as linhas que são retornadas usando a


cláusula WHERE:

SELECT *|{[DISTINCT] column|expression [alias],...}


FROM table
[WHERE condition(s)];

• A cláusula WHERE segue a cláusula


FROM.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
21

Usando a cláusula WHERE

SELECT employee_id, last_name, job_id, department_id


FROM employees
WHERE department_id = 90 ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
22

Cadeias de caracteres e datas


• Cadeias de caracteres e valores de data são
colocados entre aspas simples.
• • Os valores dos caracteres são maiúsculas de
minúsculas e valores de data são sensíveis ao
formato.
• O formato de exibição de data padrão é
DD-MON-RR.

SELECT last_name, job_id, department_id


FROM employees
WHERE last_name = 'Whalen' ;

SELECT last_name
FROM employees
WHERE hire_date = '17-FEB-96' ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
23

Operadores de comparação

Operator Meaning

= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to
BETWEEN Between two values (inclusive)
...AND...

IN(set) Match any of a list of values

LIKE Match a character pattern


IS NULL
Is a null value

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
24

Usando Operadores de Comparação

SELECT last_name, salary


FROM employees
WHERE salary <= 3000 ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
25

Condições de Intervalo usando o operador


Between
Use o operador BETWEEN para exibir linhas com base em
um intervalo de valores:

SELECT last_name, salary


FROM employees
WHERE salary BETWEEN 2500 AND 3500 ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
26

Condições usando o operador IN

Use o operador IN para testar valores em uma lista:

SELECT employee_id, last_name, salary, manager_id


FROM employees
WHERE manager_id IN (100, 101, 201) ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
27

Combinação de padrões utilizando o operador


LIKE
Use o operador LIKE para executar pesquisas curinga de
valores de string de pesquisa válidos.
Condições de pesquisa pode conter caracteres literais ou
números:

SELECT first_name
FROM employees
WHERE first_name LIKE 'S%' ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
28

Combinando Caracteres Curinga

SELECT last_name
FROM employees
WHERE last_name LIKE '_o%' ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
29

Utilizando as condições NULL

Teste para valores nulos com o operador IS NULL.


SELECT last_name, manager_id
FROM employees
WHERE manager_id IS NULL ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
30

Definição das condições usando os operadores


lógicos

Operator Meaning

AND Returns TRUE if both component conditions


are true
OR Returns TRUE if either component condition
is true
NOT
Returns TRUE if the condition is false

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
31

Usando o Operador And


AND requer tanto as condições de componentes para ser
verdade:
SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary >= 10000
AND job_id LIKE '%MAN%' ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
32

Usando o Operador OR
OR requer qualquer condição componente para ser
verdade:
SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary >= 10000
OR job_id LIKE '%MAN%' ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
33

Usando o Operador Not

SELECT last_name, job_id


FROM employees
WHERE job_id
NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
34

Regras de Precedência

Operator Meaning

1 Arithmetic operators
2 Concatenation operator
3 Comparison conditions
4 IS [NOT] NULL, LIKE, [NOT] IN
5 [NOT] BETWEEN
6 Not equal to
7 NOT logical condition

8 AND logical condition

9 OR logical condition

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
35

Regras de Precedência

SELECT last_name, job_id, salary


FROM employees
WHERE job_id = 'SA_REP'
OR job_id = 'AD_PRES' 1
AND salary > 15000;

SELECT last_name, job_id, salary


FROM employees 2
WHERE (job_id = 'SA_REP'
OR job_id = 'AD_PRES')
AND salary > 15000;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
36

Usando a Clausula Order By

Classificar linhas recuperadas com a cláusula ORDER BY:


– ASC: Ascendente ( Padrão )
– DESC: ordem Descendente

SELECT last_name, job_id, department_id, hire_date


FROM employees
ORDER BY hire_date ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
37

Classificação
1ª - Desc

SELECT last_name, job_id, department_id, hire_date


FROM employees
ORDER BY hire_date DESC ; 1
2ª - Asc
SELECT employee_id, last_name, salary*12 annsal
FROM employees
ORDER BY annsal ;
2

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
38

Classificação
Classificação usando posicionamento numérico das
colunas:
SELECT last_name, job_id, department_id, hire_date
FROM employees 3
ORDER BY 3;

Classificação com Multiplas Colunas:


SELECT last_name, department_id, salary
FROM employees 4
ORDER BY department_id, salary DESC;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
39

Variaveis de Substituição

... salary = ? …
… department_id = ? …
... last_name = ? ...

I want
to query
different
values.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
40

Usando o Conceito de Variáveis de


Substituição
Use uma variável com (&) para solicitar ao usuário um valor:

SELECT employee_id, last_name, salary, department_id


FROM employees
WHERE employee_id = &employee_num ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
41

Usando Variaveis de Substituição

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
42

Usando Variaveis de Substituição

SELECT last_name, department_id, salary*12


FROM employees
WHERE job_id = '&job_title' ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
43

Especificando nome de coluna,


Expressões e Texto
SELECT employee_id, last_name, job_id,&column_name
FROM employees
WHERE &condition
ORDER BY &order_column ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
44

Usando o Duplo (&&) nas Variáveis de


Substituição
SELECT employee_id, last_name, job_id, &&column_name
FROM employees
ORDER BY &column_name ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
45

Usando o Comando Define

Use o comando DEFINE para criar e atribuir um valor a


uma variável.
Use o comando UNDEFINE para remover variável.

DEFINE employee_num = 200

SELECT employee_id, last_name, salary, department_id


FROM employees
WHERE employee_id = &employee_num ;
UNDEFINE employee_num

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
46

Usando o Comando Verify

Use o comando VERIFY para alternar a exibição da


variável de substituição, tanto antes como depois de SQL
Developer substitui as variáveis de substituição com
valores:

SET VERIFY ON

SELECT employee_id, last_name, salary


FROM employees
WHERE employee_id = &employee_num;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
47

Usando Funções Oracle

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
48

Funções SQL

Input Output

Function

arg 1 Function performs action

arg 2
Result
value

arg n

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
49

Funções de Simples Linha

Character

General Single-row Number


functions

Conversion Date

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
50

Funções de Caracteres

Character
functions

Case-conversion Character-manipulation
functions functions

LOWER CONCAT
UPPER SUBSTR
INITCAP LENGTH
INSTR
LPAD | RPAD
TRIM
REPLACE

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
51

Funções de Conversão

Estas funções de conversão de caracteres:


Function Result

LOWER('SQL Course') sql course


UPPER('SQL Course') SQL COURSE
INITCAP('SQL Course') Sql Course

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
52

Funções de Conversão
Usando a Função Lower – Converter o Caráter em
Minúsculo :

SELECT employee_id, last_name, department_id


FROM employees
WHERE last_name = 'higgins';

SELECT employee_id, last_name, department_id


FROM employees
WHERE LOWER(last_name) = 'higgins';

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
53

Funções de Manipulação de Caracteres

Estas funções de manipulação de caracteres:

Function Result

CONCAT('Hello', 'World') HelloWorld


SUBSTR('HelloWorld',1,5) Hello
LENGTH('HelloWorld') 10
INSTR('HelloWorld', 'W') 6
LPAD(salary,10,'*') *****24000
RPAD(salary, 10, '*') 24000*****
REPLACE BLACK and BLUE
('JACK and JUE','J','BL')
TRIM('H' FROM 'HelloWorld') elloWorld

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
54

Usando Funções de Manipulações de


Caracteres
SELECT employee_id, CONCAT(first_name, last_name) NAME,
job_id, LENGTH (last_name),
INSTR(last_name, 'a') "Contains 'a'?"
FROM employees
WHERE SUBSTR(job_id, 4) = 'REP';

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
55

Funções Numéricas

• ROUND: Arredondar os valores decimal


• TRUNC: Truncar os valores decimal
• MOD: Retornar o resto da divisão

Function Result

ROUND(45.926, 2) 45.93
TRUNC(45.926, 2) 45.92
MOD(1600, 300) 100

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
56

Usando a Função ROUND

SELECT ROUND(45.923,2), ROUND(45.923,0),ROUND(45.923,-1)


FROM DUAL;

DUAL Tabela utilizada para cálculos aritméticos.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
57

Usando a Função TRUNC

SELECT TRUNC(45.923,2), TRUNC(45.923),TRUNC(45.923,-1)


FROM DUAL;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
58

Usando a Função MOD

SELECT last_name, salary, MOD(salary, 5000)


FROM employees
WHERE job_id = 'SA_REP';

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
59

Trabalhando com Datas

SELECT last_name, hire_date


FROM employees
WHERE hire_date < '01-FEB-88';

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
60

RR Formato de Data

Current
Current Year
Year Specified Date RR Format YY Format
1995 27-OCT-95 1995
1995 27-OCT-17 2017 1995
2001 27-OCT-17 2017 1917
2001 27-OCT-95 1995 2017

If the specified two-digit year is:

0–49 50–99

If two digits of the The return date is in the The return date is in the
current 0–49 current century century before the current one
year are:

The return date is in the The return date is in the


century after the current one current century
50–99

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
61

Usando a Função Sysdate

SYSDATE é uma função que retorna:


• Date
• Time

SELECT sysdate
FROM dual;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
62

Usando Operadores Aritméticos com Data

SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS


FROM employees
WHERE department_id = 90;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
63

Funções de Manipulação de Datas

Function Result

MONTHS_BETWEEN Number of months between two dates

ADD_MONTHS Add calendar months to date

NEXT_DAY Next day of the date specified

LAST_DAY Last day of the month

ROUND Round date


TRUNC Truncate date

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
64

Usando Funções de Data

Function Result

MONTHS_BETWEEN 19.6774194
('01-SEP-95','11-JAN-94')

ADD_MONTHS (‘31-JAN-96',1) ‘29-FEB-96'


NEXT_DAY ('01-SEP-95','FRIDAY') '08-SEP-95'
LAST_DAY ('01-FEB-95') '28-FEB-95'

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
65

Usando Função ROUND, TRUNC com Data

Assume SYSDATE = '25-JUL-03':


Function Result

ROUND(SYSDATE,'MONTH') 01-AUG-03
ROUND(SYSDATE ,'YEAR') 01-JAN-04
01-JUL-03
TRUNC(SYSDATE ,'MONTH')
TRUNC(SYSDATE ,'YEAR') 01-JAN-03

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
66

Usando Funções de Conversão


Expressões Condicionais

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
67

Funções de Conversões

Data type
conversion

Implicit data type Explicit data type


conversion conversion

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
68

Tipo de Dados Implícito de Conversão

Em expressões, o servidor Oracle pode converter


automaticamente o seguinte:
From To

VARCHAR2 or CHAR NUMBER

VARCHAR2 or CHAR DATE

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
69

Tipo de Dados Implícito de Conversão

Para a avaliação da expressão, o servidor Oracle pode


converter automaticamente o seguinte:
From To

NUMBER VARCHAR2 or CHAR

DATE VARCHAR2 or CHAR

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
70

Tipo de Dados Explicito de Conversão

TO_NUMBER TO_DATE

NUMBER CHARACTER DATE

TO_CHAR TO_CHAR

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
71

Usando a função TO_CHAR com Datas

TO_CHAR(date, 'format_model')

Deve ser colocado entre aspas simples


É sensível a maiúsculas
Pode incluir qualquer elemento de formato de data válida
Tem um elemento fm para remover espaços em branco
acolchoado ou suprimir zeros à esquerda
É separado do valor de data por uma vírgula

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
72

Modelo de Formato de Data

Element Result

YYYY Full year in numbers

YEAR Year spelled out (in English)

MM Two-digit value for the month


MONTH Full name of the month

MON Three-letter abbreviation of the month


DY Three-letter abbreviation of the day of the week
DAY Full name of the day of the week
DD Numeric day of the month

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
73

Usando os formatos de data

• Hora(24) , Minutos e Segundos:


HH24:MI:SS AM 15:45:32 PM

• Dia e Mes:
DD "of" MONTH 12 of OCTOBER

• Decimo Quarto:
ddspth fourteenth

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
74

Usando a Função TO_CHAR com Data

SELECT last_name,TO_CHAR(hire_date, 'fmDD Month YYYY')


AS HIREDATE
FROM employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
75

Usando Função TO_CHAR ( Numérica )


TO_CHAR(number, 'format_model')

Estes são alguns dos elementos de formato que você pode


usar com a função TO_CHAR para exibir um valor numérico:

Element Result

9 Represents a number

Forces a zero to be displayed


0

$ Places a floating dollar sign

L Uses the floating local currency symbol

. Prints a decimal point

, Prints a comma as a thousands indicator

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
76

Usando a Função TO_CHAR com Expressão


Numérica

SELECT TO_CHAR(salary, '$99,999.00') SALARY


FROM employees
WHERE last_name = 'Ernst';

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
77

Usando Funções TO_NUMBER e TO_DATE


Convertendo strings em expressão numérica:

TO_NUMBER(char[, 'format_model'])

Convertendo strings em formato de data usando a


Função TO_DATE:

TO_DATE(char[, 'format_model'])

Estas funções têm um modificador fx. Este modificador


especifica a correspondência exata para o modelo de
formato argumento caráter e data de uma função
TO_DATE.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
78

Usando a função TO_CHAR e TO_DATE


com RR formato de data

SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-YYYY')


FROM employees
WHERE hire_date < TO_DATE('01-Jan-90','DD-Mon-RR');

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
79

Funções
Funções de uma única linha podem ser alinhadas em
qualquer nível.

F3(F2(F1(col,arg1),arg2),arg3)
Step 1 = Result 1
Step 2 = Result 2
Step 3 = Result 3

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
80

Funções

SELECT last_name,
UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8), '_US'))
FROM employees
WHERE department_id = 60;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
81

Usando a Função NVL

SELECT last_name, salary, NVL(commission_pct, 0),


(salary*12) + (salary*12*NVL(commission_pct, 0))
AN_SAL
FROM employees;
2

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
82

Usando a Função NVL2

SELECT last_name, salary, commission_pct,


NVL2(commission_pct,
'SAL+COMM', 'SAL') income
FROM employees WHERE department_id IN (50, 80);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
83

Usando a Função NULLIF

SELECT first_name, LENGTH(first_name) "expr1",


last_name, LENGTH(last_name) "expr2",
NULLIF(LENGTH(first_name), LENGTH(last_name)) result
FROM employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
84

Usando a Função COALESCE


SELECT last_name, employee_id,
COALESCE(TO_CHAR(commission_pct),TO_CHAR(manager_id),
'No commission and no manager')
FROM employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
85

Função CASE

Facilita consultas condicionais, fazendo o trabalho de um


IF-THEN-ELSE statement:

CASE expr WHEN comparison_expr1 THEN return_expr1


[WHEN comparison_expr2 THEN return_expr2
WHEN comparison_exprn THEN return_exprn
ELSE else_expr]
END

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
86

Usando a Função CASE

Facilita consultas condicionais, fazendo o trabalho de um


IF-THEN-ELSE statement:

SELECT last_name, job_id, salary,


CASE job_id WHEN 'IT_PROG' THEN 1.10*salary
WHEN 'ST_CLERK' THEN 1.15*salary
WHEN 'SA_REP' THEN 1.20*salary
ELSE salary END "REVISED_SALARY"
FROM employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
87

Função DECODE

Facilita consultas condicionais, fazendo o trabalho de uma


expressão IF-THEN-ELSE statement:
DECODE(col|expression, search1, result1
[, search2, result2,...,]
[, default])

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
88

Usando a Função DECODE

SELECT last_name, job_id, salary,


DECODE(job_id, 'IT_PROG', 1.10*salary,
'ST_CLERK', 1.15*salary,
'SA_REP', 1.20*salary,
salary)
REVISED_SALARY
FROM employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
89

Usando a Função DECODE

SELECT last_name, salary,


DECODE (TRUNC(salary/2000, 0),
0, 0.00,
1, 0.09,
2, 0.20,
3, 0.30,
4, 0.40,
5, 0.42,
6, 0.44,
0.45) TAX_RATE
FROM employees
WHERE department_id = 80;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
90

Relatórios com Dados Agregados


Usando as Funções de Grupo

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
91

Quais são Funções de Grupo?


As funções de grupo operam em conjuntos de linhas para dar
um resultado por grupo.

EMPLOYEES

Maximum salary in
EMPLOYEES table

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
92

Tipos de Funções de Grupo

• AVG
• COUNT
• MAX
• MIN Group
• STDDEV functions

• SUM
• VARIANCE

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
93

Função de Grupo: Syntax

SELECT group_function(column), ...


FROM table
[WHERE condition]
[ORDER BY column];

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
94

Usando as Funções AVG e SUM

SELECT AVG(salary), MAX(salary),


MIN(salary), SUM(salary)
FROM employees
WHERE job_id LIKE '%REP%';

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
95

Usando a Função MIN e MAX

Função Min – Menor Valor / Função Max – Maior Valor

SELECT MIN(hire_date), MAX(hire_date)


FROM employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
96

Usando a Função COUNT

COUNT(*) retorna o numero de Linhas da Tabela:


SELECT COUNT(*)
FROM employees 1
WHERE department_id = 50;

SELECT COUNT(commission_pct)
FROM employees
WHERE department_id = 80;
2

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
97

Usando o DISTINCT

COUNT(DISTINCT expr) Retorna o numero de linhas


eliminado as duplicidades.

SELECT COUNT(DISTINCT department_id)


FROM employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
98

Funções de Grupo e Valores Nulos

Função AVG:
SELECT AVG(commission_pct)
1 FROM employees;

Função AVG e NVL:

SELECT AVG(NVL(commission_pct, 0))


2 FROM employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
99

Criando Grupo de Dados

EMPLOYEES
Average salary in
EMPLOYEES table for
440
each department
950

350

640

10033

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
100

Criando Grupo de Dados:


Clausula Group by
SELECT column, group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
101

Usando a Clausula Group BY

Todas as colunas na lista SELECT que não estejam em


funções de grupo deve estar na cláusula GROUP BY.

SELECT department_id, AVG(salary)


FROM employees
GROUP BY department_id ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
102

Usando a Clausula GROUP BY


A coluna especificada no GROUP BY não precisa estar na
lista SELECT.
SELECT AVG(salary)
FROM employees
GROUP BY department_id ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
103

O agrupamento por mais de uma coluna

EMPLOYEES Add the salaries in the EMPLOYEES


table for each job, grouped by
department.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
104

Usando o Group by em Múltiplas colunas

SELECT department_id dept_id, job_id, SUM(salary)


FROM employees
GROUP BY department_id, job_id
ORDER BY department_id;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
105

Resultado Restrito no Grupo


EMPLOYEES

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
106

Usando a Clausula HAVING

SELECT department_id, MAX(salary)


FROM employees
GROUP BY department_id
HAVING MAX(salary)>10000 ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
107

Usando a Clausula HAVING

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);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
108

Usando GROUP BY

Mostrar a media do maior salario:

SELECT MAX(AVG(salary))
FROM employees
GROUP BY department_id;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
109

Exibindo Dados a partir de Varias


Tabelas

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
110

 Tipos de JOINS e syntax


• Natural join:
– Clausula USING
– Clausula ON
• Self-join
• Nonequijoins
• OUTER join:
– LEFT OUTER join
– RIGHT OUTER join
– FULL OUTER join
• Cartesian product
– Cross join

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
111

Obtendo dados de várias tabelas

EMPLOYEES DEPARTMENTS

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
112

Natural JOIN

SELECT department_id, department_name,


location_id, city
FROM departments
NATURAL JOIN locations ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
113

Junção pelo Nome das Colunas

Usando uma subconsulta pa

Primary key

Foreign key

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
114

Using
Especifica a coluna da Junção entres as tabelas

SELECT employee_id, last_name,


location_id, department_id
FROM employees JOIN departments
USING (department_id) ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
115

Clausula ON

SELECT e.employee_id, e.last_name, e.department_id,


d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
116

Aplicação de condições adicionais


na Junção
Use a cláusula AND ou a cláusula WHERE para aplicar
condições adicionais:
SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id)
AND e.manager_id = 149 ;

Or
SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id)
WHERE e.manager_id = 149 ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
117

Junção de Tabelas

EMPLOYEES (WORKER) EMPLOYEES (MANAGER)

… …

MANAGER_ID in the WORKER table is equal to


EMPLOYEE_ID in the MANAGER table.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
118

Self-Joins Usando Cláusula ON

SELECT worker.last_name emp, manager.last_name mgr


FROM employees worker JOIN employees manager
ON (worker.manager_id = manager.employee_id);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
119

Nonequijoins

EMPLOYEES JOB_GRADES

JOB_GRADES table defines the LOWEST_SAL and


HIGHEST_SAL range of values for each GRADE_LEVEL.
… Hence, the GRADE_LEVEL column can be used to assign
grades to each employee.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
120

LEFT OUTER JOIN

SELECT e.last_name, e.department_id, d.department_name


FROM employees e LEFT OUTER JOIN departments d
ON (e.department_id = d.department_id) ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
121

RIGHT OUTER JOIN

SELECT e.last_name, e.department_id, d.department_name


FROM employees e RIGHT OUTER JOIN departments d
ON (e.department_id = d.department_id) ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
122

FULL OUTER JOIN

SELECT e.last_name, d.department_id, d.department_name


FROM employees e FULL OUTER JOIN departments d
ON (e.department_id = d.department_id) ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
123

Gerenciando o Cartesian Product

EMPLOYEES (20 rows) DEPARTMENTS (8 rows)

Cartesian product:
20 x 8 = 160 rows

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
124

A cláusula CROSS JOIN produz o produto cruzado de duas


tabelas.

Usando uma subconsulta para resolver um


problema

SEL
ECT
las
t_n
ame
,
dep
art
men
t_n
ame
FRO
M
emp
loy
ees
CRO
SS
JOI
N
dep
Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP
art
São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 men
- Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323
ts
www.trainning.com.br - comercial@trainning.com.br
;
125

Usando subconsultas para


Resolver Consultas

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
126

Quem tem um salário maior que o de Abel?

Main query:

Which employees have salaries greater than Abel’s salary?

Subquery:

What is Abel’s salary?

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
127

Subquery Syntax

SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);

A subconsulta (consulta interna) é executado antes da


consulta principal (consulta externa).

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
128

Usando a Subquery

SELECT last_name, salary


FROM employees
WHERE salary >
(SELECT salary
FROM employees
WHERE last_name = 'Abel');

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
129

Tipos de Subqueries

• Single-row subquery
Main query

Subquery returns
ST_CLERK

• Multiple-row subquery
Main query

ST_CLERK
Subquery returns
SA_MAN

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
130

Subqueries de Linha Simples

• Retorno apenas uma linha


• Use operadores de comparação de uma única linha

Operator Meaning

=
Equal to

>
Greater than

>=
Greater than or equal to

<
Less than

<=
Less than or equal to

<>
Not equal to

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
131

Executando Subqueries de Linha Simples

SELECT last_name, job_id, salary


FROM employees
WHERE job_id =
(SELECT job_id
FROM employees
WHERE last_name = ‘Taylor’)
AND salary >
(SELECT salary
FROM employees
WHERE last_name = ‘Taylor’);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
132

Usando Funções de Grupo na Subquery

SELECT last_name, job_id, salary


FROM employees
WHERE salary =
(SELECT MIN(salary)
FROM employees);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
133

A Cláusula Having com Subqueries

O servidor Oracle executa as subqueries primeiro.


Os retornos do servidor Oracle resulta na TENDO
cláusula da consulta principal.
SELECT department_id, MIN(salary)
FROM employees
GROUP BY department_id
HAVING MIN(salary) >
(SELECT MIN(salary)
FROM employees
WHERE department_id = 50);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
134

O que está errado com essa afirmação?

SELECT employee_id, last_name


FROM employees
WHERE salary =
(SELECT MIN(salary)
FROM employees
GROUP BY department_id);

Single-row operator with


multiple-row subquery

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
135

Não há linhas retornadas pela consulta interna

SELECT last_name, job_id


FROM employees
WHERE job_id =
(SELECT job_id
FROM employees
WHERE last_name = 'Haas');

Subquery returns no rows because there is no employee named “Haas.”

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
136

Subqueries com Multiplas Linhas

• Retorno mais de uma linha


• Use operadores de comparação de múltiplas linhas

Operator Meaning

IN Equal to any member in the list

ANY Must be preceded by =, !=, >, <, <=, >=. Compares a value to each
value in a list or returned by a query. Evaluates to FALSE if the query
returns no rows.

ALL Must be preceded by =, !=, >, <, <=, >=. Compares a value to every
value in a list or returned by a query. Evaluates to TRUE if the query
returns no rows.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
137

Usando o operador ANY para Múltiplas linhas


na Subqueries

SELECT employee_id, last_name, job_id, salary


FROM employees
WHERE salary < ANY
(SELECT salary
FROM employees
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
138

Usando o operador ALL para Múltiplas linhas


na Subqueries

SELECT employee_id, last_name, job_id, salary


FROM employees
WHERE salary < ALL
(SELECT salary
FROM employees
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
139

Null Values in a Subquery

SELECT emp.last_name
FROM employees emp
WHERE emp.employee_id NOT IN
(SELECT mgr.manager_id
FROM employees mgr);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
140

Usando o conjunto de operadores

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
141

Operadores definidos
A B

Union

A B

Union All

A B

Interse Intersect

A B

Minus

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
142

UNION Operator

A B

O operador UNION retorna linhas de ambas as consultas depois de


eliminar duplicações.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
143

Usando o Operador UNION

Exibir cada empregado apenas uma vez

SELECT employee_id, job_id


FROM employees
UNION
SELECT employee_id, job_id
FROM job_history;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
144

UNION ALL Operator

A B

O operador UNION ALL retorna linhas das duas consultas, incluindo


todas as duplicações.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
145

Usando o Operador UNION ALL

Mostra os departments de todos os employees.


SELECT employee_id, job_id, department_id
FROM employees
UNION ALL
SELECT employee_id, job_id, department_id
FROM job_history
ORDER BY employee_id;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
146

INTERSECT Operator

A B

O operador de intersecção retorna linhas que são comuns às duas


consultas.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
147

Usando o Operador INTERSECT


SELECT employee_id, job_id
FROM employees
INTERSECT
SELECT employee_id, job_id
FROM job_history;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
148

MINUS Operator

A B

O operador MINUS retorna todas as linhas distintas selecionadas pela


primeira consulta, mas não está presente no segundo conjunto de
resultados da consulta.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
149

Usando o Operador MINUS

SELECT employee_id
FROM employees
MINUS
SELECT employee_id
FROM job_history;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
150

Manipulando Dados

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
151

Lição

• A adição de novas linhas em uma tabela


- Instrução INSERT
• Alterar dados em uma tabela
- UPDATE
• Remoção de linhas de uma tabela:
- DELETE
- Instrução TRUNCATE
• Controle de transações de banco de dados usando
COMMIT,ROLLBACK e SAVEPOINT
• Cláusula FOR UPDATE em uma instrução
SELECT

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
152

Adicinando novas linhas na Tabela


New
row
DEPARTMENTS

Insert new row


into the
DEPARTMENTS table.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
153

INSERT Statement Syntax


• Adiciona novas linhas na tabela usando o comando
INSERT statement:
INSERT INTO table [(column [, column...])]
VALUES (value [, value...]);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
154

Inserindo novas Linhas

INSERT INTO departments(department_id,


department_name, manager_id, location_id)
VALUES (70, 'Public Relations', 100, 1700);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
155

Inserindo linhas com o Valor Null

Método Implicit: Omita a coluna da lista de coluna.

INSERT INTO departments (department_id,


department_name)
VALUES (30, 'Purchasing');

Método Explicit : Especifica o Valor NULL na Cláusula


Values.
INSERT INTO departments
VALUES (100, 'Finance', NULL, NULL);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
156

Inserindo Valores Especiais

A função SYSDATE registra a data e a hora atual.


INSERT INTO employees (employee_id,
first_name, last_name,
email, phone_number,
hire_date, job_id, salary,
commission_pct, manager_id,
department_id)
VALUES (113,
'Louis', 'Popp',
'LPOPP', '515.124.4567',
SYSDATE, 'AC_ACCOUNT', 6900,
NULL, 205, 110);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
157

Criando Script
INSERT INTO departments
(department_id, department_name, location_id)
VALUES (&department_id, '&department_name',&location);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
158

Copiando Linha para Tabela

INSERT INTO sales_reps(id, name, salary, commission_pct)


SELECT employee_id, last_name, salary, commission_pct
FROM employees
WHERE job_id LIKE '%REP%';

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
159

Alterar dados em uma tabela

EMPLOYEES

Update rows in the EMPLOYEES table:

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
160

UPDATE Statement Syntax

Modifique os valores existentes em uma tabela com a


instrução UPDATE:
UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
161

Atualizando a linha da Tabela


Os valores de uma ou mais linhas específicas são modificadas
se você especificar a cláusula WHERE:

UPDATE employees
SET department_id = 50
WHERE employee_id = 113;

Os valores para todas as linhas da tabela são modificados


se omitir a cláusula WHERE:

UPDATE copy_emp
SET department_id = 110;

Especifique SET column_name = NULL para atualizar uma coluna


valor para NULL.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
162

Atualizando Duas Colunas com Subquery

UPDATE employees
SET job_id = (SELECT job_id
FROM employees
WHERE employee_id = 205),
salary = (SELECT salary
FROM employees
WHERE employee_id = 205)
WHERE employee_id = 113;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
163

Removendo linhas da Tabela

DEPARTMENTS

Delete a row from the DEPARTMENTS table:

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
164

DELETE Statement

Você pode remover linhas existentes de uma tabela


utilizando a instrução DELETE:
DELETE [FROM] table
[WHERE condition];

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
165

Deletando linhas da Tabela


• Linhas específicas serão excluídas se você
especificar a cláusula WHERE:
DELETE FROM departments
WHERE department_name = ‘Finance';

• Todas as linhas da tabela serão excluídas se você


omitir a cláusula WHERE:
DELETE FROM copy_emp;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
166

Deletando linha da Tabela

DELETE FROM employees


WHERE department_id =
(SELECT department_id
FROM departments
WHERE department_name
LIKE '%Public%');

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
167

TRUNCATE Statement

• Remove todas as linhas de uma tabela, deixando a tabela


vazia e a estrutura da tabela intacta

Syntax:
TRUNCATE TABLE table_name;

• Exemplo:
TRUNCATE TABLE copy_emp;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
168

Demonstrações de controle de transação


explícita
Time COMMIT

Transaction

DELETE

SAVEPOINT A

INSERT

UPDATE

SAVEPOINT B

INSERT
ROLLBACK ROLLBACK ROLLBACK
to SAVEPOINT B to SAVEPOINT A

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
169

Alterações de volta a um marcador de


Rolamentos
• Crie um marcador na transação atual usando a
instrução SAVEPOINT.
• Reverter a esse marcador usando a instrução
ROLLBACK TO SAVEPOINT.

UPDATE...
SAVEPOINT update_done;

INSERT...
ROLLBACK TO update_done;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
170

Committing Data

• Faça as alterações:
• Commit
DELETE FROMthe changes:
employees
WHERE employee_id = 99999;

INSERT INTO departments


VALUES (290, 'Corporate Tax', NULL, 1700);

COMMIT;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
171

FOR UPDATE Cláusula no SELECT Statement

Bloqueia as linhas da EMPLOYEES Tabela na Cláusula


Where job_id is SA_REP.
SELECT employee_id, salary, commission_pct, job_id
FROM employees
WHERE job_id = 'SA_REP'
FOR UPDATE
ORDER BY employee_id;

• Bloqueio é liberada somente quando você emite um


ROLLBACK ou COMMIT.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
172

Resumo

Function Description

INSERT Adds a new row to the table


UPDATE Modifies existing rows in the table
DELETE Removes existing rows from the table
TRUNCATE Removes all rows from a table

COMMIT Makes all pending changes permanent


SAVEPOINT Is used to roll back to the savepoint marker
ROLLBACK Discards all pending data changes
FOR UPDATE clause Locks rows identified by the SELECT query
in SELECT

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
173

Usando Instruções DDL para


Criar e Gerenciar Tabelas

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
174

Lição

• Objetos de Banco de dados


- Regras de Nomenclatura
• CREATE TABLE:
- Acesso tabelas de outro usuário
- Opção DEFAULT
• Os tipos de dados
• Visão geral de restrições: não nulo, chave primária,
chave estrangeira constrangimentos
• Criar uma tabela utilizando uma subconsulta
• ALTER TABLE
- Tabelas somente leitura
• instrução DROP TABLE

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
175

Objetos Banco de Dados

Object Description

Table Basic unit of storage; composed of rows


View Logically represents subsets of data from one or
more tables
Sequence Generates numeric values
Index Improves the performance of some queries

Synonym Gives alternative name to an object

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
176

CREATE TABLE Statement

• Voce deve ter:


– CREATE TABLE privilegio.

CREATE TABLE [schema.]table


(column datatype [DEFAULT expr][, ...]);

• Voce especifica:
– Nome Tabela
– Nome Coluna e Tipos de Dados

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
177

Fazendo referência a tabelas de outro usuário

Tabelas pertencentes a outros usuários não estão no


esquema do usuário.
Você deve usar o nome do proprietário como um prefixo
para as tabelas.

USERA USERB
SELECT * SELECT *
FROM userB.employees; FROM userA.employees;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
178

Opção DEFAULT
Especifique um valor padrão para a coluna durante
uma inserção.

... hire_date DATE DEFAULT SYSDATE, ...

CREATE TABLE hire_dates


(id NUMBER(8),
hire_date DATE DEFAULT SYSDATE);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
179

Criando Tabelas

• Criando Tabelas:
• TABLE dept
CREATE
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13),
create_date DATE DEFAULT SYSDATE);

• Verificando o Dicionário de Dados da Tabela:


DESCRIBE dept

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
180

Tipos de Dados

Data Type Description

VARCHAR2(size) Variable-length character data


CHAR(size) Fixed-length character data
NUMBER(p,s) Variable-length numeric data
DATE Date and time values
LONG Variable-length character data (up to 2 GB)
CLOB Character data (up to 4 GB)
RAW and LONG Raw binary data
RAW
BLOB Binary data (up to 4 GB)
BFILE Binary data stored in an external file (up to 4 GB)
ROWID A base-64 number system representing the unique
address of a row in its table

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
181

Tipos de Dados Datetime

Você pode usar vários tipos de dados de data e hora:

Data Type Description

TIMESTAMP Date with fractional seconds


INTERVAL YEAR TO Stored as an interval of years
MONTH and months
INTERVAL DAY TO Stored as an interval of days, hours, minutes,
SECOND and seconds

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
182

Incluindo a Constraints

• Restrições de impor regras ao nível da tabela.


• Restrições de evitar a exclusão de um quadro se
são dependências.
• Os seguintes tipos de restrição são válidos:
– NOT NULL
– UNIQUE
– PRIMARY KEY
– FOREIGN KEY
– CHECK

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
183

Definindo a Constraints

• Syntax:
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint][,...]);

• Column-level constraint syntax:


column [CONSTRAINT constraint_name] constraint_type,

• Table-level constraint syntax:


column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
184

Definindo a Constraints

Exemplo de uma restrição em nível de coluna:


CREATE TABLE employees(
employee_id NUMBER(6)
CONSTRAINT emp_emp_id_pk PRIMARY KEY,
first_name
...);
VARCHAR2(20),
1

Exemplo de uma restrição de nível de tabela:


CREATE TABLE employees(
employee_id NUMBER(6),
first_name VARCHAR2(20),
...
job_id VARCHAR2(10) NOT NULL,
CONSTRAINT emp_emp_id_pk
PRIMARY KEY (EMPLOYEE_ID)); 2

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
185

NOT NULL Constraint


Garante que os valores nulos não são permitidos para a
coluna:


NOT NULL constraint Absence of NOT NULL
(Primary Key enforces NOT NULL constraint (Any row can
NOT NULL constraint.) constraint contain a null value for
this column.)

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
186

UNIQUE Constraint

UNIQUE constraint
EMPLOYEES


INSERT INTO
Allowed

Not allowed: already


exists

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
187

UNIQUE Constraint

Definida no nível da tabela ou o nível de coluna:

CREATE TABLE employees(


employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
hire_date DATE NOT NULL,
...
CONSTRAINT emp_email_uk UNIQUE(email));

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
188

PRIMARY KEY Constraint

PRIMARY KEY
DEPARTMENTS

Not allowed INSERT INTO


(null value)

Not allowed
(50 already exists)

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
189

FOREIGN KEY Constraint


DEPARTMENTS
PRIMARY
KEY


EMPLOYEES
FOREIGN
KEY


INSERT INTO Not allowed
(9 does not exist)

Allowed

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
190

FOREIGN KEY Constraint

Definida no nível da tabela ou o nível de coluna:

CREATE TABLE employees(


employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
hire_date DATE NOT NULL,
...
department_id NUMBER(4),
CONSTRAINT emp_dept_fk FOREIGN KEY
(department_id)
REFERENCES departments(department_id),

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
191

CHECK Constraint

• Define uma condição que cada linha deve satisfazer


• As expressões a seguir não são permitidos:
– References to CURRVAL, NEXTVAL, LEVEL, and
ROWNUM pseudocolumns
– Calls to SYSDATE, UID, USER, and USERENV
functions
– Queries that refer to other values in other rows

..., salary NUMBER(2)


CONSTRAINT emp_salary_min
CHECK (salary > 0),...

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
192

CREATE TABLE: Exemplo


CREATE TABLE employees
( employee_id NUMBER(6)
CONSTRAINT emp_employee_id PRIMARY KEY
, first_name VARCHAR2(20)
, last_name VARCHAR2(25)
CONSTRAINT emp_last_name_nn NOT NULL
, email VARCHAR2(25)
CONSTRAINT emp_email_nn NOT NULL
CONSTRAINT emp_email_uk UNIQUE
, phone_number VARCHAR2(20)
, hire_date DATE
CONSTRAINT emp_hire_date_nn NOT NULL
, job_id VARCHAR2(10)
CONSTRAINT emp_job_nn NOT NULL
, salary NUMBER(8,2)
CONSTRAINT emp_salary_ck CHECK
(salary>0)
, commission_pct NUMBER(2,2)
, manager_id NUMBER(6)
CONSTRAINT emp_manager_fk REFERENCES
employees (employee_id)
, department_id NUMBER(4)
CONSTRAINT emp_dept_fk REFERENCES
departments (department_id));

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
193

Violação de Constraints

UPDATE employees
SET department_id = 55
WHERE department_id = 110;

Department 55 does not exist.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
194

Violação de Constraints

Você não pode excluir uma linha que contém uma chave
primária que é usada como uma chave estrangeira em outra
tabela.
DELETE FROM departments
WHERE department_id = 60;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
195

Criando tabela usando SubConsulta

• Criando tabela inserindo os dados na SubConsulta:


Syntax
CREATE TABLE table
[(column, column...)]
AS subquery;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
196

Criando tabela usando SubConsulta

CREATE TABLE dept80


AS
SELECT employee_id, last_name,
salary*12 ANNSAL,
hire_date
FROM employees
WHERE department_id = 80;

DESCRIBE dept80

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
197

ALTER TABLE

Use o ALTER TABLE:


• Adicionar nova Coluna
• Modificar o tipo de Dados da coluna existente
• Definir valor padrao na nova Coluna
• Apagar Coluna
• Renomear Coluna

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
198

Tabelas Somente leitura

Use o Alter Table para colocar a tabela em somente leitura


ou leitura e escrita:

ALTER TABLE employees READ ONLY;


-- perform table maintenance and then
-- return table back to read/write mode
ALTER TABLE employees READ WRITE;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
199

Apagando Tabela

• Movendo a tabela para a área de Recyclebin.

DROP TABLE dept80;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
200

Criação de objetos de SCHEMA

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
201

Lição

• Visão geral de pontos de vista:


– Criar, modificar e recuperar dados a partir de
uma visão
– Operações DML em uma View
– Soltando uma visão
• Visão geral das sequências:
– Criação, utilização e modificação de uma
seqüência
– Valores de seqüência de cache
– NEXTVAL e pseudocolunas CURRVAL
• Visão geral de índices
– Criação, índices caindo
• Visão geral de sinônimos
– Criação, caindo sinônimos

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
202

Usando com cláusula WITH CHECK OPTION

• Você pode garantir que as operações DML executadas na


visão estadia no domínio da visão, utilizando o CHECK OPTION:

CREATE OR REPLACE VIEW empvu20


AS SELECT *
FROM employees
WHERE department_id = 20
WITH CHECK OPTION CONSTRAINT empvu20_ck ;

• Qualquer tentativa de inserir uma linha com um


department_id diferente de 20, ou para atualizar o número
do departamento para qualquer linha no ponto de vista não
porque viola a restrição OPÇÃO CHECK.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
203

Negando Operações DML

CREATE OR REPLACE VIEW empvu10


(employee_number, employee_name, job_title)
AS SELECT employee_id, last_name, job_id
FROM employees
WHERE department_id = 10
WITH READ ONLY ;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
204

Removendo a View

Você pode remover uma VISÃO sem perder dados porque a VISÃO
é com base nas tabelas subjacentes no banco de dados.
DROP VIEW view;

DROP VIEW empvu80;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
205

Criando Sequence

• Criar uma seqüência nomeada DEPT_DEPTID_SEQ a ser


utilizado para a chave primária da tabela DEPARTAMENTS.
• Não use a opção CICLO.
CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE
NOCYCLE;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
206

NEXTVAL e CURRVAL Pseudocoluna

NEXTVAL retorna o próximo valor de seqüência disponível.


Ele retorna um valor único de cada vez que é referenciado,
mesmo para diferentes usuários.

CURRVAL obtém o valor de seqüência atual.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
207

Usando a Sequence

• Introduza um novo departamento chamado "Support"


no location_id 2500:
INSERT INTO departments(department_id,
department_name, location_id)
VALUES (dept_deptid_seq.NEXTVAL,
'Support', 2500);

• Visualize o valor atual para o DEPT_DEPTID_SEQ


sequence:
SELECT dept_deptid_seq.CURRVAL
FROM dual;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
208

Modificando Sequence
Mude o valor do incremento, valor máximo, valor mínimo,
opção de ciclo, ou opção de cache:

ALTER SEQUENCE dept_deptid_seq


INCREMENT BY 20
MAXVALUE 999999
NOCACHE
NOCYCLE;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
209

Indexes

Object Description

Table Basic unit of storage; composed of rows

View Logically represents subsets of data from one or more tables

Sequence Generates numeric values

Index Improves the performance of some queries

Synonym Gives alternative names to objects

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
210

Indexes

Index:
• É um objeto de esquema
• Pode ser utilizada pelo servidor Oracle para acelerar a
recuperação de linhas usando um ponteiro
• Pode reduzir (I / O), utilizando um método de acesso
via rápida para localizar dados rapidamente
• É independente da tabela que ele indexa
• É usado e mantido automaticamente pelo servidor
Oracle

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
211

Como são criados indices?

Automaticamente: Um índice único é criado automaticamente


quando você definir uma chave primária ou restrição UNIQUE
em uma definição de tabela.

Manualmente: Os usuários podem criar índices não exclusivos


em colunas para acelerar o acesso às linhas.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
212

Criando Index

• Criar um índice em uma ou mais colunas:


CREATE [UNIQUE][BITMAP]INDEX index
ON table (column[, column]...);

• Melhorar a velocidade de acesso de consulta à coluna


LAST_NAME na tabela EMPLOYEES:
CREATE INDEX emp_last_name_idx
ON employees(last_name);

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
213

Orientação para Criação de Index

Create an index when:

A column contains a wide range of values


A column contains a large number of null values
One or more columns are frequently used together in a WHERE
clause or a join condition
The table is large and most queries are expected to retrieve less
than 2% to 4% of the rows in the table
Do not create an index when:

The columns are not often used as a condition in the query


The table is small or most queries are expected to retrieve more than
2% to 4% of the rows in the table
The table is updated frequently
The indexed columns are referenced as part of an expression

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
214

Removendo Index

Removendo o Index usando o comando DROP INDEX:

DROP INDEX index;

Removendo o Index emp_last_name_idx:

DROP INDEX emp_last_name_idx;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
215

Synonyms

Object Description

Table Basic unit of storage; composed of rows

View Logically represents subsets of data from one or more tables

Sequence Generates numeric values

Index Improves the performance of some queries

Synonym Gives alternative names to objects

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
216

Criando um sinônimo para um objeto

Simplificar o acesso a objetos através da criação de um


sinônimo (outro nome para um objeto). Com sinônimos, você
pode:
• Criar uma referência mais fácil de uma tabela que é
de propriedade de outro usuário
• Encurtar nomes de objetos longos

CREATE [PUBLIC] SYNONYM synonym


FOR object;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
217

Criando e Removando SYNONYM

• Crie um nome abreviado para o DEPT_SUM_VU view:


CREATE SYNONYM d_sum
FOR dept_sum_vu;

• Drop a synonym:
DROP SYNONYM d_sum;

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
218

Usando SQL*Plus

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
219

SQL e SQL*Plus

SQL statements

Server

SQL*Plus

Query results

Buffer

SQL
scripts

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
220

Login SQL*Plus

sqlplus [username[/password[@database]]]

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
221

Alterando as configurações de SQL*Plus.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
222

SERVEROUTPUT Comando
Use o SET SERVEROUT [PUT] comando para controle
se deseja exibir a saída de procedimentos armazenados
ou blocos PL / SQL no SQL * Plus.
O limite de comprimento da linha DBMS_OUTPUT é
aumentado de 255 bytes para 32,767 bytes.
O tamanho padrão é agora ilimitado.
Recursos não são pré-alocados quando SERVEROUTPUT
está definido.
Porque não há nenhuma penalidade de desempenho,
uso ilimitado, a menos que você quiser conservar a
memória física.

SET SERVEROUT[PUT] {ON | OFF} [SIZE {n | UNL[IMITED]}]


[FOR[MAT] {WRA[PPED] | WOR[D_WRAPPED] |
TRU[NCATED]}]

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
223

Usando o SQL*Plus SPOOL Comando


SPO[OL] [file_name[.ext] [CRE[ATE] | REP[LACE] | APP[END]] |
OFF | OUT]

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
224

Executando instruções DML e DDL


Operações com o GUI SQL Developer

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
225

Objetivos

Depois de concluir este apêndice, você deve ser capaz de


fazer o seguinte:
• Executar operações de linguagem de definição de
dados (DDL), utilizando as opções do menu SQL
Developer
• Realizar linguagem de manipulação de dados (DML)
operações usando as opções do menu SQL
Developer

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
226

Objetos de Banco de Dados de Navegação


• Criar um objeto de conexão de banco de dados.
• Use o Navegador Conexões para:
Navegue através de vários objetos em um esquema de
banco de dados.
Reveja as definições de objetos.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
227

Criando o Objeto Schema

• SQL Developer apoia a criação de qualquer esquema


objeto usando o menu de contexto.
• Editar os objetos usando um diálogo de edição ou um
dos muitos menus sensíveis ao contexto.
• Ver o DDL para ajustes como a criação de um novo
objeto ou editar um objeto de esquema existente.

Expand Connections. Right-click


Tables and select New Table.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
228

Criando Nova Tabela: Exemplo

Select the Advanced


check box to get all
the options for
defining tables.

Click + to add
column. Click x to
remove column.
Specify the column name,
data type, DEFAULT value,
and NULL constraint here.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
229

Definindo Constraints

From the Primary Key, Unique


Constraints, Foreign Keys, and Check
Constraints, select the appropriate
option to define a constraint on your
table.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
230

Modificando a Tabela
1 2

3 4

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
231

Criando Sequence

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
232

Definição de Preferência

• Personalizar a interface SQL Developer.

Trainning Education Services ® - Sede: Av. Paulista, 2006, 16° andar – SP

São Paulo (11) 3171-2002 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323

www.trainning.com.br - comercial@trainning.com.br
AVALIAÇÃO FINAL DE TREINAMENTO
---- DESTACAR ESTA FOLHA E ENTREGAR AO INSTRUTOR ----

Data:

NOME:
CURSO:

INSTRUTOR:

AVALIAÇÃO FINAL DE TREINAMENTO

Marque com um X na lacuna ao lado da figura na opção desejada.


Conteúdo Programático do Curso   ☺
Tempo de Realização do Curso   ☺
Referência Final ao Treinamento   ☺
Material Didático   ☺
Didática Instrutor   ☺
Conhecimento Técnico do Instrutor   ☺
Instalações Físicas (Mesa, Cadeira, Quadro, Projetor, Computador)   ☺
Atendimento Comercial e Administrativo   ☺
Conteúdo, Material Adicional e Informações no site da Trainning   ☺

COMENTÁRIOS
Espaço livre para comentários, críticas e sugestões sobre o treinamento realizado.

INDICAÇÕES
Indique 1 amigo e Ganhe Desconto no próximo treinamento.

 REGULAR

 SATISFATÓRIO

☺ ÓTIMO

Trainning Education Services ® - Sede: Av. Paulista, 777, 15° andar – SP


São Paulo (11) 3323-1676 - Rio de Janeiro (21) 4063-6518 - Brasília (61) 4063-7766 - Belo Horizonte (31) 4063-8187
Vitória (27) 4062-9192 - Curitiba (41) 4063-8083 - Porto Alegre (51) 4063-9474 - Recife (81) 3301-1600 - Salvador (71) 4062-9323
www.trainning.com.br - comercial@trainning.com.br

Você também pode gostar