142
Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer ,Information System Department

Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Embed Size (px)

Citation preview

Page 1: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Introduction to SQL

1

Mr. Anser GhazzaalLecturer ,Information System Department

Page 2: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 3: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 4: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 5: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Data Models

5

Page 6: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Entity Relationship Model

• Create an entity relationship diagram frombusiness specifications or narratives

6

Page 7: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Entity Relationship Model

• Scenario– “. . . Assign one or more employees to adepartment . . .”– “. . . Some departments do not yet haveassigned employees . . .”

7

Page 8: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 9: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Relational Database Properties

A relational database:• Can be accessed and modified by executingstructured query language (SQL) statements• Contains a collection of tables with no physical

pointers• Uses a set of operators

9

Page 10: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Plugging into the Grid

Grid computing is:Software infrastructure that uses low-cost servers

and modular storage to:Balance workloadsProvide capacity on demand

Made possible by innovations in hardwarePowered by software

10

Page 11: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Oracle Enterprise Grid Computing

Oracle’s grid infrastructure products:Oracle Database 10gOracle Application Server 10gOracle Enterprise Manager 10g

Grid Control

11

Page 12: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Oracle 10g Products and Forms Development

12

Forms Services Forms Developer

Page 13: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

SQL Statements

Data retrieval SELECT

Data manipulation language (DML)INSERTUPDATEDELETE

13

Page 14: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

SQL Statements

Data definition language (DDL)CREATEALTERDROPRENAMETRUNCATE

Transaction controlCOMMITROLLBACKSAVEPOINT

14

Page 15: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

SQL Statements

Controlling User Access

• GRANT

• REVOKE

15

Page 16: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 17: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Basic SELECT Statement

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

FROM table;

• SELECT identifies what columns • FROM identifies which table

17

Page 18: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Selecting All Columns

SELECT *FROM departments;

18

Page 19: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Selecting Specific Columns

SELECT department_id, location_idFROM departments;

19

Page 20: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department20

Arithmetic Expressions

Create expressions with number and date data byusing arithmetic operators.

Operator Description+ Add- Subtract* Multiply/ Divide

Page 21: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 22: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Using Arithmetic Operators

SELECT last_name, salary, salary + 300FROM employees;

22

Page 23: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 24: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 25: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 26: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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_idFROM employeesWHERE last_name = 'Goyal';

26

Page 27: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Duplicate Rows

The default display of queries is all rows, includingduplicate rows.SELECT department_idFROM employees;

Eliminate duplicate rows by using the DISTINCTkeyword in the SELECT clause.SELECT DISTINCT department_idFROM employees;

27

Page 28: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Limiting the Rows Selected

Restrict the rows returned by using the WHEREclause.• 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

Page 29: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 30: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Using Comparison Conditions

SELECT last_name, salaryFROM employeesWHERE salary <= 3000;

30

Page 31: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Other Comparison Conditions

Operator MeaningBETWEEN...AND...IN(set)LIKEIS NULL

Between two values (inclusive)Match any of a list of valuesMatch a character patternIs a null value

31

Page 32: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

expressionfunction_name [(arg1, arg2,...)]

32

Page 33: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Character Functions

Case Manipulation FunctionsThese functions convert case for character strings.

Function Result

LOWER('SQL Course') sql courseUPPER('SQL Course') SQL COURSEINITCAP('SQL Course') Sql Course

33

Page 34: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Character Manipulation Functions

These functions manipulate character strings:

Function Result

CONCAT('Hello', 'World') HelloWorldSUBSTR('HelloWorld',1,5) HelloLENGTH('HelloWorld') 10INSTR('HelloWorld', 'W') 6LPAD(salary,10,'*') *****24000RPAD(salary, 10, '*') 24000*****TRIM('H' FROM 'HelloWorld') elloWorld

34

Page 35: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Number Functions

• ROUND: Rounds value to specified decimalROUND(45.926, 2) 45.93• TRUNC: Truncates value to specified decimalTRUNC(45.926, 2) 45.92• MOD: Returns remainder of divisionMOD(1600, 300) 100

35

Page 36: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Working with Dates

• Oracle database stores dates in an internalnumeric format: century, year, month, day, hours,

minutes, seconds.• The default date display format is DD-MON-RR.

SELECT last_name, hire_dateFROM employeesWHERE last_name like 'G%';

36

Page 37: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Arithmetic with Dates

• Add or subtract a number to or from a date for aresultant date value.• Subtract two dates to find the number of daysbetween those dates.• Add hours to a date by dividing the number ofhours by 24.

