You are on page 1of 75

Introduction

Relational and Object Relational Database Management Systems

Relational model and object relational model User-defined data types and objects Fully compatible with relational database Supports multimedia and large objects High-quality database server features

Intro-2

Data Storage on Different Media

Electronic spreadsheet
Intro-3

Filing cabinet

Database

Definition of a Relational Database


A relational database is a collection of relations or two-dimensional tables.

Oracle server

Table name: EMPLOYEES

Table name: DEPARTMENTS

Intro-4

Data Models

Model of system in clients mind

Entity model of clients model Table model of entity model Oracle server

Tables on disk

Intro-5

Relating Multiple Tables


Each row of data in a table is uniquely identified by a primary key. You can logically relate data from multiple tables using foreign keys.

Table name: DEPARTMENTS Table name: EMPLOYEES

Primary key
Intro-6

Primary key Foreign key

Using SQL to Query Your Database


Structured query language (SQL) is: The ANSI standard language for operating relational databases Efficient, easy to learn, and use Functionally complete (With SQL, you can define, retrieve, and manipulate data in the tables.)

SELECT department_name FROM departments;

Oracle server

Intro-7

SQL Statements
SELECT INSERT UPDATE DELETE MERGE CREATE ALTER DROP RENAME TRUNCATE COMMENT GRANT REVOKE COMMIT ROLLBACK SAVEPOINT

Data manipulation language (DML)

Data definition language (DDL)

Data control language (DCL)

Transaction control

Intro-8

Using DDL Statements to Create and Manage Tables

10-9

Database Objects

Object
Table View Sequence Index Synonym

Description
Basic unit of storage; composed of rows Logically represents subsets of data from one or more tables Generates numeric values Improves the performance of some queries Gives alternative name to an object

10-10

Naming Rules

Table names and column names must: Be 130 characters long

Begin with a letter

Naming Rules Contain only AZ, az, 09, _, $, and #

Not be an Oracle serverreserved word

Not duplicate the name of another object owned by the same user
10-11

CREATE TABLE Statement

You must have:


The CREATE TABLE privilege A storage area CREATE TABLE [schema.]table (column datatype [DEFAULT expr][, ...]);

You specify:
The table name The column name, column data type, and column size

10-12

Referencing Anonther Users Tables

Tables belonging to other users are not in the users schema. You should use the owners name as a prefix to those tables.

USERA SELECT * FROM userB.employees;

USERB SELECT * FROM userA.employees;

10-13

DEFAULT Option

Specify a default value for a column during an insert. ... hire_date DATE DEFAULT SYSDATE, ...

Literal values, expressions, or SQL functions are legal values. Another columns name or a pseudocolumn are illegal values. The default data type must match the column data type.

CREATE TABLE hire_dates (id NUMBER(8), hire_date DATE DEFAULT SYSDATE);

10-14

Creating Tables
Create the table:
CREATE TABLE ord ( ID NUMBER (3), quantity NUMBER (3), ord_date DATE DEFAULT SYSDATE) ;

Confirm table creation:


DESCRIBE ord ;

10-15

Data Types

Data Type
CHAR(size) NUMBER(p,s) DATE LONG CLOB RAW and LONG RAW BLOB BFILE ROWID

Description
Fixed-length character data Variable-length numeric data Date and time values Variable-length character data (up to 2 GB) Character data (up to 4 GB) Raw binary data Binary data (up to 4 GB) Binary data stored in an external file (up to 4 GB) A base-64 number system representing the unique address of a row in its table

VARCHAR2(size) Variable-length character data

10-16

Datetime Data Types

You can use several datetime data types: Data Type


TIMESTAMP INTERVAL YEAR TO MONTH INTERVAL DAY TO SECOND

Description
Date with fractional seconds Stored as an interval of years and months Stored as an interval of days, hours, minutes, and seconds

10-17

Including Constraints
Constraints enforce rules at the table level. Constraints prevent the deletion of a table if there are dependencies. The following constraint types are valid: NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK

10-18

Defining 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, ...),

10-19

Defining Constraints
Example of a column-level constraint: CREATE TABLE orders( order_id NUMBER(4) CONSTRAINT ord_ord_id_pk PRIMARY KEY, order_mode VARCHAR2(20), ...); Example of a table-level constraint: CREATE TABLE orders( order_id NUMBER(6), order_mode VARCHAR2(20), ... customer_id VARCHAR2(10) NOT NULL, CONSTRAINT ord_ord_id_pk PRIMARY KEY (ORDER_ID));

10-20

10

NOT NULL Constraint Orders table

