Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands."— Presentation transcript:

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

2 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

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

4 BACS 485—Database Management Create Table Commands CREATE TABLE name (col-name type [(size)][CONSTRAINT],...); CONSTRAINT name {PRIMARY KEY | UNIQUE | REFERENCES foreign_table [(foreignfield)] } Basic Create Table: CREATE TABLE STUDENT (STUIDCHAR (5) PRIMARY KEY, SSNCHAR (9), LNAMEVARCHAR2 (25), FNAME VARCHAR2 (15), MAJORVARCHAR2 (7), CREDITSNUMBER (1));

5 BACS 485—Database Management Create Table Commands CREATE 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));

6 BACS 485—Database Management Alter Table Commands ALTER 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 emp ADD (thriftplan NUMBER(7,2), loancode CHAR(1) NOT NULL);

7 BACS 485—Database Management Create View Commands CREATE VIEW dept20 AS SELECT ename, sal*12 annual_salary FROM emp WHERE deptno = 20; CREATE VIEW clerk (id_number, person, department, position) AS SELECT empno, ename, deptno, job FROM emp WHERE job = ’CLERK’ WITH READ ONLY; ALTER VIEW customer_view COMPILE; DROP VIEW dept20;

8 BACS 485—Database Management Index Commands CREATE INDEX emp_idx ON scott.emp (ename); CREATE INDEX emp_i ON emp (UPPER(ename)); ALTER INDEX emp_ix REBUILD REVERSE; DROP INDEX monolith;

9 BACS 485—Database Management Sequence Command CREATE SEQUENCE seq1 INCREMENT BY 10; CREATE SEQUENCE acct_seq INCREMENT BY 10 START WITH 100 NOMAXVALUE NOCYCLE CACHE 10; ALTER SEQUENCE seq1 MAXVALUE 1500; DROP SEQUENCE elly.seq1;

10 BACS 485—Database Management Oracle SQL DML Select Insert Update Delete

11 BACS 485—Database Management Select Commands SELECT {field-list | * | DISTINCT field} FROM table-list WHERE expression GROUP BY group-fields HAVING group-expression ORDER BY field-list; Basic Select Example: Select * From Emp Where Salary > and Status = “Full Time” Order By SSN;

12 BACS 485—Database Management More Complex Selects SELECT deptno, MIN(sal), MAX (sal) FROM emp WHERE job = 'CLERK' GROUP BY deptno HAVING MIN(sal) < 1000; Would print: DEPTNOMIN(SAL)MAX(SAL)

13 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 SUMSum of non-null values NUMBER STDStandard deviation of non-null values NUMBER VAR[IANCE]Variance of non-null values NUMBER

14 BACS 485—Database Management Other Select Operators Logical Operators And Or Not Comparison Operator =,<>,,>= IS NULL BETWEEN…AND IN LIKE

15 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

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

17 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

18 BACS 485—Database Management Single Row Sub-Query SELECT deptno, UPPER(ename), sal FROM emp x WHERE sal > (SELECT AVG(sal) FROM emp WHERE x.deptno = deptno) ORDER BY deptno;

19 BACS 485—Database Management Multiple Row Query Operators >ALL means more than the maximum value in list ANY means less than the maximum value in list

20 BACS 485—Database Management Multiple Row Sub-queries SELECT SSN, Lname FROM student WHERE FacID IN (SELECT FacID FROM faculty WHERE deptID = 1); SELECT empno, lname, fname, salary FROM employee WHERE salary >ANY (SELECT salary FROM employee WHERE posID = 2) AND posID <> 2; SELECT empno, lname, fname, salary FROM employee WHERE salary

21 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 1 st value to 2 nd value Substr (col, x, y) – returns substring starting at ‘x’ for ‘y’ characters Instr (col, c) – returns position of 1 st ‘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’

22 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

23 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 n p Abs (n) – Absolute value of n Mod (x,y) – integer remainder of x/y +, -, *, / - perform basic mathematical operations