37

Page 38: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 39: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 monthROUND Round dateTRUNC Truncate date

39

Page 40: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 NUMBERVARCHAR2 or CHAR DATENUMBER VARCHAR2DATE VARCHAR2

40

Page 41: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Conversion Functions

For expression evaluation, the Oracle Server canautomatically convert the following:

From ToVARCHAR2 or CHAR NUMBERVARCHAR2 or CHAR DATE

41

Page 42: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 43: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Elements of the Date Format Model

YYYY Full year in numbersYEAR Year spelled outMM Two-digit value for monthMONTH Full name of the monthMON Three-letter abbreviation of the

monthDY Three-letter abbreviation of the day

of the weekDAY Full name of the day of the weekDD Numeric day of the month

43

Page 44: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 45: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Using the TO_CHAR Function with Dates

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

45

Page 46: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Using the TO_CHAR Function with Numbers

SELECT TO_CHAR(salary, '$99,999.00') SALARYFROM employeesWHERE last_name = 'Ernst';

46

Page 47: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 48: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Nesting Functions

• Single-row functions can be nested to any level.• Nested functions are evaluated from deepest levelto the least deep level.

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

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

48

Page 49: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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_SALFROM employees;

49

Page 50: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Conditional Expressions

• Give you the use of IF-THEN-ELSE logic within aSQL statement.

• Use two methods:– CASE expression– DECODE function

50

Page 51: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

The CASE Expression

Facilitates conditional inquiries by doing the work ofan IF-THEN-ELSE statement:

CASE expr WHEN comparison_expr1 THEN return_expr1

[WHEN comparison_expr2 THEN return_expr2WHEN comparison_exprn THEN return_exprnELSE else_expr]END

51

Page 52: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

The CASE Expression

SELECT last_name, job_id, salary,CASE job_id WHEN 'IT_PROG' THEN 1.10*salaryWHEN 'ST_CLERK' THEN 1.15*salaryWHEN 'SA_REP' THEN 1.20*salaryELSE salary END "REVISED_SALARY"FROM employees;

52

Page 53: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

The DECODE Function

Facilitates conditional inquiries by doing the work ofa CASE or IF-THEN-ELSE statement:

DECODE(col|expression, search1, result1[, search2, result2,...,][, default])

53

Page 54: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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_SALARYFROM employees;

54

Page 55: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Obtaining Data from Multiple Tables

55

Page 56: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 avalid join condition in a WHERE clause.

56

Page 57: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

What Is an Equijoin?

57

Page 58: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Retrieving Records with Equijoins

SELECT employees.employee_id, employees.last_name,

employees.department_id, departments.department_id,

departments.location_idFROM employees, departmentsWHERE employees.department_id =

departments.department_id;

58

Page 59: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Additional Search Conditions Using the AND Operator

SELECT last_name, employees.department_id,department_nameFROM employees, departmentsWHERE employees.department_id =

departments.department_idAND last_name = 'Matos';

59

Page 60: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Qualifying Ambiguous Column Names

• Use table prefixes to qualify column names thatare in multiple tables.• Improve performance by using table prefixes.• Distinguish columns that have identical names butreside in different tables by using column aliases.

60

Page 61: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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_idFROM employees e, departments dWHERE e.department_id = d.department_id;

61

Page 62: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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, aminimum of two joins is required.

SELECT e.last_name, d.department_name, l.cityFROM employees e, departments d, locations lWHERE e.department_id = d.department_idAND d.location_id = l.location_id;

62

Page 63: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Nonequijoins

Retrieving Records with Nonequijoins

SELECT e.last_name, e.salary, j.grade_levelFROM employees e, job_grades jWHERE e.salary BETWEEN j.lowest_sal AND

j.highest_sal;

63

Page 64: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Outer Joins

64

Page 65: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Outer Joins Syntax

• You use an outer join to also see rows that do notmeet the join condition.• The outer join operator is the plus sign (+).

SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column(+) = table2.column;

SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column = table2.column(+);

65

Page 66: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Outer Joins Syntax

SELECT e.last_name, e.department_id, d.department_name

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

66

Page 67: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Self Joins

67

Page 68: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Joining a Table to Itself

SELECT worker.last_name || ' works for '|| manager.last_nameFROM employees worker, employees managerWHERE worker.manager_id = manager.employee_id;

68

Page 69: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Group Functions

Group functions operate on sets of rows to give oneresult per group.

69

Page 70: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Group Functions

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

70

Page 71: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Group Functions Syntax

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