Ensures that null values are not permitted for the column:

NOT NULL constraint (Primary Key enforces NOT NULL constraint.)

NOT NULL constraint

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

10-21

UNIQUE Constraint

EMPLOYEES

UNIQUE constraint

INSERT INTO

Allowed Not allowed: already exists

10-22

11

UNIQUE Constraint

Defined at either the table level or the column level: CREATE TABLE orders( order_id NUMBER(4), order_mode VARCHAR2(25) NOT NULL, order_status CHAR(2), customer_id NUMBER(8,2), order_date DATE NOT NULL, ... CONSTRAINT ord_id_uk UNIQUE(order_id));

10-23

PRIMARY KEY Constraint

ORDER_ITEMS
PRIMARY KEY

10-24

12

FOREIGN KEY Constraint


INVENTORIES TABLE
PRIMARY KEY

ORDER_ITEMS TABLE
FOREIGN KEY

10-25

FOREIGN KEY Constraint

Defined at either the table level or the column level:

CREATE TABLE orders( order_id order_mode order_status customer_id order_date ...

NUMBER(4), VARCHAR2(25) NOT NULL, CHAR(2), NUMBER(8,2), DATE NOT NULL,

CONSTRAINT ord_inv_fk FOREIGN KEY (order_id) REFERENCES inventories(order_id));

10-26

13

FOREIGN KEY Constraint: Keywords


FOREIGN KEY: Defines the column in the child table at the table-constraint level REFERENCES: Identifies the table and column in the parent table ON DELETE CASCADE: Deletes the dependent rows in the child table when a row in the parent table is deleted ON DELETE SET NULL: Converts dependent foreign key values to null

10-27

CHECK Constraint
Defines a condition that each row must satisfy

The following expressions are not allowed: References to CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudo columns Calls to SYSDATE, UID, USER, and USERENV functions Queries that refer to other values in other rows

..., order_status NUMBER(2) CONSTRAINT ord_status_btw CHECK (order_status BETWEEN 0 AND 10),...

10-28

14

CREATE TABLE: Example


CREATE TABLE customers

( customer_id NUMBER(6) , cust_first_name VARCHAR2(20) CONSTRAINT cust_fname_nn NOT NULL , cust_last_name VARCHAR2(20) CONSTRAINT cust_lname_nn NOT NULL , cust_address cust_address_typ , phone_numbers phone_list_typ , nls_language VARCHAR2(3) , nls_territory VARCHAR2(30) , credit_limit NUMBER(9,2) , cust_email VARCHAR2(30) , account_mgr_id NUMBER(6) , CONSTRAINT customer_credit_limit_max CHECK (credit_limit <= 5000) , CONSTRAINT customer_id_min CHECK (customer_id > 0) ) ;

10-29

ALTER TABLE Statement


Use the ALTER TABLE statement to: Change table to read-only status

Add a new column

Rename a column

ALTER TABLE Statement

Modify an existing column definition

Drop a column

Define a default value for the new column

10-30

15

Read-Only Tables
You can use the ALTER TABLE syntax to:
Put the table back into read/write mode Put a table into read-only mode, which prevents DDL or DML changes during table maintenance

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

10-31

Dropping a Table

with DROP Table statement, entire table is deleted from the database

Invalidates dependent objects and removes object privileges on the table

DROP TABLE ord2458;

10-32

16

Retrieving Data Using the SQL SELECT Statement

Basic SELECT Statement

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

SELECT identifies the columns to be displayed.

FROM identifies the table containing those columns.

1-34

17

Selecting All Columns

SELECT * FROM inventories ;

1-35

Selecting Specific Columns

SELECT product_id, quantity_on_hand FROM inventories ;

1-36

18

Arithmetic Expressions
Create expressions with number and date data by using arithmetic operators.

Operator + * /

Description Add Subtract Multiply Divide

1-37

Using Arithmetic Operators


SELECT product_id, quantity_on_hand, quantity_on_hand+200 FROM inventories ;

1-38

19

What is a NULL value ?

What is a NULL value ? If a row does not have an entry for a particular column, that value is said to be NULL.. What is a NULL value ? It is the absence of any character, zero, blank space etc. What is a NULL value ? Arithmetic operations on a NULL value always return a NULL value.

1-39

Defining a Null Value

Null is a value that is unavailable, unassigned, unknown, or inapplicable. Null is not the same as zero or a blank space.

SELECT order_id, ROUND (order_date) ORDER_DATE, customer_id, promotion_id FROM orders ;

Note: Round() will be explained later during the course of the presentation.
1-40

