0% found this document useful (0 votes)
6 views142 pages

64505_Introduction-to-SQL

The document provides an introduction to SQL and database concepts, including definitions of databases, types of databases, and the relational database model. It covers SQL statements for data retrieval, manipulation, and definition, along with functions for data types and conditional expressions. Additionally, it explains how to work with multiple tables and avoid Cartesian products in SQL queries.

Uploaded by

kurumisora01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views142 pages

64505_Introduction-to-SQL

The document provides an introduction to SQL and database concepts, including definitions of databases, types of databases, and the relational database model. It covers SQL statements for data retrieval, manipulation, and definition, along with functions for data types and conditional expressions. Additionally, it explains how to work with multiple tables and avoid Cartesian products in SQL queries.

Uploaded by

kurumisora01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 142

Introduction to SQL

1
Produced By © Information System Department
Defining a Database

A database is an organized collection of


information. To manage databases, you need
database management systems (DBMS). A DBMS
is a program that stores, retrieves, and modifies
data in the database on request. There are four
main types of databases: hierarchical, network,
relational, and more recently object relational.
Note: Oracle7 is a relational database
management system and Oracle8, 8i, 9i and 10g
are object relational database management
systems.

2
Produced By © Information System Department
Relational Database Concept

Dr. E.F. Codd proposed the relational model for


database systems in 1970. It is the basis for the
relational database management system.
• The relational model consists of the following:
– Collection of objects or relations
– Set of operators to act on the relations
– Data integrity for accuracy and consistency

3
Produced By © Information System Department
Definition of a Relational
Database

A relational database uses relations or two-


dimensional tables to store information.
For example, you might want to store information
about all the employees in your company. In a
relational database, you create several tables to
store different pieces of information about your
employees, such as an employee table, a
department table, and a salary table.

4
Produced By © Information System Department
Data Models

5
Produced By © Information System Department
Entity Relationship Model

• Create an entity relationship diagram from


business specifications or narratives

6
Produced By © Information System Department
Entity Relationship Model

• Scenario
– “. . . Assign one or more employees to a
department . . .”
– “. . . Some departments do not yet have
assigned employees . . .”

7
Produced By © Information System Department
Relating Multiple Tables

• Each row of data in a table is uniquely identified


by a primary key (PK).

• You can logically relate data from multiple tables


using foreign keys (FK).

8
Produced By © Information System Department
Relational Database Properties

A relational database:
• Can be accessed and modified by executing
structured query language (SQL) statements
• Contains a collection of tables with no physical
pointers
• Uses a set of operators

9
Produced By © Information System Department
Plugging into the Grid

Grid computing is:


Software infrastructure that uses low-cost servers
and modular storage to:
Balance workloads
Provide capacity on demand
Made possible by innovations in hardware
Powered by software

10
Produced By © Information System Department
Oracle Enterprise Grid
Computing

Oracle’s grid infrastructure products:


Oracle Database 10g
Oracle Application Server 10g
Oracle Enterprise Manager 10g
Grid Control

11
Produced By © Information System Department
Oracle 10g Products and Forms
Development

Forms Services Forms Developer

12
Produced By © Information System Department
SQL Statements

Data retrieval
SELECT

Data manipulation language (DML)


INSERT
UPDATE
DELETE

13
Produced By © Information System Department
SQL Statements

Data definition language (DDL)


CREATE
ALTER
DROP
RENAME
TRUNCATE

Transaction control
COMMIT
ROLLBACK
SAVEPOINT

14
Produced By © Information System Department
SQL Statements

 Controlling User Access


• GRANT
• REVOKE

15
Produced By © Information System Department
Writing SQL Statements

 SQL statements are not case sensitive.


 SQL statements can be on one or more lines.
 Keywords cannot be abbreviated or split across
lines.
 Clauses are usually placed on separate lines.
 Indents are used to enhance readability.

16
Produced By © Information System Department
Basic SELECT Statement

 SELECT *|{[DISTINCT] column|expression


[alias],...}
 FROM table;

 • SELECT identifies what columns


 • FROM identifies which table

17
Produced By © Information System Department
Selecting All Columns

SELECT *
FROM departments;

18
Produced By © Information System Department
Selecting Specific Columns

SELECT department_id, location_id


FROM departments;

19
Produced By © Information System Department
Arithmetic Expressions

Create expressions with number and date data by


using arithmetic operators.

