Relational and Object Relational Database Management Systems
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
Electronic spreadsheet
Intro-3
Filing cabinet
Database
Oracle server
Intro-4
Data Models
Entity model of clients model Table model of entity model Oracle server
Tables on disk
Intro-5
Primary key
Intro-6
Oracle server
Intro-7
SQL Statements
SELECT INSERT UPDATE DELETE MERGE CREATE ALTER DROP RENAME TRUNCATE COMMENT GRANT REVOKE COMMIT ROLLBACK SAVEPOINT
Transaction control
Intro-8
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
Not duplicate the name of another object owned by the same user
10-11
You specify:
The table name The column name, column data type, and column size
10-12
Tables belonging to other users are not in the users schema. You should use the owners name as a prefix to those tables.
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.
10-14
Creating Tables
Create the table:
CREATE TABLE ord ( ID NUMBER (3), quantity NUMBER (3), ord_date DATE DEFAULT SYSDATE) ;
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
10-16
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
Ensures that null values are not permitted for the column:
Absence of NOT NULL constraint (Any row can contain a null value for this column.)
10-21
UNIQUE Constraint
EMPLOYEES
UNIQUE constraint
INSERT INTO
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
ORDER_ITEMS
PRIMARY KEY
10-24
12
ORDER_ITEMS TABLE
FOREIGN KEY
10-25
10-26
13
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
( 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
Rename a column
Drop a 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
10-32
16
1-34
17
1-35
1-36
18
Arithmetic Expressions
Create expressions with number and date data by using arithmetic operators.
Operator + * /
1-37
1-38
19
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
Null is a value that is unavailable, unassigned, unknown, or inapplicable. Null is not the same as zero or a blank space.
Note: Round() will be explained later during the course of the presentation.
1-40
20
column alias Requires double quotation marks if it contains spaces column or special alias characters, or if it is case-sensitive
column alias
column alias
column alias
Immediately follows the column name (There can also be the optional AS keyword between the column name and the alias.)
1-41
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
22
EMPLOYEES
2-45
2-46
23
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
2-49
SELECT product_id, quantity_on_hand FROM inventories WHERE product_id BETWEEN 3100 AND 3108; Lower limit Upper limit
2-50
25
SELECT order_id, order_mode, order_status FROM orders WHERE order_id IN (2458, 2397, 2454) ;
2-51
2-52
26
You can use the ESCAPE identifier to search for the actual % and _ symbols.
2-53
2-54
27
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
2-56
28
2-57
SELECT order_id, order_status, order_total FROM orders WHERE order_status NOT IN (0,1,2,3) ;
2-58
29
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
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
JOB SAL SAL MAN SAL MAN MAN ANA PRE SAL CLE CLE ANA CLE
1400
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
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
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
Format String
YYYY Year MM MON Month MONTH DY Day HH24:MI:SS HH:MI:SS Ddspth DDth D
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
5-70
35
Group functions operate on sets of rows to give one result per group. EMPLOYEES
5-71
Group functions
5-72
36
5-73
AVG
Numeric Data
SUM
5-74
37
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
COUNT(expr) returns the number of rows with non-null values for expr:
5-76
38
EMPLOYEES
4400 9500
3500
6400
10033
5-77
SELECT column, group_function(column) FROM table [WHERE condition] [GROUP BY group_by_expression] [ORDER BY column];
5-78
39
5-79
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
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
5-82
41
5-83
SELECT warehouse_id, AVG(quantity_on_hand) FROM inventories GROUP BY warehouse_id HAVING MAX (quantity_on_hand) > 130 ;
5-84
42
job_id, SUM(salary) PAYROLL employees job_id NOT LIKE '%REP%' job_id SUM(salary) > 13000 SUM(salary);
5-85
43
6-87
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
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
6-90
45
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
6-92
46
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
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
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
48
Who has a credit limit than Charlie Pacinos? Main query: Which customers have credit limit greater than Charlie Pacinos credit limit? Subquery:
7-97
Subquery Syntax
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
7-100
50
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
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
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
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
7-105
Manipulating Data
9-106
53
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
9-108
54
Add new rows to a table by using the INSERT statement: INSERT INTO VALUES table [(column [, column...])] (value [, value...]);
9-109
9-110
55
9-111
9-112
56
9-113
Values for all the rows in the table are modified if you omit the WHERE clause: UPDATE inventories SET warehouse_id = 7 ;
9-114
57
9-115
DELETE Statement
You can remove existing rows from a table by using the DELETE statement:
table condition];
9-116
58
All rows in the table are deleted if you omit the WHERE clause:
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
9-119
9-120
60
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
An automatic rollback occurs when there is an abnormal termination of SQL Developer or SQL*Plus or a system failure
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
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
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
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
11-129
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
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 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 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) ;
11-141
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>
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