20

Defining a Column Alias

column alias Requires double quotation marks if it contains spaces column or special alias characters, or if it is case-sensitive

Renames a column heading

column alias

column alias

Is useful with calculations

column alias

Immediately follows the column name (There can also be the optional AS keyword between the column name and the alias.)

1-41

Using Column Aliases


SELECT product_id AS Product , quantity_on_hand Quantity FROM inventories ;

SELECT order_id "Order " , ROUND(order_date) "Date of Order" FROM orders ;

1-42

21

Concatenation Operator
A concatenation operator: Links columns or character strings to other columns Is represented by two vertical bars (||) Creates a resultant column that is a character expression SELECT first_name || last_name AS "NAME" FROM customers ;

1-43

Restricting and Sorting Data

22

Limiting Rows Using a Selection

EMPLOYEES

retrieve all employees in department 90

2-45

Limiting the Rows That Are Selected


Restrict the rows that are returned by using the : WHERE clause SELECT *|{[DISTINCT] column|expression [alias],...} FROM table [WHERE condition(s)]; The WHERE clause follows the FROM clause.

2-46

23

Using the WHERE Clause

SELECT order_id, order_date, order_status FROM orders WHERE order_status = 1 ;

2-47

Comparison Operators

Operator
= > >= < <= <> BETWEEN ...AND... IN(set) LIKE IS NULL

Meaning
Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to Between two values (inclusive) Match any of a list of values Match a character pattern Is a null value

2-48

24

Using Comparison Operators

SELECT order_id, order_date FROM orders WHERE order_id <= 2400 ;

2-49

Range Conditions Using the BETWEEN Operator


Use the BETWEEN operator to display rows based on a range of values:

SELECT product_id, quantity_on_hand FROM inventories WHERE product_id BETWEEN 3100 AND 3108; Lower limit Upper limit

2-50

25

Membership Condition Using the IN Operator


Use the IN operator to test for values in a list:

SELECT order_id, order_mode, order_status FROM orders WHERE order_id IN (2458, 2397, 2454) ;

2-51

Pattern Matching Using the LIKE Operator


Use the LIKE operator to perform wildcard searches of valid search string values. Search conditions can contain either literal characters or numbers: % denotes zero or many characters. _ denotes one character.

SELECT FROM WHERE

first_name employees first_name LIKE 'S%' ;

2-52

26

Combining Wildcard Characters


You can combine the two wildcard characters (%, _) with literal characters for pattern matching: SELECT last_name FROM employees WHERE last_name LIKE '_o%' ;

You can use the ESCAPE identifier to search for the actual % and _ symbols.

2-53

Using the NULL Conditions


Test for nulls with the IS NULL operator. SELECT order_ID, order_status, sales_rep_id FROM orders WHERE sales_rep_id IS NULL;

2-54

27

Defining Conditions Using the Logical Operators

Operator
AND OR NOT

Meaning
Returns TRUE if both component conditions are true Returns TRUE if either component condition is true Returns TRUE if the condition is false

2-55

Using the AND Operator


AND requires both the component conditions to be true: SELECT order_mode, order_status, customer_id FROM orders WHERE order_mode = ' direct ' AND customer_id = 103;

2-56

28

Using the OR Operator


OR requires either component condition to be true: SELECT order_id, order_status, order_total FROM orders WHERE order_status = 0 OR order_total >= 100000 ;

2-57

Using the NOT Operator

SELECT order_id, order_status, order_total FROM orders WHERE order_status NOT IN (0,1,2,3) ;

2-58

29

Using the ORDER BY Clause


Sort the retrieved rows with the ORDER BY clause: ASC: Ascending order, default DESC: Descending order The ORDER BY clause comes last in the SELECT statement:

SELECT order_id, order_date, order_status FROM orders ORDER BY order_date ;

2-59

Sorting
Sorting in descending order: SELECT order_id, round(order_date), order_status FROM orders ORDER BY order_date desc; Sorting by column alias: SELECT order_id, round(order_date), order_status Order Status FROM orders ORDER BY order_date desc ;

2-60

30

Sorting
Sorting by using the columns numeric position: SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY 3; Sorting by multiple columns: SELECT last_name, department_id, salary FROM employees ORDER BY department_id, salary DESC;

2-61

SQL Functions

31

Single row SQL Function

EMPNO 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934

ENAME RAM SHYAM RAGHU RAVI ARJUN JOSEPH ARUN RAJ TURNER AKBAR CAPTAIN CHANDRAN MILLER

JOB SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER ANALYST PRESIDENT SALESMAN CLERK CLERK ANALYST CLERK