Operator Description
+ Add
- Subtract
* Multiply
/ Divide

20
Produced By © Information System Department
Operator Precedence

* / + -

• Multiplication and division take priority over


addition and subtraction.
• Operators of the same priority are evaluated from
left to right.
• Parentheses are used to force prioritized
evaluation and to clarify statements.

21
Produced By © Information System Department
Using Arithmetic Operators

SELECT last_name, salary, salary + 300


FROM employees;

22
Produced By © Information System Department
Defining a Column Alias

A column alias:
• Renames a column heading
• Is useful with calculations
• Immediately follows the column name: there can
also be the optional AS keyword between the
column name and alias
• Requires double quotation marks if it contains
spaces or special characters or is case sensitive

23
Produced By © Information System Department
Concatenation Operator

A concatenation operator:
• Concatenates columns or character strings to
other columns
• Is represented by two vertical bars (||)
• Creates a resultant column that is a character
expression

24
Produced By © Information System Department
Literal Character Strings

• A literal value is a character, a number, or a date


included in the SELECT list.
• Date and character literal values must be enclosed
within single quotation marks.
• Each character string is output once for each row
returned.

25
Produced By © Information System Department
Character Strings and Dates

• Character strings and date values are enclosed in


single quotation marks.
• Character values are case sensitive, and date
values are format sensitive.
• The default date format is DD-MON-RR.

SELECT last_name, job_id, department_id


FROM employees
WHERE last_name = 'Goyal';

26
Produced By © Information System Department
Duplicate Rows

The default display of queries is all rows, including


duplicate rows.
SELECT department_id
FROM employees;

Eliminate duplicate rows by using the DISTINCT


keyword in the SELECT clause.
SELECT DISTINCT department_id
FROM employees;

27
Produced By © Information System Department
Limiting the Rows Selected

Restrict the rows returned by using the WHERE


clause.
• The WHERE clause follows the FROM clause.
SELECT *|{[DISTINCT] column|expression [alias],...}
FROM table
[WHERE condition(s)];

• The WHERE clause follows the FROM clause.

28
Produced By © Information System Department
Comparison Conditions

Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to

29
Produced By © Information System Department
Using Comparison Conditions

SELECT last_name, salary


FROM employees
WHERE salary <= 3000;

30
Produced By © Information System Department
Other Comparison Conditions

Operator Meaning
BETWEEN...AND...
IN(set)
LIKE
IS NULL

Between two values (inclusive)


Match any of a list of values
Match a character pattern
Is a null value

31
Produced By © Information System Department
Single-Row Functions

Single row functions:


• Manipulate data items
• Accept arguments and return one value
• Act on each row returned
• Return one result per row
• May modify the data type
• Can be nested
• Accept arguments which can be a column or an
expression
function_name [(arg1, arg2,...)]

32
Produced By © Information System Department
Character Functions

Case Manipulation Functions


These functions convert case for character strings.

Function Result

LOWER('SQL Course') sql course


UPPER('SQL Course') SQL COURSE
INITCAP('SQL Course') Sql Course

33
Produced By © Information System Department
Character Manipulation Functions

These functions manipulate character strings:

Function Result

CONCAT('Hello', 'World') HelloWorld


SUBSTR('HelloWorld',1,5) Hello
LENGTH('HelloWorld') 10
INSTR('HelloWorld', 'W') 6
LPAD(salary,10,'*') *****24000
RPAD(salary, 10, '*') 24000*****
TRIM('H' FROM 'HelloWorld') elloWorld

34
Produced By © Information System Department
Number Functions

• ROUND: Rounds value to specified decimal


ROUND(45.926, 2) 45.93
• TRUNC: Truncates value to specified decimal
TRUNC(45.926, 2) 45.92
• MOD: Returns remainder of division
MOD(1600, 300) 100

35
Produced By © Information System Department
Working with Dates

• Oracle database stores dates in an internal


numeric format: century, year, month, day, hours,
minutes, seconds.
• The default date display format is DD-MON-RR.

SELECT last_name, hire_date


FROM employees
WHERE last_name like 'G%';

36
Produced By © Information System Department
Arithmetic with Dates

• Add or subtract a number to or from a date for a


resultant date value.
• Subtract two dates to find the number of days
between those dates.
• Add hours to a date by dividing the number of
hours by 24.

37
Produced By © Information System Department
Arithmetic with Dates

Operation Result
date + number Date
(Adds a number of days to a date)

date - number Date


