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

Slides:



Advertisements
Similar presentations
Manipulating Data Schedule: Timing Topic 60 minutes Lecture
Advertisements

Copyright  Oracle Corporation, All rights reserved. 10 Creating and Managing Tables.
9-1 Copyright  Oracle Corporation, All rights reserved. Data Manipulation Language A DML statement is executed when you: – Add new rows to a table.
Introduction To SQL Lynnwood Brown President System Managers LLC Copyright System Managers LLC 2003 all rights reserved.
12-1 Copyright  Oracle Corporation, All rights reserved. What Is a View? EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
Restricting and sorting data 16 May May May Created By Pantharee Sawasdimongkol.
Bogdan Shishedjiev SQL1 SQL Reminder of SQL. Bogdan Shishedjiev SQL 2 Subsets of language Data definition language (DDL) –Domain definition –Schema definition.
1Eyad Alshareef Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
Dale Roberts 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
Copyright  Oracle Corporation, All rights reserved. 9 Manipulating Data: INSERT, UPDATE, DELETE.
Logical Operators Operator AND OR NOT Meaning Returns TRUE if both component conditions are TRUE Returns TRUE if either component condition is TRUE Returns.
Introduction to DBMS and SQL Introduction to DBMS and SQL GUIDED BY : MR. YOGESH SAROJ (PGT-CS) MR. YOGESH SAROJ (PGT-CS) Presented By : JAYA XII –COM.
ORACLE SQL. Overview Personal DBMS Vs Client/Server DBMS Oracle 8 Environment SQL – syntax and examples PL/SQL-introduction.
o At the end of this lesson, you will be able to:  Describe the life-cycle development phases  Discuss the theoretical and physical aspects of a relational.
Copyright  Oracle Corporation, All rights reserved. I Introduction.
Creating a Table Create a table, “emp”, containing: –empno – a 4 digit employee number –ename – up to 10 character string –job – up to 9 character string.
Copyright  Oracle Corporation, All rights reserved. 1 Writing Basic SQL Statements.
4-1 Copyright  Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
Oracle Database Administration Lecture 2 SQL language.
Dr. Philip Cannata 1 Programming Languages Prolog Part 3 SQL & Prolog.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Introduction to Relational Databases &
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Cursors These slides are licensed under.
ACTION QUERIES (SQL COMMANDS ) STRUCTURED QUERY LANGUAGE.
Subqueries.
1 Information Retrieval and Use (IRU) CE An Introduction To SQL Part 1.
Joins & Sub-queries. Oracle recognizes that you may want data that resides in multiple tables drawn together in some meaningful way. One of the most important.
Copyright س Oracle Corporation, All rights reserved. I Introduction.
Copyright  Oracle Corporation, All rights reserved. 4 Accessing a Database Using JBCL.
10 Creating and Managing Tables Objectives At the end of this lesson, you will be able to: Describe the main database objects Create tables Describe.
Nitin Singh/AAO RTI ALLAHABAD 1 SQL Nitin Singh/AAO RTI ALLAHABAD 2 OBJECTIVES §What is SQL? §Types of SQL commands and their function §Query §Index.
SQL- DQL (Oracle Version). 2 SELECT Statement Syntax SELECT [DISTINCT] column_list FROM table_list [WHERE conditional expression] [GROUP BY column_list]
SQL. Relating Multiple Tables Relational Database Terminology Row PK Column FK Field NULL.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Basic SQL These slides are licensed under.
Copyright  Oracle Corporation, All rights reserved. 10 Creating and Managing Tables.
Session 2: SQL (A): Parts 1 and 2 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram.
SQL SeQueL -Structured Query Language SQL SQL better support for Algebraic operations SQL Post-Relational row and column types,
11-1 Copyright  Oracle Corporation, All rights reserved. What Are Constraints? Constraints enforce rules at the table level. Constraints prevent.
Copyright  Oracle Corporation, All rights reserved. 11 Including Constraints.
Copyright  Oracle Corporation, All rights reserved. Introduction.
Copyright  Oracle Corporation, All rights reserved. 4 Introduction.
SQL: Part 1 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial.
I-1 Copyright س Oracle Corporation, All rights reserved. Data Retrieval.
Manipulating Data. Objectives After completing this lesson, you should be able to do the following: Describe each DML statement Insert rows into a table.
9 Manipulating Data. 9-2 Objectives At the end of this lesson, you should be able to: Describe each DML statement Insert rows into a table Update rows.
Copyright  Oracle Corporation, All rights reserved. 12 Creating Views.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Subqueries These slides are licensed under.
An Introduction To SQL Part 2 (Special thanks to Geoff Leese)
1 Information Retrieval and Use (IRU) An Introduction To SQL Part 2.
Copyright س Oracle Corporation, All rights reserved. I Introduction.
Oracle CONNECT BY function JAVA WEB Programming. Emp 테이블의 내용 ( 상 / 하급자 계층구조 ) SQL> select * from emp; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
Copyright س Oracle Corporation, All rights reserved. 12 Creating Views.
CSCI N311: Oracle Database Programming 5-1 Chapter 15: Changing Data: insert, update, delete Insert Rollback Commit Update Delete Insert Statement –Allows.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
SQL Statements SELECT INSERTUPDATEDELETECREATEALTERDROPRENAMETRUNCATECOMMITROLLBACKSAVEPOINTGRANTREVOKE Data Retrieval Language (DRL) Data Retrieval Language.
Communicating with a RDBMS Using SQL Database SQL> SELECT loc 2 FROM dept; SQL> SELECT loc 2 FROM dept; SQL statement is entered Statement is sent to database.
Relational Normalization Theory
Including Constraints
Subqueries.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Manipulating Data Schedule: Timing Topic 40 minutes Lecture
Interacting with the Oracle Server
Writing Correlated Subqueries
What Is a View? EMPNO ENAME JOB EMP Table EMPVU10 View
(SQL) Manipulating Data
SQL Statements SELECT INSERT UPDATE DELETE CREATE ALTER DROP RENAME
Subqueries Schedule: Timing Topic 25 minutes Lecture
Subqueries Schedule: Timing Topic 25 minutes Lecture
Presentation transcript:

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

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)

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

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

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

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;

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;

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;

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

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;

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)

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

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

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

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

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

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;

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.

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 <ALL (SELECT AVG(salary) FROM employee GROUP BY deptID);

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’

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

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

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 ;

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;

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

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

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 …

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

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

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

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

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

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;

BACS 485—Database Management Oracle SQL DCL Commit Rollback

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

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