71

Page 72: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 employeesWHERE job_id LIKE '%REP%';

72

Page 73: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 74: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Using the COUNT Function

COUNT(*) returns the number of rows in a table.SELECT COUNT(*)FROM employeesWHERE 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 employeesWHERE department_id = 80;

74

Page 75: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 76: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 employeesGROUP BY department_id;

76

Page 77: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Grouping by More Than One Column

SELECT department_id dept_id, job_id, SUM(salary)FROM employeesGROUP BY department_id, job_id;

77

Page 78: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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_functionFROM table[WHERE condition][GROUP BY group_by_expression][HAVING group_condition][ORDER BY column];

78

Page 79: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Excluding Group Results: The HAVING Clause

SELECT department_id, MAX(salary)FROM employeesGROUP BY department_idHAVING MAX(salary)>10000;

79

Page 80: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Nesting Group Functions

Display the maximum average salary.

SELECT MAX(AVG(salary))FROM employeesGROUP BY department_id;

80

Page 81: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Using a Subquery to Solve a Problem

81

Page 82: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Subquery Syntax

SELECT select_listFROM tableWHERE expr operator

(SELECT select_listFROM table);

• The subquery (inner query) executes once beforethe main query.• The result of the subquery is used by the mainquery (outer query).

82

Page 83: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Using a Subquery

SELECT last_nameFROM employeesWHERE salary >

(SELECT salaryFROM employeesWHERE last_name = 'Abel');

83

Page 84: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Guidelines for Using Subqueries

• Enclose subqueries in parentheses.• Place subqueries on the right side of thecomparison condition.• The ORDER BY clause in the subquery is notneeded unless you are performing top-n analysis.• Use single-row operators with single-rowsubqueries and use multiple-row operators withmultiple-row subqueries.

84

Page 85: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Types of Subqueries

85

Page 86: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 87: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Executing Single-Row Subqueries

87

Page 88: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

The HAVING Clause with Subqueries

• The Oracle Server executes subqueries first.• The Oracle Server returns results into the HAVINGclause of the main query.

SELECT department_id, MIN(salary)FROM employeesGROUP BY department_idHAVING MIN(salary) >

(SELECT MIN(salary)FROM employeesWHERE department_id = 50);

88

Page 89: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Multiple-Row Subqueries

• Return more than one row• Use multiple-row comparison operators

Operator MeaningIN Equal to any member in the listANY Compare value to each value

returned by the subquery

ALL Compare value to every value returned by the

subquery

89

Page 90: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Multiple-Row Subqueries

SELECT employee_id, last_name, job_id, salaryFROM employeesWHERE salary < ANY(SELECT salaryFROM employeesWHERE job_id = 'IT_PROG')AND job_id <> 'IT_PROG';

90

Page 91: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Null Values in a Subquery

SELECT emp.last_nameFROM employees empWHERE emp.employee_id NOT IN(SELECT mgr.manager_idFROM employees mgr);no rows selected

91

Page 92: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 DMLstatements that form a logical unit of work.

92

Page 93: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

The INSERT Statement Syntax

• Add new rows to a table by using the INSERTstatement.• Only one row is inserted at a time with this

syntax.

INSERT INTO table [(column [, column...])]VALUES (value [, value...]);

93

Page 94: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 95: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 departmentsVALUES (100, 'Finance', NULL, NULL);

95

Page 96: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 INSERTclause to those in the subquery.

INSERT INTO sales_reps(id, name, salary, commission_pct)

SELECT employee_id, last_name, salary, commission_pct

FROM employeesWHERE job_id LIKE '%REP%';

96

Page 97: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 tableSET column = value [, column = value, ...][WHERE condition];

97

Page 98: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

The UPDATE Statement Syntax

• Specific row or rows are modified if you specify the WHERE clause

UPDATE employeesSET department_id = 70WHERE employee_id = 113;• All rows in the table are modified if you omit the

WHERE clause.

UPDATE copy_empSET department_id = 110;

98

Page 99: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Updating Two Columns with a Subquery

Update employee 114’s job and department to matchthat of employee 205.UPDATE employees

SET job_id = (SELECT job_idFROM employeesWHERE employee_id = 205),

salary = (SELECT salaryFROM employeesWHERE employee_id = 205)

WHERE employee_id = 114;1 row updated.

99

Page 100: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

The DELETE Statement

You can remove existing rows from a table by usingthe DELETE statement.

DELETE [FROM] table[WHERE condition];

100

Page 101: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Deleting Rows from a Table