(Subtracts a number of days from a date )

date - date Number of days


(Subtracts one date from another)

date + number/24 Date


(Adds a number of hours to a date)

38
Produced By © Information System Department
Date Functions

Function Description

MONTHS_BETWEEN Number of months


between two dates
ADD_MONTHS Add calendar months to
date
NEXT_DAY Next day of the date
specified
LAST_DAY Last day of the month
ROUND Round date
TRUNC Truncate date

39
Produced By © Information System Department
Conversion Functions

Implicit Data-Type Conversion

For assignments, the Oracle server can


automatically
convert the following:
From To

VARCHAR2 or CHAR NUMBER


VARCHAR2 or CHAR DATE
NUMBER VARCHAR2
DATE VARCHAR2
40
Produced By © Information System Department
Conversion Functions

For expression evaluation, the Oracle Server can


automatically convert the following:

From To
VARCHAR2 or CHAR NUMBER
VARCHAR2 or CHAR DATE

41
Produced By © Information System Department
Using the TO_CHAR Function with
Dates

TO_CHAR(date, 'format_model')

The format model:


• Must be enclosed in single quotation marks and is
case sensitive
• Can include any valid date format element
• Has an fm element to remove padded blanks or
suppress leading zeros
• Is separated from the date value by a comma

42
Produced By © Information System Department
Elements of the Date Format
Model

YYYY Full year in numbers


YEAR Year spelled out
MM Two-digit value for month
MONTH Full name of the month
MON Three-letter abbreviation of the
month
DY Three-letter abbreviation of the day
of the week
DAY Full name of the day of the week
DD Numeric day of the month

43
Produced By © Information System Department
Elements of the Date Format
Model

• Time elements format the time portion of the


date.
HH24:MI:SS AM 15:45:32 PM

• Add character strings by enclosing them in double


quotation marks.
DD "of" MONTH 12 of OCTOBER

• Number suffixes spell out numbers.


ddspth fourteenth

44
Produced By © Information System Department
Using the TO_CHAR Function with
Dates

SELECT last_name,
TO_CHAR(hire_date, 'fmDD Month YYYY') HIREDATE
FROM employees;

45
Produced By © Information System Department
Using the TO_CHAR Function with
Numbers

SELECT TO_CHAR(salary, '$99,999.00') SALARY


FROM employees
WHERE last_name = 'Ernst';

46
Produced By © Information System Department
Using the TO_NUMBER and
TO_DATE Functions

• Convert a character string to a number format


using the TO_NUMBER function:

TO_NUMBER(char[, 'format_model'])

• Convert a character string to a date format using


the TO_DATE function:

TO_DATE(char[, 'format_model'])

47
Produced By © Information System Department
Nesting Functions

• Single-row functions can be nested to any level.


• Nested functions are evaluated from deepest level
to the least deep level.

F3(F2(F1(col,arg1),arg2),arg3)

SELECT last_name,
NVL(TO_CHAR(manager_id), 'No Manager')
FROM employees
WHERE manager_id IS NULL;

48
Produced By © Information System Department
NVL Function

• Converts a null to an actual value


• Data types that can be used are date, character,
and number.
• Data types must match:
– NVL(commission_pct,0)
– NVL(hire_date,'01-JAN-97')
– NVL(job_id,'No Job Yet')

SELECT last_name, salary, NVL(commission_pct, 0),


(salary*12) + (salary*12*NVL(commission_pct, 0)) AN_SAL
FROM employees;

49
Produced By © Information System Department
Conditional Expressions

• Give you the use of IF-THEN-ELSE logic within a


SQL statement.
• Use two methods:
– CASE expression
– DECODE function

50
Produced By © Information System Department
The CASE Expression

Facilitates conditional inquiries by doing the work of


an IF-THEN-ELSE statement:

CASE expr WHEN comparison_expr1 THEN


return_expr1
[WHEN comparison_expr2 THEN return_expr2
WHEN comparison_exprn THEN return_exprn
ELSE else_expr]
END

51
Produced By © Information System Department
The CASE Expression

SELECT last_name, job_id, salary,


CASE job_id WHEN 'IT_PROG' THEN 1.10*salary
WHEN 'ST_CLERK' THEN 1.15*salary
WHEN 'SA_REP' THEN 1.20*salary
ELSE salary END "REVISED_SALARY"
FROM employees;

52
Produced By © Information System Department
The DECODE Function