DEPTNO 30 30 30 20 30 30 10 20 10 30 20 30 20

HIREDATE 20-Feb-81 22-Feb-81 2-Apr-81 28-Sep-81 1-May-81 9-Jun-81 19-Apr-87 17-Nov-81 8-Sep-81 23-May-87 3-Dec-81 3-Dec-81 23-Jan-82

MGR 7698 7698 7839 7698 7839 7839 7566

SAL 2200 3000 2500 2100 2500 1200 2500 900

COMM 300 500

SUBSTR(JO,B,1,3) SUBSTR(SALESMAN,1,3) SUBSTR(SALESMAN,1,3) SUBSTR(MANAGER,1,3)

JOB SAL SAL MAN SAL MAN MAN ANA PRE SAL CLE CLE ANA CLE

1400

SUBSTR(SALESMAN,1,3) SUBSTR(MANAGER,1,3) SUBSTR(MANAGER,1,3) SUBSTR(ANALYST,1,3) SUBSTR(PRESIDENT,1,3)

7698 7788 7698 7566 7782

2200 2100 2100 1600 800

SUBSTR(SALESMAN,1,3) SUBSTR(CLERK,1,3) SUBSTR(CLERK,1,3) SUBSTR(ANALYST,1,3) SUBSTR(CLERK,1,3)

General Syntax : Function Name ( Column | Expression [, Arg1, Arg2 ..])

Single Row Number functions

Function Abs (n) Ceil (n) Exp(n) Mod(m,n) Power(m,n) Round(m,n) Sign(n) Sqrt(n) Trunc(n,m)

Return value Description Retruns positive value of n Returns smallest integer greater than or equal to n E raised to the nth power Returns reminder after dividing m by n whole number of times M raised to the nth power M rounded to nth decimal place, where n can take n to +n -1 if n is negative, 0 if n is 0 and +1 if n is positive Square root of n , where n is a positive value Value truncated to m decimal places, where m could range from m to +m

32

Single Row Char functions


Character Function Concat( string1,string2) Initcap(string) Upper(string) Lower(string) Lpad(string,n,char) Ltrim(string,set) Rtrim(string,set) Substr(mainstring,start,num_of_chars) Instr(mainstr,searchstr,start) Return value Description String after concatenating string1 and string2 Returns string with initial letters of words of the string in capital letters String in upper case String in Lower case String padded in left with char (default space) to form string of n character length Trims set (of chars) if it appears in the left of string Trims trim char set from source string according to option used Returns num_of_chars of mainstring starting from start position of mainstring Starting position of searchstr in mainstr starting from start

Single Row Date functions


Function Add_months(date,n_months) Extract( YEAR|MONTH|DAY|HOUR|MINUTE|SE COND|TIMEZONE_HOUR|TIMEZONE _MINUTE|TIMEZONE_REGION|TIMEZ ONE_ABBR From Date_value) Months_between(date1,date2) Round(date,formatstr) Sysdate Next_day(date,strday) Last_day(date) Trunc(date,formatstr) Current_timestamp Return value description Date after adding n_months to the given date Extracts any date/time component from a given date/or time interval value

Number representing No. of months bet date1 and date2 Rounded date value to nearest date component represented by formatstr Returns database date & time as of now Next date when strday comes after date Last date in the month of given date Date truncated to the unit specified by formatstr Returns current timestamp with time zone

33

Single Row - Conversion functions

Function To_char(date-time) To_char(number,formatstr) To_date(charstr,formatstr) To_number(charstr,formatstr) To_timestamp(string,fmt)

Return Value description String equivalent of the given date-time Number to equivalent character string as specified by format str Date present in charstr as in the given formatstr Number equivalent of the string by applying the format str Converts given string to equivalent time stamp

Miscellaneous functions
Function Decode ( exp1, outcome1, value1, outcome2, value2, .,value_default) Greatest(value1,value2,valueN) Least9value1, value2, , valueN) Nvl(expression|column, alternateValue) Nvl2(expression,value1,value2) Nullif(exp1,exp2) Coalesce(exp1,exp2,..expN) Return value/Description Evaluates exp1 and based on outcome corresponding value will be returned otherwise if present default value is returned Greatest all N values passed. All values are of same data type Least of all N values If expression evaluates to or column is of Null value alternate value or original expression/column value will be returned. If expression is not null then value1 or value2 will be returned Returns null if exp1 and 2 are equal else exp1 will be returned Returns first of exp1expN which if evaluates to a non Null value else returns NULL

34

Explicit date to character conversion formats