24 BACS 485—Database Management Complex Select Sub-Queries SELECT 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.emp GROUP BY deptno) a, (SELECT COUNT(*) total_count, SUM(sal) total_sal FROM scott.emp) b ;

25 BACS 485—Database Management Complex Select Sub-Queries SELECT 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;

26 BACS 485—Database Management Complex Select Sub-Queries Find the top 2 salaries in each department: SELECT m.ename, m.sal, m.deptno FROM emp m WHERE 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.ROWID FROM emp i2) I WHERE I.deptno = m.deptno)) ORDER BY deptno, sal DESC; ENAMESALDEPTNO KING CLARK SCOTT FORD BLAKE285030

27 BACS 485—Database Management Complex Select Sub-Queries Find top 3 travel agents based on tickets sold: SELECT id, ticket_price, agent_rank FROM (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; IDTicket_PriceAgent_rank

28 BACS 485—Database Management Select Self-Join SELECT 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 KING CLARK works for KING JONES works for KING FORD works for JONES SMITH works for FORD ALLEN works for BLAKE WARD works for BLAKE …

29 BACS 485—Database Management Select Outer Join SELECT ename, job, dept.deptno, dname FROM emp, dept WHERE emp.deptno (+) = dept.deptno; SELECT custname, TO_CHAR(orderdate, ’MON-DD-YYYY’) "ORDERDATE", partno, quantity FROM customers, orders, lineitems WHERE customers.custno = orders.custno (+) AND orders.orderno = lineitems.orderno (+);

30 BACS 485—Database Management Decode Statement SELECT ename, deptno, DECODE (deptno, 10, ‘ACCOUNTING’, 20, ‘RESEARCH’, 30, ‘SALES’, ‘NOT INDICATED’) FROM emp; ENAMEDEPTNODECODE(DEPTNO TURNER30SALES ALLEN20RESEARCH JONES10ACCOUNTING WARD20RESEARCH

31 BACS 485—Database Management Insert Commands INSERT INTO dept VALUES (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 bonus SELECT ename, job, sal, comm FROM emp WHERE comm > 0.25 * sal OR job IN (’PRESIDENT’, ’MANAGER’); INSERT INTO emp VALUES (empseq.nextval, ’LEWIS’, ’CLERK’, 7902, SYSDATE, 1200, NULL, 20);

32 BACS 485—Database Management Update Commands UPDATE emp SET comm = NULL WHERE job = ’TRAINEE’; UPDATE emp SET job = ’MANAGER’, sal = sal , deptno = 20 WHERE ename = ’JONES’; UPDATE emp SET sal = sal * 1.1 WHERE empno NOT IN (SELECT empno FROM bonus);

33 BACS 485—Database Management Complex Update Command UPDATE emp a SET deptno = (SELECT deptno FROM dept WHERE loc = ’BOSTON’), (sal, comm) = (SELECT 1.1*AVG(sal), 1.5*AVG(comm) FROM emp b WHERE a.deptno = b.deptno) WHERE deptno IN (SELECT deptno FROM dept WHERE loc = ’DALLAS’ OR loc = ’DETROIT’);

34 BACS 485—Database Management Delete Command DELETE FROM temp_assign; DELETE FROM emp WHERE JOB = ’SALESMAN’ AND COMM < 100; DELETE FROM (select * from emp) WHERE JOB = ’SALESMAN’ AND COMM < 100;

35 BACS 485—Database Management Oracle SQL DCL Commit Rollback

36 BACS 485—Database Management Commit INSERT INTO dept VALUES (50, ’MARKETING’, ’TAMPA’); COMMIT; COMMIT COMMENT ’In-doubt transaction Code 36, Call x1122’;

37 BACS 485—Database Management Rollback ROLLBACK; ROLLBACK TO SAVEPOINT sp5;


Download ppt "BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands."

Similar presentations


Ads by Google