bacs 485—database management advanced sql overview advanced ddl, dml, and dcl commands

37
BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

Upload: larry-lodes

Post on 14-Dec-2015

241 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Advanced SQL

Overview Advanced DDL, DML, and DCL Commands

Page 2: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Lecture Objectives Review basic DDL, DML, and DCL SQL

commands used in Oracle Learn advanced SQL commands useful

for DBA’s and database programmers

Page 3: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Oracle SQL DDL

Basic Object Manipulation Set Create Table (Alter, Drop) Create View (Alter, Drop) Create Index (Alter, Drop) Create Sequence (Alter, Drop)

Page 4: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Create Table CommandsCREATE TABLE name (col-name type [(size)][CONSTRAINT],...);

 CONSTRAINT name {PRIMARY KEY | UNIQUE | REFERENCES foreign_table

[(foreignfield)] }

Basic Create Table:

CREATE TABLE STUDENT(STUID CHAR (5) PRIMARY KEY, SSN CHAR (9), LNAME VARCHAR2 (25), FNAME VARCHAR2 (15), MAJOR VARCHAR2 (7), CREDITS NUMBER (1));

Page 5: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Create Table CommandsCREATE TABLE scott.emp

(empno NUMBER CONSTRAINT pk_emp PRIMARY KEY, ename VARCHAR2(10) CONSTRAINT nn_ename NOT NULL

CONSTRAINT upper_ename CHECK (ename = UPPER(ename)),job VARCHAR2(9),mgr NUMBER CONSTRAINT fk_mgr REFERENCES scott.emp(empno) on delete cascade,hiredate DATE DEFAULT SYSDATE,sal NUMBER(10,2) CONSTRAINT ck_sal CHECK (sal > 500),comm NUMBER(9,0) DEFAULT NULL,deptno NUMBER(2) CONSTRAINT nn_deptno NOT NULL CONSTRAINT fk_deptno REFERENCES scott.dept(deptno));

Page 6: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Alter Table CommandsALTER TABLE emp

ADD (CONSTRAINT sal_com_cc CHECK (sal + comm <= 5000))DISABLE CONSTRAINT sal_com_cc;

ALTER TABLE EMP DROP (SSN) CASCADE CONSTRAINTS;

ALTER TABLE dept ADD CONSTRAINT manager_fk FOREIGN KEY (manager) REFERENCES emp (mgr);

ALTER TABLE empADD (thriftplan NUMBER(7,2),

loancode CHAR(1) NOT NULL);

Page 7: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Create View CommandsCREATE VIEW dept20 AS

SELECT ename, sal*12 annual_salaryFROM empWHERE deptno = 20;

CREATE VIEW clerk (id_number, person, department, position) ASSELECT empno, ename, deptno, job

FROM empWHERE job = ’CLERK’WITH READ ONLY;

ALTER VIEW customer_view COMPILE;

DROP VIEW dept20;

Page 8: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Index CommandsCREATE INDEX emp_idx ON scott.emp (ename);

CREATE INDEX emp_i ON emp (UPPER(ename));

ALTER INDEX emp_ix REBUILD REVERSE;

DROP INDEX monolith;

Page 9: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Sequence CommandCREATE SEQUENCE seq1 INCREMENT BY 10;

CREATE SEQUENCE acct_seqINCREMENT BY 10 START WITH 100 NOMAXVALUENOCYCLE CACHE 10;

ALTER SEQUENCE seq1MAXVALUE 1500;

DROP SEQUENCE elly.seq1;

Page 10: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Oracle SQL DML

Select Insert Update Delete

Page 11: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Select CommandsSELECT {field-list | * | DISTINCT field}

FROM table-listWHERE expressionGROUP BY group-fields

HAVING group-expressionORDER BY field-list;

Basic Select Example:

Select * From EmpWhere Salary > 45000 and Status = “Full Time”

Order By SSN;

Page 12: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

More Complex SelectsSELECT deptno, MIN(sal), MAX (sal)

FROM empWHERE job = 'CLERK'GROUP BY deptno

HAVING MIN(sal) < 1000;

Would print:

DEPTNO MIN(SAL) MAX(SAL)---------- ---------- ----------20 800 110030 950 950

Page 13: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

SQL Aggregate Functions AVG Average of non-null values

NUMBER  COU[NT]  Count of non-null values

All types  MIN[IMUM]  Minimum value

NUMBER, CHAR, NCHAR, VARCHAR2 (VARCHAR), NVARCHAR2 (NCHAR VARYING) 

MAX[IMUM] Maximum value NUMBER, CHAR, NCHAR, VARCHAR2 (VARCHAR), NVARCHAR2 (NCHAR

VARYING)  NUM[BER] Count of rows