Format String
YYYY Year MM MON Month MONTH DY Day HH24:MI:SS HH:MI:SS Ddspth DDth D

Value returned for the date 23-NOV-1926


1926 Nineteen Twenty Six 11 NOV November NOVEMBER TUE Tuesday 00:00:00 12:00:00 Twenty Third 23rd 3 (Day number of the week)

RR Format Interpretation
Mentioned 2 digits in the date value 0-49 0-49 50-99 Current Century Next century 2 digits of Current Year

50-99 Previous century Current Century

Century of the interpreted Date

Reporting Aggregated Data Using the Group Functions

5-70

35

What Are Group Functions?

Group functions operate on sets of rows to give one result per group. EMPLOYEES

Maximum salary in EMPLOYEES table

5-71

Types of Group Functions

AVG COUNT MAX MIN STDDEV SUM VARIANCE

Group functions

5-72

36

Group Functions: Syntax

SELECT FROM [WHERE [ORDER BY

group_function(column), ... table condition] column];

5-73

Using the AVG and SUM Functions


You can use AVG and SUM for numeric data.

AVG

Numeric Data

SUM

SELECT AVG(order_total), MAX(order_total), MIN (order_total), SUM( order_total) FROM orders;

5-74

37

Using the MIN and MAX Functions


You can use MIN and MAX for numeric, character, and date data types. Numeric, Character, and Date Data types

MIN

MAX

SELECT MIN(to_char(order_date, 'fmDD Month YYYY')) AS "Min Order Date", MAX(to_char(order_date, 'fmDD Month YYYY')) AS "Max Order Date" FROM orders ;

5-75

Using the COUNT Function


COUNT(*) returns the number of rows in a table: SELECT count(*) FROM inventories WHERE warehouse_id = 8;

COUNT(expr) returns the number of rows with non-null values for expr:

SELECT COUNT(sales_rep_id) FROM orders WHERE order_status <=3;

5-76

38

Creating Groups of Data

EMPLOYEES
4400 9500

Average salary in the EMPLOYEES table for each department

3500

6400

10033

5-77

Creating Groups of Data: GROUP BY Clause Syntax


You can divide rows in a table into smaller groups by using the GROUP BY clause.

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

5-78

39

Using the GROUP BY Clause


All the columns in the SELECT list that are not in group functions must be in the GROUP BY clause. SELECT warehouse_id, AVG(quantity_on_hand) FROM inventories GROUP BY warehouse_id ;

5-79

Using the GROUP BY Clause

The GROUP BY column does not have to be in the SELECT list. SELECT AVG(order_total) FROM orders GROUP BY order_status ;

5-80

40

Illegal Queries Using Group Functions


Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause: SELECT department_id, COUNT(last_name) FROM employees; A GROUP BY clause must be added to count the last names for each department_id.

SELECT department_id, job_id, COUNT(last_name) FROM employees GROUP BY department_id; Either add job_id in the GROUP BY or remove the job_id column from the SELECT list.

5-81

Restricting Group Results


EMPLOYEES

The maximum salary per department when it is greater than $10,000

5-82

41

Restricting Group Results with the HAVING Clause


When you use the HAVING clause, the Oracle server restricts groups as follows: Rows are grouped. The group function is applied. Groups matching the HAVING clause are displayed.

SELECT FROM [WHERE [GROUP BY [HAVING [ORDER BY

column, group_function table condition] group_by_expression] group_condition] column];

5-83

Using the HAVING Clause

SELECT warehouse_id, AVG(quantity_on_hand) FROM inventories GROUP BY warehouse_id HAVING MAX (quantity_on_hand) > 130 ;

5-84

42

Using the HAVING Clause

SELECT FROM WHERE GROUP BY HAVING ORDER BY

job_id, SUM(salary) PAYROLL employees job_id NOT LIKE '%REP%' job_id SUM(salary) > 13000 SUM(salary);

5-85

Displaying Data from Multiple Tables Using Joins

43

Obtaining Data from Multiple Tables


EMPLOYEES DEPARTMENTS

6-87

Creating Joins with the ON Clause

The join condition for the natural join is basically an equijoin of all columns with the same name. Use the ON clause to specify arbitrary conditions or specify columns to join. The join condition is separated from other search conditions. The ON clause makes code easy to understand.

6-88

44

Retrieving Records with the ON Clause

SELECT e.order_status, e.customer_id, e.order_id, d.order_id, d.quantity FROM orders e JOIN order_items d ON (e.order_id = d.order_id) ;

6-89

Creating Three-Way Joins with the ON Clause