Facilitates conditional inquiries by doing the work of


a CASE or IF-THEN-ELSE statement:

DECODE(col|expression, search1, result1


[, search2, result2,...,]
[, default])

53
Produced By © Information System Department
The DECODE Function

SELECT last_name, job_id, salary,


DECODE(job_id, 'IT_PROG', 1.10*salary,
'ST_CLERK', 1.15*salary,
'SA_REP', 1.20*salary,
salary)
REVISED_SALARY
FROM employees;

54
Produced By © Information System Department
Obtaining Data from Multiple
Tables

55
Produced By © Information System Department
Cartesian Products

• A Cartesian product is formed when:


– A join condition is omitted
– A join condition is invalid
– All rows in the first table are joined to all rows in
the second table
• To avoid a Cartesian product, always include a
valid join condition in a WHERE clause.

56
Produced By © Information System Department
What Is an Equijoin?

57
Produced By © Information System Department
Retrieving Records with Equijoins

SELECT employees.employee_id,
employees.last_name,
employees.department_id,
departments.department_id,
departments.location_id
FROM employees, departments
WHERE employees.department_id =
departments.department_id;

58
Produced By © Information System Department
Additional Search Conditions
Using the AND Operator

SELECT last_name, employees.department_id,


department_name
FROM employees, departments
WHERE employees.department_id =
departments.department_id
AND last_name = 'Matos';

59
Produced By © Information System Department
Qualifying Ambiguous Column
Names

• Use table prefixes to qualify column names that


are in multiple tables.
• Improve performance by using table prefixes.
• Distinguish columns that have identical names but
reside in different tables by using column aliases.

60
Produced By © Information System Department
Using Table Aliases

• Simplify queries by using table aliases


• Improve performance by using table prefixes

SELECT e.employee_id, e.last_name,


e.department_id,
d.department_id, d.location_id
FROM employees e, departments d
WHERE e.department_id = d.department_id;

61
Produced By © Information System Department
Joining More than Two Tables

To join n tables together, you need a minimum of n-


1
join conditions. For example, to join three tables, a
minimum of two joins is required.

SELECT e.last_name, d.department_name, l.city


FROM employees e, departments d, locations l
WHERE e.department_id = d.department_id
AND d.location_id = l.location_id;

62
Produced By © Information System Department
Nonequijoins

Retrieving Records with Nonequijoins

SELECT e.last_name, e.salary, j.grade_level


FROM employees e, job_grades j
WHERE e.salary BETWEEN j.lowest_sal AND
j.highest_sal;

63
Produced By © Information System Department
Outer Joins

64
Produced By © Information System Department
Outer Joins Syntax

• You use an outer join to also see rows that do not


meet the join condition.
• The outer join operator is the plus sign (+).

SELECT table1.column, table2.column


FROM table1, table2
WHERE table1.column(+) = table2.column;

SELECT table1.column, table2.column


FROM table1, table2
WHERE table1.column = table2.column(+);

65
Produced By © Information System Department
Outer Joins Syntax

SELECT e.last_name, e.department_id,


d.department_name
FROM employees e, departments d
WHERE e.department_id(+) = d.department_id;

66
Produced By © Information System Department
Self Joins

67
Produced By © Information System Department
Joining a Table to Itself

SELECT worker.last_name || ' works for '


|| manager.last_name
FROM employees worker, employees manager
WHERE worker.manager_id = manager.employee_id;

68
Produced By © Information System Department
Group Functions

Group functions operate on sets of rows to give one


result per group.

69
Produced By © Information System Department
Group Functions

• AVG
• COUNT
• MAX
• MIN
• STDDEV
• SUM
• VARIANCE

70
Produced By © Information System Department
Group Functions Syntax

SELECT [column,] group_function(column), ...


FROM table
[WHERE condition]
[GROUP BY column]
[ORDER BY column];

71
Produced By © Information System Department
Using the AVG and SUM
Functions

You can use AVG and SUM for numeric data.

SELECT AVG(salary), MAX(salary),


MIN(salary), SUM(salary)
FROM employees
WHERE job_id LIKE '%REP%';

72
Produced By © Information System Department
Using the MIN and MAX
Functions

You can use MIN and MAX for any data type.

SELECT MIN(hire_date), MAX(hire_date)


FROM employees;

73
Produced By © Information System Department
Using the COUNT Function

COUNT(*) returns the number of rows in a table.