• Specific rows are deleted if you specify the WHERE clause.

DELETE FROM departmentsWHERE 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

Page 102: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 103: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 abnormaltermination of iSQL*Plus or a system failure.

103

Page 104: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Committing Data

• Make the changes.DELETE FROM employeesWHERE employee_id = 99999;1 row deleted.INSERT INTO departmentsVALUES (290, 'Corporate Tax', NULL, 1700);1 row inserted.

• Commit the changes.COMMIT;Commit complete.

104

Page 105: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

ROLLBACK

Discard all pending changes by using the ROLLBACKstatement:

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

ROLLBACK ;

105

Page 106: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Controlling Transactions

106

Page 107: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Rolling Back Changes to a Marker

• Create a marker in a current transaction by usingthe SAVEPOINT statement.• Roll back to that marker by using the ROLLBACKTO SAVEPOINT statement.

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

107

Page 108: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 109: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 110: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Data Definition Language DDL

Statement Description

Create Create Database ObjectAlter Change Definition of Database ObjectDrop Removes the Definition of Database

ObjectsRename Rename the Database ObjectTruncateTruncate the table

110

Page 111: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 generatorIndex Improves the performance of

some queriesSynonym Gives alternative names to

objects

111

Page 112: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 113: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 114: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 115: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 116: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Querying the Data Dictionary

Prefix DescriptionUSER_ 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

Page 117: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Data Types

Data Type Description

VARCHAR2(size) Variable-length character dataCHAR[(size)] Fixed-length character dataNUMBER[(p,s)] Variable-length numeric dataDATE Date and time valuesLONG Variable-length character data up

to 2 gigabytesCLOB Character data up to 4 gigabytes

117

Page 118: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Data Types

RAW and LONG RAW Raw binary dataBLOB Binary data up to 4 gigabytesBFILE Binary data stored in an external

file; up to 4 gigabytesROWID Hexadecimal string representing

the unique address of a row in its table

118

Page 119: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 120: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Creating a Table by Using a Subquery Syntax

CREATE TABLE dept80ASSELECT employee_id, last_name,salary*12 ANNSAL,hire_dateFROM employeesWHERE department_id = 80;Table created.

DESCRIBE dept80

120

Page 121: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 122: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

The ALTER TABLE Statement

Use the ALTER TABLE statement to add, modify or drop columns.

ALTER TABLE tableADD (column datatype [DEFAULT expr][, column datatype]...);

ALTER TABLE tableMODIFY (column datatype [DEFAULT expr][, column datatype]...);

ALTER TABLE tableDROP (column);

122

Page 123: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Adding a Column

• Use the ADD clause to add columns.ALTER TABLE dept80ADD (job_id VARCHAR2(9));Table altered.

123

Page 124: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 dept80MODIFY (last_name VARCHAR2(30));Table altered.

124

Page 125: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 dept80DROP COLUMN job_id; Table altered.

125

Page 126: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 127: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 128: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 129: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 130: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 131: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 132: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

clauseALTER TABLE tableADD [CONSTRAINT constraint] type (column);

132

Page 133: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 employeesDROP CONSTRAINT emp_manager_fk;Table altered.ALTER TABLE departmentsDROP PRIMARY KEY CASCADE;Table altered.

133

Page 134: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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

Page 135: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Creating Users

CREATE USER userIDENTIFIED BY password;

CREATE USER scottIDENTIFIED BY tiger;User created.

135

Page 136: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 PROCEDUREGRANT privilege [, privilege...]TO user [, user| role, PUBLIC...];

136

Page 137: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 viewTO scott;Grant succeeded.

137

Page 138: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Object Privileges

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

138

Page 139: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 objectTO {user|role|PUBLIC}[WITH GRANT OPTION];

139

Page 140: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Granting Object Privileges

• Grant query privileges on the EMPLOYEES table.GRANT selectON employeesTO sue, rich;Grant succeeded.• Grant privileges to update specific columns to users and roles. GRANT update (department_name, location_id)ON departmentsTO scott, manager;Grant succeeded.

140

Page 141: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

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 objectFROM {user[, user...]|role|PUBLIC}[CASCADE CONSTRAINTS];

141

Page 142: Produced By © Information System Department Introduction to SQL 1 Mr. Anser Ghazzaal Lecturer,Information System Department

Produced By © Information System Department

Revoking Object Privileges

As user Alice, revoke the SELECT and INSERTprivileges given to user Scott on the DEPARTMENTS

table.

REVOKE select, insertON departmentsFROM scott;Revoke succeeded.

142