SELECT customer_id, unit_price, warehouse_id FROM orders e JOIN order_items d ON e.order_id = d.order_id JOIN inventories f ON d.product_id = f.product_id;

6-90

45

Applying Additional Conditions to a Join

Use the AND clause or the WHERE clause to apply additional conditions:

SELECT

e.order_status, e.customer_id, e.order_id, d.order_id, d.quantity FROM orders e JOIN order_items d ON (e.order_id = d.order_id) AND e.order_status = 0;

Or
SELECT e.order_status, e.customer_id, e.order_id, d.order_id, d.quantity FROM orders e JOIN order_items d ON (e.order_id = d.order_id) WHERE e.order_status = 0;

6-91

INNER Versus OUTER Joins


In SQL:1999, the join of two tables returning only matched rows is called an INNER join. A join between two tables that returns the results of the INNER join as well as the unmatched rows from the left (or right) table is called a left (or right) OUTER join. A join between two tables that returns the results of an INNER join as well as the results of a left and right join is a full OUTER join.

6-92

46

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

6-93

RIGHT OUTER JOIN

SELECT e.last_name, d.department_id, d.department_name FROM employees e RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id) ;

6-94

47

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

6-95

Using Sub queries to Solve Queries

48

Using a Subquery to Solve a Problem

Who has a credit limit than Charlie Pacinos? Main query: Which customers have credit limit greater than Charlie Pacinos credit limit? Subquery:

What is Charlie Pacinos credit limit?

7-97

Subquery Syntax

SELECT FROM WHERE

select_list table expr operator (SELECT FROM

select_list table);

The subquery (inner query) executes before the main query (outer query). The result of the subquery is used by the main query.

7-98

49

Using a Subquery

SELECT cust_first_name || cust_last_name FROM customers WHERE credit_limit < 200 (Select credit_limit FROM customers WHERE cust_first_name = 'Charlie' AND cust_last_name = 'Pacino');

7-99

Single-Row Subqueries

Return only one row


Use single-row comparison operators
Operator = > >= < <= <> Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to

7-100

50

Executing Single-Row Subqueries

SELECT customer_id, cust_last_name AS "LAST NAME" FROM customers 108 WHERE customer_id = (SELECT customer_id FROM customers WHERE cust_first_name = 'Meenakshi') AND credit_limit =
700

(SELECT credit_limit FROM customers WHERE cust_first_name = 'Meenakshi');

7-101

Multiple-Row Subqueries
Return more than one row Use multiple-row comparison operators

Operator IN ANY

Meaning Equal to any member in the list 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. 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.

ALL

7-102

51

Using the ANY Operator in Multiple-Row Subqueries

SELECT employee_id, last_name, job_id, salary 9000, 6000, 4200 FROM employees WHERE salary < ANY (SELECT salary FROM employees WHERE job_id = 'IT_PROG') AND job_id <> 'IT_PROG';

7-103

Using the ALL Operator in Multiple-Row Subqueries

SELECT employee_id, last_name, job_id, salary 9000, 6000, 4200 FROM employees WHERE salary < ALL (SELECT salary FROM employees WHERE job_id = 'IT_PROG') AND job_id <> 'IT_PROG';

7-104

52

Using the EXISTS Operator


SELECT * from orders WHERE NOT EXISTS (Select * FROM order_items WHERE order_items.order_id = orders.order_id);

7-105

Manipulating Data

9-106

53

Data Manipulation Language

A DML statement is executed when you: Add new rows to a table Modify existing rows in a table Remove existing rows from a table

A transaction consists of a collection of DML statements that form a logical unit of work.

9-107

Adding a New Row to a Table


DEPARTMENTS
New row Insert new row into the DEPARTMENTS table.

9-108

54

INSERT Statement Syntax

Add new rows to a table by using the INSERT statement: INSERT INTO VALUES table [(column [, column...])] (value [, value...]);

With this syntax, only one row is inserted at a time.

9-109

Inserting New Rows


Insert a new row containing values for each column. List values in the default order of the columns in the table. Optionally, list the columns in the INSERT clause. INSERT INTO order_items (order_id, line_item_id, product_id, unit_price, quantity) VALUES (2355, 1, 3108, 46, 200) ;

Enclose character and date values within single quotation marks.

9-110

55

Inserting Rows with Null Values


Implicit method: Omit the column from the column list. INSERT INTO promotions (promo_id) VALUES (3) ; Explicit method: Specify the NULL keyword in the VALUES clause. INSERT INTO promotions VALUES (3 , NULL) ;

9-111