SELECT COUNT(*)
FROM employees
WHERE department_id = 50;
• COUNT(expr) returns the number of rows with
non-null values for the expr.
• Display the number of department values in the
EMPLOYEES table, excluding the null values.
SELECT COUNT(commission_pct)
FROM employees
WHERE department_id = 80;

74
Produced By © Information System Department
Group Functions and Null Values

Group functions ignore null values in the column.


SELECT AVG(commission_pct)
FROM employees;

SELECT AVG(NVL(commission_pct, 0))


FROM employees;

75
Produced By © Information System Department
Creating Groups of Data:
GROUP BY Clause Syntax

SELECT column, group_function(column)


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];

SELECT department_id, AVG(salary)


FROM employees
GROUP BY department_id;

76
Produced By © Information System Department
Grouping by More Than One
Column

SELECT department_id dept_id, job_id, SUM(salary)


FROM employees
GROUP BY department_id, job_id;

77
Produced By © Information System Department
Excluding Group Results: The
HAVING Clause

Use the HAVING clause to restrict groups:


1. Rows are grouped.
2. The group function is applied.
3. Groups matching the HAVING clause are displayed.

SELECT column, group_function


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];

78
Produced By © Information System Department
Excluding Group Results: The
HAVING Clause

SELECT department_id, MAX(salary)


FROM employees
GROUP BY department_id
HAVING MAX(salary)>10000;

79
Produced By © Information System Department
Nesting Group Functions

Display the maximum average salary.

SELECT MAX(AVG(salary))
FROM employees
GROUP BY department_id;

80
Produced By © Information System Department
Using a Subquery to Solve a
Problem

81
Produced By © Information System Department
Subquery Syntax

SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);

• The subquery (inner query) executes once before


the main query.
• The result of the subquery is used by the main
query (outer query).

82
Produced By © Information System Department
Using a Subquery

SELECT last_name
FROM employees
WHERE salary >
(SELECT salary
FROM employees
WHERE last_name = 'Abel');

83
Produced By © Information System Department
Guidelines for Using Subqueries

• Enclose subqueries in parentheses.


• Place subqueries on the right side of the
comparison condition.
• The ORDER BY clause in the subquery is not
needed unless you are performing top-n analysis.
• Use single-row operators with single-row
subqueries and use multiple-row operators with
multiple-row subqueries.

84
Produced By © Information System Department
Types of Subqueries

85
Produced By © Information System Department
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

86
Produced By © Information System Department
Executing Single-Row Subqueries

87
Produced By © Information System Department
The HAVING Clause with
Subqueries

• The Oracle Server executes subqueries first.


• The Oracle Server returns results into the HAVING
clause of the main query.

SELECT department_id, MIN(salary)


FROM employees
GROUP BY department_id
HAVING MIN(salary) >
(SELECT MIN(salary)
FROM employees
WHERE department_id = 50);

88
Produced By © Information System Department
Multiple-Row Subqueries

• Return more than one row


• Use multiple-row comparison operators

Operator Meaning
IN Equal to any member in the list
ANY Compare value to each value
returned by the
subquery
ALL Compare value to every value
returned by the
subquery

89
Produced By © Information System Department
Multiple-Row Subqueries

SELECT employee_id, last_name, job_id, salary


FROM employees
WHERE salary < ANY
(SELECT salary
FROM employees
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';

90
Produced By © Information System Department
Null Values in a Subquery

SELECT emp.last_name
FROM employees emp
WHERE emp.employee_id NOT IN
(SELECT mgr.manager_id
FROM employees mgr);
no rows selected

91
Produced By © Information System Department
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.

92
Produced By © Information System Department
The INSERT Statement Syntax

• Add new rows to a table by using the INSERT


statement.
• Only one row is inserted at a time with this
syntax.

INSERT INTO table [(column [, column...])]


VALUES (value [, value...]);

93
Produced By © Information System Department
Inserting 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.
• Enclose character and date values within single
quotation marks.

INSERT INTO departments(department_id,


department_name,
manager_id, location_id)
VALUES (70, 'Public Relations', 100, 1700);

94
Produced By © Information System Department
Inserting Rows with Null Values

• Implicit method: Omit the column from the column


list.
INSERT INTO departments (department_id,
department_name )
VALUES (30, 'Purchasing');

• Explicit method: Specify the NULL keyword in the


VALUES clause.

. INSERT INTO departments


VALUES (100, 'Finance', NULL, NULL);

95
Produced By © Information System Department
Copying Rows from Another
Table

• Write your INSERT statement with a subquery.


• Do not use the VALUES clause.
• Match the number of columns in the INSERT
clause to those in the subquery.

INSERT INTO sales_reps(id, name, salary,


commission_pct)
SELECT employee_id, last_name, salary,
commission_pct
FROM employees
WHERE job_id LIKE '%REP%';

96
Produced By © Information System Department
The UPDATE Statement Syntax

• Modify existing rows with the UPDATE statement.


• Update more than one row at a time, if required.

UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];