All types  SUM Sum of non-null values

NUMBER  STD Standard deviation of non-null values

NUMBER  VAR[IANCE] Variance of non-null values

NUMBER 

Page 14: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Other Select Operators Logical Operators

And Or Not

Comparison Operator =,<>,<,<=,>,>= IS NULL BETWEEN…AND IN LIKE

Page 15: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Multi-Table Joins Data from 2 or more tables can be

combined into a single select by several methods. Use ‘where’ clause to combine all

data Use Suq-query

Equi-join Non-Equi-join Outer Join Self-Join

Page 16: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Select Sub-Query Sub-queries allow a component of a simple select to be an

embedded select statement.

SELECT Ename, sal FROM emp WHERE deptno = (SELECT deptno FROM dept WHERE dname = 'ACCOUNTING');

Page 17: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Sub-query operators The following operators can be

used to select one or more tuples in a sub-query. Single row queries

=, <>, >,>=,<,<= Multiple row queries

IN – equal to any values in a list ALL – compare to all values in list ANY – compare to each value in list

Page 18: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Single Row Sub-QuerySELECT deptno, UPPER(ename), sal

FROM emp xWHERE sal >

(SELECT AVG(sal)FROM empWHERE x.deptno = deptno)

ORDER BY deptno;

Page 19: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Multiple Row Query Operators >ALL means more than the maximum value in list <ALL means less than the minimum value in list >ANY means less than the maximum value in list <ANY means more than the minimum value in list

Note, from the diagram below, it is obvious that overlap is possible. The key to understanding is to remember that these operators are used to determine how a specific value relates to a list. Different operators would produce different relations.

10 20

>Any

<Any > All

< All530

14

18

Page 20: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Multiple Row Sub-queriesSELECT SSN, Lname FROM student WHERE FacID IN

(SELECT FacID FROM faculty WHERE deptID = 1);

SELECT empno, lname, fname, salaryFROM employeeWHERE salary >ANY

(SELECT salary FROM employee WHERE posID = 2)AND posID <> 2;

SELECT empno, lname, fname, salaryFROM employeeWHERE salary <ALL

(SELECT AVG(salary) FROM employee GROUP BY deptID);

Page 21: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Character Functions Upper (col) – changes all to uppercase

Lower (col) – changes all to lowercase

Initcap (col) – first character of each word uppercase

Concat (col1,col2) – joins 1st value to 2nd value

Substr (col, x, y) – returns substring starting at ‘x’ for ‘y’ characters

Instr (col, c) – returns position of 1st ‘c’ character

Trim(‘c’ FROM col) – removes ‘c’ leading and trailing characters

Length (col) – returns length

Lpad(col,n,str) – pads value with ‘str’ to the left to total width of ‘n’

Page 22: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Date Manipulation Months_Between (date1,date2) – Number months

between 2 dates Add_Months (date, m) – Add calendar months to a date

Next_Day (date, ‘day’) – Find next day after a date

Last_Day (date) – Find last day of the month

Round (date) – Round to nearest day, month, or year

Trunc (date) – Truncate date to nearest day, month, or year

Date + number – Add days to a date

Date – number – Subtract days from a date

Date + number/24 – Add hours to a date

Date1 – Date 2 – Find number of days between 2 dates

Page 23: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Math Manipulation Round (col, n) – Round column to n decimal

places

Trunc (col, n) – Truncate the column to n decimal places

Power (n,p) – returns np

Abs (n) – Absolute value of n

Mod (x,y) – integer remainder of x/y

+, -, *, / - perform basic mathematical operations

Page 24: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Complex Select Sub-QueriesSELECT a.deptno "Department",

a.num_emp/b.total_count "%Employees", a.sal_sum/b.total_sal "%Salary"FROM (SELECT deptno, COUNT(*) num_emp, SUM(SAL) sal_sum

FROM scott.empGROUP BY deptno) a,

(SELECT COUNT(*) total_count, SUM(sal) total_salFROM scott.emp) b ;

Page 25: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Complex Select Sub-QueriesSELECT Tablespace_Name, Max_Blocks, Block_Count, Total_Blocks_Free, ((Total_Blocks_Free/Total_Allocated_Blocks)*100) AS Pct_Free

FROM (SELECT Tablespace_Name, SUM(Blocks) Total_Allocated_Blocks

FROM DBA_DATA_FILES GROUP BY Tablespace_Name), (SELECT Tablespace_Name Free_Space, MAX(Blocks) AS Max_Blocks,

COUNT(Blocks) AS Count_Blocks, SUM(Blocks) AS Total_Free_Blocks FROM DBA_FREE_SPACE GROUP BY Tablespace_Name)WHERE Tablespace_Name = Free_Space;