Changing Data in a Table


EMPLOYEES

Update rows in the EMPLOYEES table:

9-112

56

UPDATE Statement Syntax


Modify existing values in a table with the UPDATE statement: UPDATE SET [WHERE table column = value [, column = value, ...] condition];

Update more than one row at a time (if required).

9-113

Updating Rows in a Table


Values for a specific row or rows are modified if you specify the WHERE clause: UPDATE inventories SET warehouse_id = 7 WHERE product_id = 3108 ;

Values for all the rows in the table are modified if you omit the WHERE clause: UPDATE inventories SET warehouse_id = 7 ;

Specify SET column_name= NULL to update a column value to NULL.

9-114

57

Removing a Row from a Table


DEPARTMENTS

Delete a row from the DEPARTMENTS table:

9-115

DELETE Statement
You can remove existing rows from a table by using the DELETE statement:

DELETE [FROM] [WHERE

table condition];

9-116

58

Deleting Rows from a Table


Specific rows are deleted if you specify the WHERE clause: DELETE FROM runreport WHERE comments = ' Editing Report ' ;

All rows in the table are deleted if you omit the WHERE clause:

DELETE FROM copy_emp;

9-117

Database Transactions
A database transaction consists of one of the following: DML statements that constitute one consistent change to the data One DDL statement One data control language (DCL) statement

9-118

59

Database Transactions: Start and End


Begin when the first DML SQL statement is executed. End with one of the following events: A COMMIT or ROLLBACK statement is issued. A DDL or DCL statement executes (automatic commit). The user exits SQL Developer or SQL*Plus. The system crashes.

9-119

Explicit Transaction Control Statements


Time

COMMIT Transaction DELETE SAVEPOINT A INSERT

UPDATE SAVEPOINT B INSERT ROLLBACK to SAVEPOINT B ROLLBACK to SAVEPOINT A ROLLBACK

9-120

60

Rolling Back Changes to a Marker

Create a marker in the current transaction by using the SAVEPOINT statement. Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement. UPDATE... SAVEPOINT update_done; INSERT... ROLLBACK TO update_done;

9-121

Implicit Transaction Processing

An automatic rollback occurs when there is an abnormal termination of SQL Developer or SQL*Plus or a system failure

Implicit Transaction Processing

An automatic commit occurs in the following circumstances: A DDL statement issued A DCL statement issued Normal exit from SQL Developer or SQL*Plus, without explicitly issuing COMMIT or ROLLBACK statements

9-122

61

State of the Data Before COMMIT or ROLLBACK

The previous state of the data can be recovered.

The current user can review the results of the DML operations by using the SELECT statement.

Other users cannot view the results of the DML statements issued by the current user. The affected rows are locked; other users cannot change the data in the affected rows.

9-123

Committing Data
Make the changes: DELETE FROM inventories WHERE product_id = 2458 ; INSERT INTO Inventories VALUES (2670, 6, 159); Commit the changes: COMMIT ;

9-124

62

State of the Data After ROLLBACK: Example

DELETE FROM order_items; 603 rows deleted. ROLLBACK; Rollback complete. DELETE FROM order_items WHERE 1 row deleted. SELECT * FROM order_id WHERE No rows selected. COMMIT; Commit complete. product_id = 2348;

product_id = 2348;

9-125

Creating Other Schema Objects

63

Database Objects

Object
Table View Sequence Index Synonym

Description
Basic unit of storage; composed of rows Logically represents subsets of data from one or more tables Generates numeric values Improves the performance of data retrieval queries Gives alternative names to objects

11-127

What Is a View?
EMPLOYEES table

11-128

64

Advantages of Views

To restrict data access

To make complex queries easy

To provide data independence

To present different views of the same data

11-129

Simple Views and Complex Views

Feature
Number of tables Contain functions Contain groups of data DML operations through a view

Simple Views
One No No Yes

Complex Views
One or more Yes Yes Not always

11-130

65

Creating a View

You embed a subquery in the CREATE VIEW statement: CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)] AS subquery [WITH CHECK OPTION [CONSTRAINT constraint]] [WITH READ ONLY [CONSTRAINT constraint]]; The subquery can contain complex SELECT syntax.

11-131

Creating a View
Create the EMPVU80 view, which contains details of the employees in department 80:
CREATE VIEW ordvu AS SELECT order_id , order_date , order_status FROM orders WHERE order_status = 10 ;

Describe the structure of the view by using the SQL*Plus DESCRIBEordvu command: DESCRIBE ;

11-132

66

Creating a View