97
Produced By © Information System Department
The UPDATE Statement Syntax

• Specific row or rows are modified if you specify


the WHERE clause
UPDATE employees
SET department_id = 70
WHERE employee_id = 113;
• All rows in the table are modified if you omit the
WHERE clause.

UPDATE copy_emp
SET department_id = 110;

98
Produced By © Information System Department
Updating Two Columns with a
Subquery

Update employee 114’s job and department to match


that of employee 205.
UPDATE employees
SET job_id = (SELECT job_id
FROM employees
WHERE employee_id = 205),
salary = (SELECT salary
FROM employees
WHERE employee_id = 205)
WHERE employee_id = 114;
1 row updated.

99
Produced By © Information System Department
The DELETE Statement

You can remove existing rows from a table by using


the DELETE statement.

DELETE [FROM] table


[WHERE condition];

100
Produced By © Information System Department
Deleting Rows from a Table

• Specific rows are deleted if you specify the WHERE


clause.

DELETE FROM departments


WHERE department_name = 'Finance';
1 row deleted.
• All rows in the table are deleted if you omit the
WHERE clause.

DELETE FROM copy_emp;


22 rows deleted.

101
Produced By © Information System Department
Database Transactions

A database transaction consists of one of the


following:

• DML statements which constitute one consistent


change to the data
• One DDL statement
• One DCL statement

102
Produced By © Information System Department
Implicit Transaction Processing

• An automatic commit occurs under the following


circumstances:
– DDL statement is issued
– DCL statement is issued
– Normal exit from iSQL*Plus, without explicitly
issuing COMMIT or ROLLBACK statements
• An automatic rollback occurs under an abnormal
termination of iSQL*Plus or a system failure.

103
Produced By © Information System Department
Committing Data

• Make the changes.


DELETE FROM employees
WHERE employee_id = 99999;
1 row deleted.
INSERT INTO departments
VALUES (290, 'Corporate Tax', NULL, 1700);
1 row inserted.

• Commit the changes.


COMMIT;
Commit complete.

104
Produced By © Information System Department
ROLLBACK

Discard all pending changes by using the ROLLBACK


statement:

• Data changes are undone.


• Previous state of the data is restored.
• Locks on the affected rows are released.

ROLLBACK ;

105
Produced By © Information System Department
Controlling Transactions

106
Produced By © Information System Department
Rolling Back Changes to a Marker

• Create a marker in a current transaction by using


the SAVEPOINT statement.
• Roll back to that marker by using the ROLLBACK
TO SAVEPOINT statement.

UPDATE...
SAVEPOINT update_done;
Savepoint created.
INSERT...
ROLLBACK TO update_done;
Rollback complete.

107
Produced By © Information System Department
Locking

In an Oracle database, locks:


• Prevent destructive interaction between
concurrent transactions
• Require no user action
• Use the lowest level of restrictiveness
• Are held for the duration of the transaction
• Are of two types: explicit locking and implicit
locking

108
Produced By © Information System Department
Implicit Locking

• Two lock modes:


– Exclusive: Locks out other users
– Share: Allows other users to access the server

• High level of data concurrency:


– DML: Table share, row exclusive
– Queries: No locks required
– DDL: Protects object definitions

• Locks held until commit or rollback

109
Produced By © Information System Department
Data Definition Language DDL

Statement Description

Create Create Database Object


Alter Change Definition of Database Object
Drop Removes the Definition of Database
Objects
Rename Rename the Database Object
TruncateTruncate the table

110
Produced By © Information System Department
Database Objects

Object Description

Table Basic unit of storage; composed


of rows and columns
View Logically represents subsets of
data from one or more tables
Sequence Numeric value generator
Index Improves the performance of
some queries
Synonym Gives alternative names to
objects

111
Produced By © Information System Department
Naming Rules

Table names and column names:


• Must begin with a letter
• Must be 1 to 30 characters long
• Must contain only A–Z, a–z, 0–9, _, $, and #
• Must not duplicate the name of another object
owned by the same user
• Must not be an Oracle Server reserved word

112
Produced By © Information System Department
The CREATE TABLE Statement

• You must have:


– CREATE TABLE privilege
– A storage area

CREATE TABLE [schema.]table


(column datatype [DEFAULT expr][, ...]);

• You specify:
– Table name
– Column name, column data type, and column size

113
Produced By © Information System Department
Creating Tables

• Create the table.

CREATE TABLE dept


(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13));
Table created.

• Confirm creation of the table.


DESCRIBE dept

114
Produced By © Information System Department
Tables in the Oracle Database

• User tables:
– Are a collection of tables created and maintained
by the user
– Contain user information

• Data dictionary:
– Is a collection of tables created and maintained by
the Oracle Server
– Contain database information

115
Produced By © Information System Department
Querying the Data Dictionary

Prefix Description
USER_ These views contain information about
objects owned by the user.
ALL_ These views contain information about all
of the tables (object tables and relational
tables) accessible to the user.
DBA_ These views are restricted views, which
can be accessed only by people who have
been assigned the DBA role.
V$ These views are dynamic performance
views, database server
performance, memory, and locking.
116
Produced By © Information System Department
Data Types

Data Type Description

VARCHAR2(size) Variable-length character data


CHAR[(size)] Fixed-length character data
NUMBER[(p,s)] Variable-length numeric data
DATE Date and time values
LONG Variable-length character data up
to 2 gigabytes
CLOB Character data up to 4 gigabytes

117
Produced By © Information System Department
Data Types

RAW and LONG RAW Raw binary data


BLOB Binary data up to 4 gigabytes
BFILE Binary data stored in an external
file; up to 4 gigabytes
ROWID Hexadecimal string representing
the unique address of a row in
its table

118
Produced By © Information System Department
Creating a Table by Using a
Subquery Syntax

• Create a table and insert rows by combining the


CREATE TABLE statement and the AS subquery option.

CREATE TABLE table


[(column, column...)]
AS subquery;

• Match the number of specified columns to the


number of subquery columns.
• Define columns with column names and default
values.

119
Produced By © Information System Department
Creating a Table by Using a
Subquery Syntax

CREATE TABLE dept80


AS
SELECT employee_id, last_name,
salary*12 ANNSAL,
hire_date
FROM employees
WHERE department_id = 80;
Table created.

DESCRIBE dept80

120
Produced By © Information System Department
The ALTER TABLE Statement

Use the ALTER TABLE statement to:


• Add a new column
• Modify an existing column
• Define a default value for the new column
• Drop a column

121
Produced By © Information System Department
The ALTER TABLE Statement

Use the ALTER TABLE statement to add, modify or drop


columns.
ALTER TABLE table
ADD (column datatype [DEFAULT expr]
[, column datatype]...);

ALTER TABLE table


MODIFY (column datatype [DEFAULT expr]
[, column datatype]...);

ALTER TABLE table


DROP (column);

122
Produced By © Information System Department
Adding a Column

• Use the ADD clause to add columns.


ALTER TABLE dept80
ADD (job_id VARCHAR2(9));
Table altered.

123
Produced By © Information System Department
Modifying a Column

• You can change a column’ s data type, size, and


default value.
• A change to the default value affects only
subsequent insertions to the table.
ALTER TABLE dept80
MODIFY (last_name VARCHAR2(30));
Table altered.

124
Produced By © Information System Department
Dropping a Column

Use the DROP COLUMN clause to drop columns you


no longer need from the table.
ALTER TABLE dept80
DROP COLUMN job_id;
Table altered.

125
Produced By © Information System Department
Dropping a Table

• All data and structure in the table is deleted.


• Any pending transactions are committed.
• All indexes are dropped.
• You cannot roll back the DROP TABLE statement.
DROP TABLE dept80;
Table dropped.

126
Produced By © Information System Department
Changing the Name of an Object

• To change the name of a table, view, sequence, or


synonym, execute the RENAME statement.
• You must be the owner of the object.
RENAME dept TO detail_dept;
Table renamed.

127
Produced By © Information System Department
Truncating a Table

• The TRUNCATE TABLE statement:


– Removes all rows from a table
– Releases the storage space used by that table
• You cannot roll back row removal when using
TRUNCATE.
• Alternatively, you can remove rows by using the
DELETE statement.
TRUNCATE TABLE detail_dept;
Table truncated.