Page 26: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Complex Select Sub-QueriesFind the top 2 salaries in each department:

SELECT m.ename, m.sal, m.deptnoFROM emp mWHERE m.sal >=

(SELECT DISTINCT o.sal FROM emp 0 WHERE (o.sal, 2) IN (SELECT i.sal, ROWNUM

FROM (SELECT DSTINCT i2.sal r_sal,i2.deptno, i2.sal, i2.ROWIDFROM emp i2) IWHERE I.deptno = m.deptno))

ORDER BY deptno, sal DESC;

ENAME SAL DEPTNO----- --- -----KING 5000 10CLARK 2450 10SCOTT 3000 20FORD 3000 20BLAKE 2850 30

Page 27: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Complex Select Sub-QueriesFind top 3 travel agents based on tickets sold:

SELECT id, ticket_price, agent_rankFROM (SELECT agent_id AS id,

SUM(ticket_price) AS ticket_price,RANK() OVER (ORDER BY SUM (ticket_price) DESC) AS agent_rank

FROM invoice GROUP BY agent_id)

WHERE agent_rank < 4;

ID Ticket_Price Agent_rank-- ------------ ----------1234 8141 15675 6708 24434 5140 3

Page 28: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Select Self-JoinSELECT e1.ename || ‘ works for ’ || e2.ename

"Employees and their Managers"FROM emp e1, emp e2 WHERE e1.mgr = e2.empno;

Would Print:

Employees and their Managers-------------------------------BLAKE works for KINGCLARK works for KINGJONES works for KINGFORD works for JONESSMITH works for FORDALLEN works for BLAKEWARD works for BLAKE

Page 29: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Select Outer JoinSELECT ename, job, dept.deptno, dname

FROM emp, deptWHERE emp.deptno (+) = dept.deptno;

SELECT custname, TO_CHAR(orderdate, ’MON-DD-YYYY’) "ORDERDATE", partno, quantity

FROM customers, orders, lineitemsWHERE customers.custno = orders.custno (+)

AND orders.orderno = lineitems.orderno (+);

Page 30: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Decode StatementSELECT ename, deptno,

DECODE (deptno, 10, ‘ACCOUNTING’,20, ‘RESEARCH’,30, ‘SALES’,‘NOT INDICATED’)

FROM emp;

ENAME DEPTNO DECODE(DEPTNO----- ------ -------------TURNER 30 SALESALLEN 20 RESEARCHJONES 10 ACCOUNTINGWARD 20 RESEARCH

Page 31: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Insert CommandsINSERT INTO deptVALUES (50, ’PRODUCTION’, ’SAN FRANCISCO’);

INSERT INTO emp (empno, ename, job, sal, comm, deptno)VALUES (7890, ’JINKS’, ’CLERK’, 1.2E3, NULL, 40);

INSERT INTO (SELECT ename, deptno FROM emp WHERE deptno < 10)VALUES (’Taylor’, 20);

INSERT INTO bonusSELECT ename, job, sal, comm

FROM empWHERE comm > 0.25 * sal

OR job IN (’PRESIDENT’, ’MANAGER’);

INSERT INTO emp VALUES (empseq.nextval, ’LEWIS’, ’CLERK’,7902, SYSDATE, 1200, NULL, 20);

Page 32: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Update CommandsUPDATE emp

SET comm = NULL WHERE job = ’TRAINEE’;

UPDATE empSET job = ’MANAGER’, sal = sal + 1000, deptno = 20

WHERE ename = ’JONES’;

UPDATE empSET sal = sal * 1.1 WHERE empno NOT IN

(SELECT empno FROM bonus);

Page 33: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Complex Update CommandUPDATE emp a

SET deptno = (SELECT deptno

FROM dept WHERE loc = ’BOSTON’),(sal, comm) = (SELECT 1.1*AVG(sal), 1.5*AVG(comm)

FROM emp bWHERE a.deptno = b.deptno)

WHERE deptno IN(SELECT deptno FROM dept WHERE loc = ’DALLAS’ OR loc = ’DETROIT’);

Page 34: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Delete CommandDELETE FROM temp_assign;

DELETE FROM empWHERE JOB = ’SALESMAN’

AND COMM < 100;

DELETE FROM (select * from emp)WHERE JOB = ’SALESMAN’

AND COMM < 100;

Page 35: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

Oracle SQL DCL

Commit Rollback

Page 36: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

CommitINSERT INTO dept VALUES (50, ’MARKETING’, ’TAMPA’);COMMIT;

COMMITCOMMENT ’In-doubt transaction Code 36, Call x1122’;

Page 37: BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands

BACS 485—Database Management

RollbackROLLBACK;

ROLLBACK TO SAVEPOINT sp5;