Create a view by using column aliases in the subquery: CREATE VIEW ordvu AS SELECT order_id , order_status , order_total / 12 Total_per_Month FROM orders WHERE order_status = 10 ;

Select the columns from this view by the given alias names.

11-133

Retrieving Data from a View

SELECT * FROM ordvu ;

11-134

67

Removing a View
You can remove a view without losing data because a view is based on underlying tables in the database.
DROP VIEW view; DROP VIEW ordvu;

11-135

Sequences

Object
Table View Sequence Index Synonym

Description
Basic unit of storage; composed of rows Logically represents subsets of data from one or more tables Generates numeric values Improves the performance of some queries Gives alternative names to objects

11-136

68

Sequences

A sequence:
Can automatically generate unique numbers Is a shareable object Can be used to create a primary key value Replaces application code Speeds up the efficiency of accessing sequence values when cached in memory

2 1 3

4 5

6 7

8 9

10

11-137

CREATE SEQUENCE Statement: Syntax

Define a sequence to generate sequential numbers automatically:

CREATE SEQUENCE sequence [INCREMENT BY n] [START WITH n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}];

11-138

69

Creating a Sequence

Create a sequence named DEPT_DEPTID_SEQ to be used for the primary key of the DEPARTMENTS table. Do not use the CYCLE option.

CREATE SEQUENCE ord_ordid_seq INCREMENT BY 10 START WITH 120 MAXVALUE 9999 NOCACHE NOCYCLE;

11-139

NEXTVAL and CURRVAL Pseudocolumns

NEXTVAL returns the next available sequence value. It returns a unique value every time it is referenced, even for different users. CURRVAL obtains the current sequence value. NEXTVAL must be issued for that sequence before CURRVAL contains a value.

11-140

70

Using a Sequence
Insert a new order with mode Direct and status 5:
INSERT INTO orders ( order_id , order_date , order_mode , order_status ) VALUES ( ord_ordid_seq.NEXTVAL, to_char (SYSDATE , fmDDfmDD-MonMon-YYYY ) , direct', 1) ;

View the current value for the DEPT_DEPTID_SEQ sequence:


SELECT FROM ord_ordid_seq.CURRVAL dual ;

11-141

Caching Sequence Values


Caching sequence values in memory gives faster access to those values.

Gaps in sequence values can occur when: A rollback occurs The system crashes A sequence is used in another table

11-142

71

Modifying a Sequence

Change the increment value, maximum value, minimum value, cycle option, or cache option:
ALTER SEQUENCE ord_ordid_seq INCREMENT BY 20 MAXVALUE 999999 NOCACHE NOCYCLE ;

11-143

Understanding Index

Index is a faster routing/searching mechanism to reach the actual location of (row of) data Indexes, in general, does not change the physical order of rows in a table rather facilitates faster reach to the location using application/domain specific data value based searching Brings the data organization/searching closer to the domain

72

Creating Index

Purpose: Create an index to increase the performance of the queries on cust_accounts table based on cust_id
Create Index command SQL> Create Index cust_accounts_cust_id_idx on cust_accounts(ca_custid); Index Created SQL>

Purpose: Performance of an application query which retrieves cust_accounts table based on acc_type and acc# has to be improved
Create Index command SQL> Create Index cust_accounts_acc_type_n_number_idx on cust_accounts(ca_type,ca_acc#); Index Created SQL>

Altering & Dropping Index

Purpose: When there are lot of index key column updates happened index structure needs to be recreated to increase or maintain the efficacy of the index based searches on the table
Alter Index command SQL> Alter Index cust_accounts_acc_type_n_number_idx Rebuild; Index altered SQL>

Purpose: Drop the index cust_accounts_cust_id_idx as it is not much used by the queries

Drop Index command SQL> Drop Index cust_accounts_cust_id_idx; Index dropped SQL>

73

Using an Index

There is, in general, no control in the users hand to dictate oracle to make use of index for a query execution Wherever in a query the where clause is based on indexed columns, Oracle query optimizer better decides when/where to make use of an index Users scope is only to create the index and leave it to oracle to maintain and use it

Index - Guidelines

Unnecessary creation of index will penalize the performance of DML operations for no cause Too many indexes (if it can be avoided) on on a table undergoing high rate of transaction will pull down the performance Good practice is to avoid updating primary key column(s) of a table rather delete and insert a new row

74

Synonyms
End Application Table Table in other schema Table in another database SYNONYM End Application View in another schema Procedure in another database

Create synonym statement SQL> Create synonym accounts for bank.cust_accounts; Synonym created. SQL>

Thank you!!!

75

You might also like