128
Produced By © Information System Department
What Are 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

129
Produced By © Information System Department
Data Integrity Constraints

Constraint Description
NOT NULL Specifies that the column cannot
contain a null value
UNIQUE Specifies a column or combination of
columns whose values must be unique
for all rows in the table
PRIMARY KEY Uniquely identifies each row of the
table
FOREIGN KEY Establishes and enforces a foreign
key relationship between the column
and a column of the referenced table
CHECK Specifies a condition that must be true

130
Produced By © Information System Department
Defining Constraints

CREATE TABLE [schema.]table


(column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint][,...]);
CREATE TABLE employees(
employee_id NUMBER(6),
first_name VARCHAR2(20),
...
job_id VARCHAR2(10) NOT NULL,
CONSTRAINT emp_emp_id_pk
PRIMARY KEY (EMPLOYEE_ID));

131
Produced By © Information System Department
Adding a Constraint Syntax

Use the ALTER TABLE statement to:


• Add or drop a constraint, but not modify its
structure
• Enable or disable constraints
• Add a NOT NULL constraint by using the MODIFY
clause
ALTER TABLE table
ADD [CONSTRAINT constraint] type (column);

132
Produced By © Information System Department
Dropping a Constraint

• Remove the manager constraint from the EMPLOYEES


table.
• Remove the PRIMARY KEY constraint on the
DEPARTMENTS table and drop the associated
FOREIGN KEY constraint on the
EMPLOYEES.DEPARTMENT_ID column.
ALTER TABLE employees
DROP CONSTRAINT emp_manager_fk;
Table altered.
ALTER TABLE departments
DROP PRIMARY KEY CASCADE;
Table altered.

133
Produced By © Information System Department
Controlling User Access

• Database security:
– System security
– Data security
• System privileges: Gaining access to the database
• Object privileges: Manipulating the content of the
database objects
• Schemas: Collections of objects, such as tables,
views, and sequences

134
Produced By © Information System Department
Creating Users

CREATE USER user


IDENTIFIED BY password;

CREATE USER scott


IDENTIFIED BY tiger;
User created.

135
Produced By © Information System Department
User System Privileges

• Once a user is created, the DBA can grant system


privileges to a user.
• An application developer, for example,
the following system privileges:
– CREATE SESSION
– CREATE TABLE
– CREATE SEQUENCE
– CREATE VIEW
– CREATE PROCEDURE
GRANT privilege [, privilege...]
TO user [, user| role, PUBLIC...];
136
Produced By © Information System Department
Granting System Privileges

The DBA can grant a user specific system privileges.

GRANT create session, create table,


create sequence, create view
TO scott;
Grant succeeded.

137
Produced By © Information System Department
Object Privileges

Object
Privilege Table View Sequence Procedure
ALTER ÷ ÷
DELETE ÷ ÷
EXECUTE ÷
INDEX ÷
INSERT ÷ ÷
REFERENCES ÷ ÷
SELECT ÷ ÷ ÷
UPDATE ÷ ÷

138
Produced By © Information System Department
Object Privileges

• Object privileges vary from object to object.


• An owner has all the privileges on the object.
• An owner can give specific privileges on that
owner’ s object.

GRANT object_priv [(columns)]


ON object
TO {user|role|PUBLIC}
[WITH GRANT OPTION];

139
Produced By © Information System Department
Granting Object Privileges

• Grant query privileges on the EMPLOYEES table.


GRANT select
ON employees
TO sue, rich;
Grant succeeded.
• Grant privileges to update specific columns to
users and roles.
GRANT update (department_name, location_id)
ON departments
TO scott, manager;
Grant succeeded.

140
Produced By © Information System Department
How to Revoke Object Privileges

• You use the REVOKE statement to revoke


privileges
granted to other users.
• Privileges granted to others through the WITH
GRANT OPTION clause are also revoked.

REVOKE {privilege [, privilege...]|ALL}


ON object
FROM {user[, user...]|role|PUBLIC}
[CASCADE CONSTRAINTS];

141
Produced By © Information System Department
Revoking Object Privileges

As user Alice, revoke the SELECT and INSERT


privileges given to user Scott on the DEPARTMENTS
table.

REVOKE select, insert


ON departments
FROM scott;
Revoke succeeded.

142
Produced By © Information System Department

You might also like