Professional Documents
Culture Documents
Theory
3130703 DBMS
Rule 9. Logical Data Independence: how data is viewed should not be changed when the
logical structure (Table’s Structure) of database changes. this rule is particularly
difficult to satisfy. Or Application programs and terminal activities remain logically
unimpaired when information preserving changes of any kind that theoretically
permit impairment are made to the base tables.
Rule 10. Integrity Independence: Integrity constraints specific to a particular relational
database must be definable in the relational data sublanguage and storable in the
catalog, not in the application programs.
Rule 11. Distribution Independence: The data manipulation sublanguage of a relational
DBMS must enable application programs and terminal activities to remain logically
unimpaired whether and whenever data are physically centralized or distributed.
Rule 12. Non subversion Rule: If a relational system has or supports a low-level (single-
record-at-a-time) language, that low-level language cannot be used to subvert or
bypass the integrity rules or constraints expressed in the higher-level (multiple-
records-at-a-time) relational language.
Table 1: Comparison of DBMS v/s RDBMS
DBMS RDBMS
In DBMS relationship between two tables In RDBMS relationship between two tables
or files are maintained programmatically. or files can be specified at the time of table
creation
DBMS does not support client/server Most of RDBMS support client/server
architecture. architecture.
DBMS does not support Distributed Most of RDBMS support Distributed
Database. Database.
In DBMS there is no security of Data. In RDBMS there are multiple levels of
Security. Logging in at OS level, Command
level, Object level.
DBMS may satisfy less than 7 or 8 rules of RDBMS may satisfy more than 7 or 8 rules
Dr.E.F.Codd. of Dr.E.F.Codd.
It support single user only It supports multiple user.
FoxPro, IMS are Examples SQL-Server, Oracle are examples
Introduction to SQL
SQL is a language that provides an interface to relational database systems. The language
developed by IBM in 1970 to manipulate the data stores within codd’s model was originally
called structured English Query Language (SEQUEL) with the word English later begin
dropped in favourStructured Query Language (SQL).
In almost all relational databases, data is accessed through SQL. SQL allows you to
SELECT your data, INSERT new records, UPDATE existing records and DELETE records
you want to get rid of. SQL can be embedded in other languages or you can run scripts of SQL
directly against the database.
Features of SQL:
• SQL can be used by a range of users, including those with little or no programming
experience.
• It is a non-procedural language.
• It reduces the amount of time required for creating and maintaining systems.
• It is English like language.
Features of SQL * PLUS:
• SQL *PLUS is an oracle tool that recognizes and submit statement to oracle server for
execution.
• It accepts ad hoc entry of statements.
• It accepts SQL input from files.
• It provides line editor for modifying SQL statement.
• It controls environment settings.
• It formats query results into basic reports.
• It accesses local and remote databases.
Table 2: Comparison of SQL v/s SQL*PLUS
SQL SQL * PLUS
It is a language for communicating with the It recognizes SQL statement and send them to
oracle server to access data. the server.
It is based on American National standards It is the oracle proprietary interface for
Institute (ANSI) standard SQL. executing SQL statements.
SQL manipulate data and table definition in It does not allow manipulation of values in the
the database. database.
SQL is entered into SQL buffer on one or SQL * PLUS is entered one line at a time, not
more lines stored in SQL buffer.
SQL does not have a continuation character. SQL * PLUS uses a dash (-) as a continuation
character if the command is longer than one
line.
SQL uses a termination character to execute It does not require termination characters;
commands immediately. executing commands immediately.
Components of SQL
• DDL (Data Definition Language): CREATE, ALTER, DROP, TRUNCATE,
COMMENT, GRANT, REVOKE
• DML (Data Manipulation Language): INSERT, UPDATE, DELETE, CALL,
EXPLAIN PLAN, LOCK
• DCL (Data Control Language): COMMIT, SAVEPOINT, ROLLBACK, SET
TRANSACTION, GRANT/REVOKE
• DQL (Data Query Language): SELECT
DDL: it is a set of SQL commands used to create, modify and delete database structure but not
data.
3130703 DBMS
DML: It is the area of SQL that allows changing data within the database.
DCL: it is component of SQL statement that control access to data and to the database.
DQL: it is the component of SQL statement that allows getting data from the database and
imposing ordering upon it.
Database Objects
An Oracle Database can contain multiple data structures. Each structure should be outlined in
the database design so that it can be created during the build stage of database development.
• Table: Stores data
• View: Subset of data from one or more tables
• Sequence: Generates numeric values
• Index: Improves the performance of some queries
• Synonym: Gives alternative names to objects
Naming Rules for table name
• Table names and column names must begin with a letter and be 1-30 characters long.
• Names must contain only the characters A-Z, a-z, 0-9, _ (underscore), $, and # (legal
characters, but their use is discouraged).
• Names must not duplicate the name of another object owned by the same Oracle server
user.
• Names must not be an Oracle server-reserved word.
Note: Names are case-insensitive. For example, EMPLOYEES is treated as the same
name as eMPloyees or eMpLOYEES.
Update employee 114’s job and salary 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;
• SELECT: It selects data from table.
Syntax: SELECT * from <table_name>;
Or
SELECT <column_name1>, <Column_name2> from <table_name>;
Or
SELECT * from <table_name> where <condition>
Description: selects data and displays on screen. If * is used, all data from whole table
will be displayed. If specific attribute (Column name) is used only that attribute values will
be displayed.
• DISTINCT: Removes duplicate values.
Syntax: SELECT DISTINCT <column_name1>, <Column_name2> from <table_name>;
Or
SELECT DISTINCT * from <table_name>;
Description: Eliminate duplicate rows when using a select statement
• ORDER BY: It Sorts the data .
Syntax: SELECT * FROM <table_name> ORDER BY <column_name1>,
<Column_name2><sort_order>;
Description: rows retrieved from table will be sorted in either ascending or
descending order.
• DESCRIBE: It displays table structure .
Syntax: DESCRIBE <table_name>;
Exercises:
1. Create tables according to the following definition.
a) CREATE TABLE DEPOSIT (ACTNO VARCHAR2(5) ,CNAME
VARCHAR2(18) , BNAME VARCHAR2(18) , AMOUNT
NUMBER(8,2) ,ADATE DATE);
b) CREATE TABLE BRANCH(BNAME VARCHAR2(18),CITY
VARCHAR2(18));
c) CREATE TABLE CUSTOMERS(CNAME VARCHAR2(19) ,CITY
VARCHAR2(18));
2. Insert the data as shown below.
Table 1. Deposite
ACTNO CNAME BNAME AMOUNT ADATE
100 Anil Vrce 1000.00 1-MAR-95
101 Sunil Ajni 5000.00 4-JAN-96
102 Mehul Karolbagh 3500.00 17-NOV-95
104 Madhuri Chandi 1200.00 17-DEC-95
105 Prmod M.G.Road 3000.00 27-MAR-96
106 Sandip Andheri 2000.00 31-MAR-96
107 Shivani Virar 1000.00 5-SEP-95
108 Kranti Nehru Place 5000.00 2-JUL-95
109 Minu Powai 7000.00 10-AUG-95
3130703 DBMS
Table 2. Branch
BNAME CITY
Vrce Nagpur
Ajni Nagpur
Karolbagh Delhi
Chandi Delhi
Dharampeth Nagpur
M.G.Road Banglore
Andheri Bombay
Virar Bombay
Nehru Place Delhi
Powai Bombay
Table 3. Customers
CNAME CITY
Anil Calcutta
Sunil Delhi
Mehul Baroda
Mandar Patna
Madhuri Nagpur
Pramod Nagpur
Sandip Surat
Shivani Bombay
Kranti Bombay
Naren Bombay
Table 4. Borrow
LOANNO CNAME BNAME AMOUNT
201 Anil Vrce 1000.00
206 Mehul Ajni 5000.00
311 Sunil Dharampeth 3000.00
321 Madhuri Andheri 2000.00
375 Prmod Virar 8000.00
481 Kranti Nehru Place 3000.00
3. From the above given tables perform the following queries:
a) Describe deposit, branch.
b) Describe borrow, customers.
c) List all data from table DEPOSIT.
d) List all data from table BORROW.
e) List all data from table CUSTOMERS.
f) List all data from table BRANCH.
g) Give account no and amount of depositors.
h) Give name of depositors having amount greater than 4000.
i) Give name of customers who opened account after date '1-12-96'.
Review Questions:
1. What is the role of DDL and DML.
2. Difference between DDL, DML and DCL commands?
3. What are various DML commands in SQL? Give brief description of their purposes.
[This page is intentionally left blank]
3130703 DBMS
SQL concepts
Aim: Develop programs to learn different types of SQL concept (Alias, conditional
operation, like).
Theory
RETRIEVING DATA USING THE SQL SELECT STATEMENT
Capabilities of SQL SELECT Statements
A SELECT statement retrieves information from the database. With a SELECT statement, you
can use the following capabilities:
• Projection: Choose the columns in a table that are returned by a query. Choose as few or
as many of the columns as needed.
• Selection: Choose the rows in a table that are returned by a query. Various criteria can be
used to restrict the rows that are retrieved.
• Joining: Bring together data that is stored in different tables by specifying the link
between them. SQL joins are covered in more detail in the lesson titled “Displaying Data
from Multiple Tables.”
• Selecting All Columns: It display all columns of data in a table by following the.
Syntax: SELECT * FROM departments;
• Selecting Specific Columns: It display specific columns of data in a table
Syntax: SELECT department_id, location_id FROM departments;
Desciption: You can use the SELECT statement to display specific columns of the
Table by specifying the column names, separated by commas
ARITHMETIC EXPRESSIONS
You may need to modify the way in which data is displayed, or you may want to perform
calculations or look at what-if scenarios. These are all possible using arithmetic expressions.
An arithmetic expression can contain column names, constant numeric values, and the
arithmetic operators.
Table 1: Basic arithmetic operators.
Operator Description
+ Add
- Subtract
* Multiply
/ divide
Example:
SELECT last_name, salary, salary + 300 FROM employees;
SELECT last_name, salary,12*salary+100 FROM employees;
SELECT last_name, salary,12*(salary+100) FROM employees;
• Null Values: Arithmetic expressions containing a null value evaluate to null.
Description: If a row lacks a data value for a particular column, that value is said to be null
or to contain a null. A null is a value that is unavailable, unassigned, unknown, or inapplicable.
A null is not the same as a zero or a space. Zero is a number, and a space is a character.
Columns of any data type can contain nulls.
Example: SELECT last_name, 12*salary*commission_pct FROM employees;
DEFINING A COLUMN ALIAS
• COLUMN ALIAS: Renames a column heading
Description: Is useful with calculations. Immediately follows the column name (There can also
be the optional AS keyword between the column name and alias.). If the alias contains spaces
or special characters (such as # or $), or if it is case-sensitive, enclose the alias in doublequotation
marks (" ").
Example: SELECT last_name AS name, commission_pctcommFROM employees;
Output:
CONCATENATION OPERATOR
• CONCATENATION: Links columns or character strings to other columns
Description: Is represented by two vertical bars (||). Creates a resultant column that is a
character expression
Example: SELECT last_name || job_id AS "Employees" FROMemployees;
Values with the Concatenation Operator: If you concatenate a null value with a character
string, the result is a character string. LAST_NAME || NULL results in LAST_NAME.
• Literal Character Strings: A literal is a character, a number, or a date that is included
in the SELECT statement
Description: Date and character literal values must be enclosed by single quotation marks.
Each character string is output once for each row returned.
Example: SELECT last_name || ' is a ' || job_id AS "Employee Details"
FROM employees;
Output:
3130703 DBMS
Output:
Example: SELECT last_name, salary FROM employees WHERE salary <= 3000;
Note: If characters or dates are used in the list, they must be enclosed in single quotation
marks ('').
• LIKE Condition: It perform wildcard searches of valid search string values
Description: Search conditions can contain either literal characters or numbers:
% Denotes zero or many characters.
_ Denotes one character.
Example: SELECT first_name FROM employees WHERE first_name LIKE S%';
Output: The SELECT statement in the above example returns the employee first name from the
EMPLOYEES table for any employee whose first name begins with the letter S.
Note: the uppercase S. Names beginning with an s are not returned.
Description: The LIKE condition can be used as a shortcut for some BETWEEN comparisons.
Example: SELECT last_name, hire_date FROM employees WHERE hire_date LIKE '%95' ;
Output: Example displays the last names and hire dates of all employees who joined between
January 1995 and December 1995
3130703 DBMS
Description: You can combine pattern-matching characters
Example: SELECT last_name FROM employees WHERE last_name LIKE '_o%';
Output: The following example displays the names of all employees whose last names have
the letter o as the second character.
Exercises:
1. Create the below given table and insert the data accordingly.
3130703 DBMS
d) Display name and salary of employee whose department no is 20. Give alias
name to name of employee.
e) Display employee no, name and department details of those employee whose
department lies in(10,20)
4. To study various options of LIKE predicate
a) Display all employee whose name start with ‘A’ and third character is ‘ ‘a’.
b) Display name, number and salary of those employees whose name is 5 characters
long and first three characters are ‘Ani’.
c) Display the non-null values of employees and also employee name second
character should be ‘n’ and string should be 5 characters long.
d) Display the null values of employee and also employee name’s third character
should be ‘a’.
e) What will be output if you are giving LIKE predicate as ‘%\_%’ ESCAPE ‘\’
Review Questions:
1. Is a NULL value same as zero or a blank space? If not then what is the difference?
2. What is the purpose of the condition operators BETWEEN and IN?
3. How do you search for a value in a database table when you don’t have the exact value
to search for?
[This page is intentionally left blank]
3130703 DBMS
Data Manipulation
Aim: Develop programs to perform various data manipulation commands, aggregate functions
and sorting concept on all created tables.
Theory
• UPADATING:
Syntax: UPDATE <table_ name>SET <coumn_name1>=<value1>,
<column_name1>=<value2>
Description: Update all row
Syntax: UPDATE <table_ name>SET <coumn_name1>=<value1>,
<column_name1>=<value2>WHERE <condition>;
Description: Update specific selected row
• MODIFING:
Syntax: ALTER TABLE <table_name>ADD ( <new_column_name>
<data_type>(<size>), new_column_name><data_type>(<size>)..);
Description: Adding new column.
Syntax: ALTER TABLE <table_name> DROP COLUMN <column_name>;
Description: Dropping column from table
Modifying existing Column:
Restriction on alter table:
• Table name and column name cannot be change.
• Decrease size of column if table data exists.
• RENAMING:
Syntax: RENAME <table_name> To <New_table_Name>;
Description: Table will be renamed.
• DROP:
Syntax: DROP TABLE <Table_name>;
Description: If table is dropped all records held within it are lost and cannot be recovered.
• All data and structure in the table are deleted.
• Any pending transactions are committed.
• All indexes are dropped.
• All constraints are dropped.
• You cannot roll back the DROP TABLE statement.
• TRUNCATING: It drop and re-create the table
Syntax: TRUNCATE TABLE <Table_name>;
Description: Truncate operation Removes all rows from a table, leaving the table empty and
the table structure intact Is a data definition language (DDL) statement rather than a DML
statement; cannot easily be undone
• ORDER BY: It sort retrieves rows with ascending order, default or descending order
Syntax: SELECT expr FROM table [WHERE condition(s)]
[ORDER BY {column, expr, numeric_position} [ASC|DESC]];
Description: The order of rows that are returned in a query result is undefined. The ORDER
BY clause can be used to sort the rows. If you use the ORDER BY clause, it must be the last
clause of the SQL statement. You can specify an expression, an alias, or a column position as
the sort condition.
Example: SELECT last_name, job_id, department_id, hire_date FROM employees
ORDER BY hire_date;
Output:
3130703 DBMS
Use substitution variables to supplement the following:
• WHERE conditions
• ORDER BY clauses
• Column expressions
• Table names
• Entire SELECT statements
Description: Character and Date Values with Substitution Variables. Use single quotation
marks for date and character values
Example: SELECT last_name, department_id, salary*12 FROM employees
WHERE job_id = '&job_title' ;
Output:
• && Substitution Variable:
Example: SELECT employee_id, last_name, job_id, &&column_name FROM employees
ORDER BY &column_name ;
Output:
Exercises:
1. Perform query on created table(i.e. in the experiment 2 and 3).
a) List total deposit from deposit.
b) List total loan from karolbagh branch
c) Give maximum loan from branch vrce.
d) Count total number of customers
e) Count total number of customer’s cities.
f) Create table supplier from employee with all the columns.
g) Create table sup1 from employee with first two columns.
h) Create table sup2 from employee with no data
i) Insert the data into sup2 from employee whose second character should be ‘n’
and string should be 5 characters long in employee name field.
j) Delete all the rows from sup1.
k) Delete the detail of supplier whose sup_ no is 103.
l) Rename the table sup2.
m) Destroy table sup1 with all the data.
n) Update the value dept_ no to 10 where second character of emp. name is ‘m’.
o) Update the value of employee name whose employee number is 103.
Review Questions:
1. What is the difference between Drop, Delete and Truncate statements in SQL Server?
2. What is Cascading referential integrity constraint?
3. Explain following features of SQL Server:
a) No Action
b) Cascade
c) Set NULL
d) Set Default
3130703 DBMS
Single Row function
Theory
Functions are a very powerful feature of SQL. They can be used to do the following:
• Perform calculations on data
• Modify individual data items
• Manipulate output for groups of rows
• Format dates and numbers for display
• Convert column data types
Single-Row Functions: These functions operate on single rows only and return one result per
row. There are different types of single-row functions.
Multiple-Row Functions: Functions can manipulate groups of rows to give one result per
group of rows. These functions are also known as group functions.
SINGLE-ROW FUNCTIONS
Single-row functions are used to manipulate data items. They accept one or more arguments
and return one value for each row that is returned by the query. An argument can be one of
the following:
• User-supplied constant
• Variable value
• Column name
• Expression
Single-Row Function:
• Character functions: Accept character input and can return both character and number
values
• Number functions: Accept numeric input and return numeric values
• Date functions: Operate on values of the DATE data type (All date functions return a
value of DATE data type except the MONTHS_BETWEEN function, which returns a
number.)
• Conversion functions: Convert a value from one data type to another
• General functions: NVL, NVL2 , NULLIF , COALESCE ,CASE ,DECODE
Table 1: Single Row Function
Conversion Character Number Date General
Case Character
Manipulation Manipulation
Function Function
Implicit LOWER CONCAT ROUND MONTH_BETWEEN NVL
Explicit UPPER SUBSTR TRUNC ADD_MONTHS NVL2
INITCAP LENGTH MOD NEXT_DAY NVLLIF
INSTR ABS LAST_DAY COALES
CE
LPAD/RPAD POWER ROUND CASE
TRIM SQRT TRUNC DECODE
REPLACE EXP
Character functions
Table 2: Character Function (Case Manipulation)
Function Purpose
LOWER(column|expression) Converts alpha character values to lowercase
UPPER(column|expression) Converts alpha character values to uppercase
INITCAP(column|expression) Converts alpha character values to uppercase for the
first letter of each word; all other letters in lowercase
CONCAT(column1|expression1, Concatenates the first character value to the second
column2|expression2) character value; equivalent to concatenation operator
(||)
SUBSTR(column|expression,m[ Returns specified characters from character value
,n]) starting at character position m, n characters long (If m
is negative, the count starts from the end of the
character value. If n is omitted, all characters to the
end of the string are returned.)
Table 3: Character Function (Character Manipulation)
Function Purpose
LENGTH(column|expression) Returns the number of characters in the
expression
INSTR(column|expression, ’string’, [,m], Returns the numeric position of a named string.
[n] ) Optionally, you can provide a position m to
start searching, and the occurrence n of the
string. m and n default to 1, meaning start the
search at the beginning of the search and report
the first occurrence.
LPAD(column|expression, n, 'string') Pads the character value right-justified to a total
width of n character positions
RPAD(column|expression, n, 'string') Pads the character value left-justified to a total
width of n character positions
TRIM(leading|trailing|both, Enables you to trim heading or trailing
trim_character FROM trim_source) characters (or both) from a character string. If
trim_character or trim_source is a character
literal, you must enclose it in single quotation
marks.This is a feature that is available in
Oracle8i and later versions.
3130703 DBMS
REPLACE(text, search_string, Searches a text expression for a character string
replacement_string) and, if found, replaces it with a specified
replacement string
• CASE MANIPULATION:
Example: SELECT 'The job id for ' || UPPER(last_name) || ' is ' || LOWER(job_id) AS
"EMPLOYEE DETAILS" FROM employees;
Output:
Example: Display the employee number, name, and department number for employee Higgins
SELECT employee_id, last_name, department_id FROM employees
WHERE last_name = 'higgins';
Output: no rows selected
The WHERE clause of the first SQL statement specifies the employee name as higgins.
Because all the data in the EMPLOYEES table is stored in upper case, the name higgins does
not find a match in the table, and no rows are selected.
The WHERE clause of the second SQL statement specifies that the employee name in the
EMPLOYEES table is compared to higgins, converting the LAST_NAME column to
lowercase for comparison purposes. Because both names are now lowercase, a match is found
and one row is selected. The WHERE clause can be rewritten in the following manner to
produce the same result...WHERE last_name = 'Higgins'
• TRIM: It trims heading and trailing character (or both) from a character string
Description: Work only for one character. Character must be first or last including space or all.
Example: TRIM(‘H’ FROM ‘HELLOWORLD’);
Output: ELLOWORLD (H trim)
Example: TRIM(‘HE’ FROM ‘HELLOWORLD’);
Output: give error
Example: TRIM(‘H’ FROM ‘ HELLOWORLD’);
Output: HELLOWORLD (space trim)
3130703 DBMS
• CONCAT, LENGTH, SUBSTR:
Description: The following example displays employee first names and last names joined
together, the length of the employee last name, and the numeric position of the letter a in the
employee last name for all employees who have the string REP contained in the job ID starting
at the fourth position of the job ID.
Example: SELECT employee_id, CONCAT(first_name, last_name) NAME job_id, LENGTH
(last_name), INSTR(last_name, 'a') "Contains 'a'?" FROM employees WHERE
SUBSTR(job_id, 4) = 'REP';
Output:
• SUBSTR:
Description: Modify the SQL statement in the slide to display the data for those employees
whose last names end with the letter n.
Example: SELECT employee_id, CONCAT(first_name, last_name) NAME, LENGTH
(last_name), INSTR(last_name, 'a') "Contains 'a'?" FROM employees WHERE
SUBSTR(last_name, -1, 1) = 'n';
Output:
Number Function
Number functions accept numeric input and return numeric values.
Table 5: Different types of number functions
Function Purpose
Rounds the column, expression, or value to n decimal
places or, if n is omitted, no decimal places (If n is
ROUND(column|expression, n)
negative, numbers to left of the decimal point are
rounded.)
Truncates the column, expression, or value to n
TRUNC(column|expression, n)
decimal places or, if n is omitted, n defaults to zero
MOD(m,n) Returns the remainder of m divided by n
ABS(n) Returns the absolute value of n
Returns m raised to th nth power.n must be an
POWER(m,n)
integer,else error returned.
SQRT(n) Returns square root of n. if n<0.Null
Returns e raised to the nth power.where
EXP(n)
e=2.71828283
GREATEST(expr1,expr2,..expr n) Returns the greatest value in a list of expression.
LEAST(expr1,expr2,..expr n) Returns the least value in a list of expression.
Returns the largest integer value that is equal to or
FLOOR(n)
less than a number.
Returns the smallest integer value that is equal to or
CEIL(n)
greater than a number.
Table 6: Examples of number functions.
Function Result
ROUND(45.926, 2) 45.93
TRUNC(45.926, 2) 45.92
MOD(1600, 300) 100
ABS(-15) 15
POWER(3,2) 9
SQRT(25) 5
EXP(5) 148.413159
GREATEST(4,5,17) 17
LEAST(4,5,17) 4
FLOOR(24.8) 24
CEIL(24.8) 25
• ROUND:
Example: SELECT ROUND (45.923,2), ROUND (45.923,0), ROUND(45.923,-1) FROM DUAL;
Output:
3130703 DBMS
• Arithmetic with Dates:
Description: Because the database stores dates as numbers, you can perform calculations using
arithmetic operators such as addition and subtraction. You can add and subtract number
constants as well as dates.
Table 7: Different arithmetic operators with Dates.
Operation Result Description
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
In The following example displays the last name and the number of weeks employed for all
employees in department 90. It subtracts the date on which the employee was hired from the
current date (SYSDATE) and divides the result by 7 to calculate the number of weeks that a
worker has been employed.
Example: SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS FROM
employees WHERE department_id = 90;
Output:
Exercises:
1. Perform query on created table (i.e. in the experiment 2 and 3).
a) Write a query to display the current date. Label the column Date
b) For each employee, display the employee number, job, salary, and salary
increased by 15% and expressed as a whole number. Label the column New
Salary
c) Modify your query no 4.(2) to add a column that subtracts the old salary from
the new salary. Label the column Increase
d) Write a query that displays the employee’s names with the first letter capitalized
and all other letters lowercase, and the length of the names, for all employees
whose name starts with J, A, or M. Give each column an appropriate label. Sort
the results by the employees’ last names.
e) Write a query that produces the following for each employee: <employee last
name> earns <salary> monthly
f) Display the name, hire date, number of months employed and day of the week
on which the employee has started. Order the results by the day of the week
starting with Monday.
g) Display the hiredate of emp in a format that appears as Seventh of June 1994
12:00:00 AM.
h) Write a query to calculate the annual compensation of all employees
(sal+comm.).
Review Questions:
1. Is it possible to trim all the values in a column in a single statement?
2. Differentiate between ROUND, TRUNC and TRIM commands.
3. Which of the following commands is used to count the number of rows and non-
NULL values in Oracle database?
4. How we can perform arithmetic operations with DATE function. Explain with an
example.
3130703 DBMS
Constraints
Theory
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).
Table 1: EMPLOYEES
Employee_ID First_Name Last_Name Dept_ID
200 Jennifer Whalen 10
201 Michael Hartstein 20
202 Pat Fay 20
205 Shelley Higgins 110
206 William Gietz 110
(Employee_ID = Primary Key, Dept_ID= Foreign Key)
Table 2: DEPARTMENTS
Dept_ID Dept_Name Manager_ID Location_ID
10 Administration 200 1700
20 Marketing 201 1800
50 Shipping 124 1500
60 IT 103 1400
80 Sales 149 2500
90 Executive 100 1700
110 Accounting 205 1700
190 Contracting (null) 1700
(Dept_ID=Primary Key)
Guidelines for Primary Keys and Foreign Keys
• You cannot use duplicate values in a primary key.
• Primary keys generally cannot be changed.
• Foreign keys are based on data values and are purely logical (not physical) pointers.
• A foreign key value must match an existing primary key value or unique key value, or
else it must be null.
• A foreign key must reference either a primary key or a unique key column.
• CONSTRAINTS: Oracle server uses constraints to prevent invalid data entry into tables.
Description: You can use constraints to do the following:
• Enforce rules on the data in a table whenever a row is inserted, updated, or deleted from
that table. The constraint must be satisfied for the operation to succeed.
• Prevent the deletion of a table if there are dependencies from other tables
• Provide rules for Oracle tools, such as Oracle Developer
Following Constraints are there:
• 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
Syntax: CREATE TABLE [schema.]table (column datatype [DEFAULT expr]
[column_constraint], [table_constraint][,...]);
Column-level constraint
column [CONSTRAINT constraint_name] constraint_type,
Table-level constraint
column,... [CONSTRAINT constraint_name] constraint_type (column, ...),
Example: Column-level constraint:
CREATE TABLE employees(employee_id NUMBER(6) CONSTRAINT
emp_emp_id_pk PRIMARY KEY, first_name VARCHAR2(20), ...);
Table-level constraint
CREATE TABLE employees(employee_id NUMBER(6), first_nameVARCHAR2(20),
job_id VARCHAR2(10) NOT NULL, CONSTRAINT emp_emp_id_pk PRIMARY KEY
(EMPLOYEE_ID));
• UNIQUE Constraint: It validates that every value in a column or set of columns (key) be
unique—that is, no two rows of a table can have duplicate values in a specified column or
set of columns.
Description: The column (or set of columns) included in the definition of the UNIQUE key
Constraint is called the unique key. If the UNIQUE constraint comprises more than one
column, that group of columns is called a composite unique key.
Example: CREATE TABLE employees(employee_id NUMBER(6),last_name
VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary
NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT
NULL, CONSTRAINT emp_email_ukUNIQUE(email));
• Primary key constraint:
Example: CREATE TABLE departments(Department_id number(4) CONSTRAINT
dept_dept_id_pk PRIMARY KEY, Department_nameVARCHAR2(30),…);
3130703 DBMS
CHECK Constraint: It defines a condition that each row must satisfy
Description: The following expressions are not allowed:
• References to CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudo columns
• Calls to SYSDATE, UID, USER, and USERENV functions
• Queries that refer to other values in other rows
Example: ..., salary NUMBER(2) CONSTRAINT emp_salary_min CHECK (salary > 0),...
Description: Create the EMPLOYEES2 table based on the structure of the EMPLOYEES
table. Include only the EMPLOYEE_ID, FIRST_NAME, LAST_NAME, SALARY, and
DEPARTMENT_ID columns. Name the columns in your new table ID, FIRST_NAME,
LAST_NAME, SALARY, and DEPT_ID, respectively.
Example: CREATE TABLE employees2 AS SELECT employee_id id, first_name, last_name,
salary, department_iddept_id FROM employees;
Exercises:
1. Create A Human Resource Dataset with different constraints.
a) Human Resources (HR) Data Set
The Human Resources (HR) schema is part of the Oracle Common Schema that can be
installed in an Oracle Database. The practices in this course use the data from the HR
schema.
Table Descriptions
• REGIONS - contains rows representing a region (such as Americas, Asia, and so
on).
• COUNTRIES - contains rows for countries, each of which are associated with a
region.
• LOCATIONS - contains the addresses of specific offices, warehouses, and/or
production sites of a company in a particular country.
• DEPARTMENTS - shows details of the departments in which employees work.
Each department can have a relationship representing the department manager in
the EMPLOYEES table.
• EMPLOYEES - contains details about each employee who works for a
department. Some employees may not be assigned to any department.
• JOBS - contains the job types that can be held by each employee.
• JOB_HISTORY - contains the job history of the employees. If an employee
changes departments within the job or changes jobs within the department, a new
row is inserted in this table with the old job information of the employee.
• JOB_GRADES - identifies a salary range per job grade. The salary ranges do not
overlap.
REGIONS COUNTRY
Column_name Data Type
Column_name Data Type
REGION_ID NUMBER(4)
COUNTRY_ID NUMBER(4)
REGION_NAME VARCHAR2
COUNTRY_NAME VARCHAR2
REGION_ID NUMBER(4)
DEPARTMENTS
Column_name Null Data Type
EMPLOYEES
DEPARTMENT_ID NOT NUMBER(4)
Column_name Null Data Type
NULL
EMPLOYEE_ID NOT NUMBER(6)
DEPARTMENT_NAME NOT VARCHAR2(30)
NULL
NULL
FIRST_NAME VARCHAR2(20)
MANAGER_ID NUMBER(6)
LAST_NAME NOT VARCHAR2(25)
LOCATION_ID NUMBER(4)
NULL
JOBS EMAIL NOT VARCHAR2(25)
Column_name Null Data Type NULL
JOB_ID NOT NULL VARCHAR2(10)
PHONE_NUMBER VARCHAR2(20)
JOB_TITLE NOT NULL VARCHAR2(35)
HIRE_DATE NOT DATE
MIN_SALARY NUMBER(6) NULL
MAX_SALARY NUMBER(6) JOB_ID NOT VARCHAR2(10)
NULL
JOB_HISTORY SALARY NUMBER(8,2)
Column_name Null Data Type
COMMISSION_PAT NUMBER(2,2)
EMPLOYEE_ID NOT NUMBER(6)
MANAGER_ID NUMBER(6)
NULL
DEPRTMENT_ID NUMBER(4)
START_DATE NOT DATE
NULL
JOB_GRADES
END_DATE NOT DATE
Column_name Null Data Type
NULL
GRADE_LEVEL VARCHAR2(4)
JOB_ID NOT VARCHAR2(10)
NULL LOWEST_SAL NUMBER(6)
DEPARTMENT_ID NUMBER(4) HIGHEST_SAL NUMBER(6)
Review Questions:
1. What is the Purpose of foreign key constraint in SQL Server?
2. What do you understand by data integrity? List out types of data integrity?
3. Explain Referential Integrity Constraint.
3130703 DBMS
Types of Joins
Theory
Displaying Data from Multiple Tables
• Types of Joins
• Equijoins
• Nonequijoins
• Outer joins
• Self-joins
• Cross joins
• Natural joins
• Full (or two-sided) outer joins
• Cartesian Products
• A Cartesian product results in a display of all combinations of rows. This is done
by either omitting the WHERE clause or specifying the CROSS JOIN clause.
• Table Aliases
• Table aliases speed up database access.
• Table aliases can help to keep SQL code smaller by conserving memory.
• Join: It links and use data from more than one table.
Syntax: SELECT table1.column, table2.column FROM table1 [NATURAL JOIN table2] |
[JOIN table2 USING (column_name)] | [JOIN table2 ON (table1.column_name =
table2.column_name)]| [LEFT|RIGHT|FULL OUTER JOIN table2 ON
(table1.column_name = table2.column_name)]| [CROSS JOIN table2];
• Natural Joins: It selects rows from the two tables that have equal values in all matched
columns.
Description: The NATURAL JOIN clause is based on all columns in the two tables that have
the same name. If the columns having the same names have different data types, an error is
returned. In the following example, the LOCATIONS table is joined to the DEPARTMENT
table by the LOCATION_ID column, which is the only column of the same name in both tables.
If other common columns were present, the join would have used them all.
Example: INSERT INTO dept SELECT department_id, department_name FROM departments;
Output:
• Inner Join: It is a clause to match only one column when more than one column matches
Description: If several columns have the same names but the data types do not match, natural
join can be applied by using the INNER JOIN to specify the columns that should be used for
an equijoin. Do not use a table name or alias in the referenced columns.
Syntax: We can write the query by following two methods. Both are same.
SELECT <Table_name>.<column_name1>, <Table_name>.<column_name2>,
<Table_name>.<column_nameN>FROM <Table_name1> INNER JOIN
<Table_name2>ON <Table_name1>.<column_name1> = <Table_name2>.
<column_name2>WHERE <condition>ORDER BY <column_name1>,
<column_name2>, <column_nameN>;
OR
3130703 DBMS
SELECT <Table_name>.<column_name1>, <Table_name>.<column_name2>,
<Table_name>.<column_nameN>FROM <Table_name1>, <Table_name2>
WHERE <Table_name1>.<column_name1> = Table_name2>.<column_name2>
AND <condition>ORDER BY <column_name1>, <column_name2>,<column_nameN>;
• Column_name1 in table_name1 is usually that table’s PRIMARY KEY.
• Column_name2 in table_name2 is a FOREIGN KEY in that table.
• Column_name1 and Column_name2 must have the same data type and for certain
data types, the same size.
EMPLOYEES DEPARTMENTS
• Table Aliases: Aliases have been used to simplify queries and to improve performance.
Description:
• Table aliases can be up to 30 characters in length, but shorter aliases are better than
longer ones.
• If a table alias is used for a particular table name in the FROM clause, then that
table alias must be substituted for the table name throughout the SELECT statement.
• Table aliases should be meaningful.
• The table alias is valid for only the current SELECT statement.
Example: SELECT e.employee_id, e.last_name, d.location_id, d.department_id FROM
employees e INNER JOIN departments d ON e.department_id = d.department_id;
• Self-Joins Using the ON Clause: It join a table to itself
Description: To find the name of each employee’s manager, you need to join the
EMPLOYEES table to itself, or perform a self-join. For example, to find the name of Lorentz’s
manager, you need to:
• Find Lorentz in the EMPLOYEES table by looking at the LAST_NAME column
• Find the manager number for Lorentz by looking at the MANAGER_ID column.
Lorentz’s manager number is 103.
• Find the name of the manager with EMPLOYEE_ID 103 by looking at the
LAST_NAME column. Hunold’s employee number is 103, so Hunold is Lorentz’s
manager.
In this process, you look in the table twice. The first time you look in the table to find Lorentz
in the LAST_NAME column and MANAGER_ID value of 103. The second time you look in
the EMPLOYEE_ID column to find 103 and the LAST_NAME column to find Hunold.
MANAGER_ID in the WORKER table is equal to EMPLOYEE_ID in the MANAGERtable.
3130703 DBMS
Example: Aliasing the column name. (In the following example bold + italic word refer to as
alise name of column.)
SELECT e.employee_ideid, e.last_namelastname, e.department_id, d.department_id,
d.location_id FROM employees e JOIN departments d ON (e.department_id = d.department_id)
AND e.manager_id = 149 ;
The above example creates a nonequijoin to evaluate an employee’s salary grade. The salary
must be between any pair of the low and high salary ranges.
It is important to note that all employees appear exactly once when this query is executed. No
employee is repeated in the list. There are two reasons for this:
• None of the rows in the job grade table contain grades that overlap. That is, the salary
value for an employee can lie only between the low salary and high salary values of
one of the rows in the salary grade table.
• All of the employees’ salaries lie within the limits that are provided by the job grade
table. That is, no employee earns less than the lowest value contained in the
LOWEST_SAL column or more than the highest value contained in the
HIGHEST_SAL column.
Note: Other conditions (such as <= and >=) can be used, but BETWEEN is the simplest.
Remember to specify the low value first and the high value last when using BETWEEN. Table
aliases have been specified in the slide example for performance reasons, not because of
possible ambiguity.
• Outer Joins: A join between two tables that returns the results of the inner join as well as
the unmatched rows from the left (or right) tables is called a left (or right) outer join.
Description: If a row does not satisfy a join condition, the row does not appear in the query
result. For example, in the equijoin condition of EMPLOYEES and DEPARTMENTS tables,
department ID 190 does not appear because there are no employees with that department ID
recorded in the EMPLOYEES table. Instead of seeing 20 employees in the result set, you see
19 records. To return the department record that does not have any employees, you can use an
outer join. There are no employees in department 190.
3130703 DBMS
• Right Outer Join:
Description: The following query retrieves all rows in the DEPARTMENTS table, which is
the table on the right even if there is no match in the EMPLOYEES table.
Example: SELECT e.last_name, e.department_id, d.department_name FROM employees e
RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id);
Output:
• Cartesian product: When a join condition is invalid or omitted completely, the result is
a Cartesian product, in which all combinations of rows are displayed. All rows in the first
table are joined to all rows in the second table.
Description: A Cartesian product tends to generate a large number of rows, and the result is
rarely useful. You should always include a valid join condition unless you have a specific need
to combine all rows from all tables. Cartesian products are useful for some tests when you need
to generate a large number of rows to simulate a reasonable amount of data.A Cartesian product
is generated if a join condition is omitted.
Example: Employee last name and department name from the EMPLOYEES and
DEPARTMENTS tables. Because no join condition has been specified, all rows (20 rows) from
the EMPLOYEES table are joined with all rows (8 rows) in the DEPARTMENTS table,
thereby generating 160 rows in the output.
Fig 6: Cartesian product of EMPLOYEES and DEPARTMENTS tables.
• Creating Cross Joins: It produces the cross-product of two tables.
Description: This is also called a Cartesian product between the two tables.
Example: SELECT last_name, department_name FROM employees CROSS JOIN departments;
Exercises:
1) Displaying data from Multiple Tables (join)
1. Perform query on created table (i.e. in the experiment 2 and 3).
a) Give details of customers ANIL.
b) Give name of customer who are borrowers and depositors and having
living city Nagpur
c) Give city as their city name of customers having same living branch.
d) Write a query to display the last name, department number, and
department name for all employees.
e) Create a unique listing of all jobs that are in department 30. Include the
location of the department in the output
f) Write a query to display the employee name, department number, and
department name for all employees who work in NEW YORK.
g) Display the employee last name and employee number along with their
manager’s last name and manager number. Label the columns
Employee, Emp#, Manager, and Mgr#, respectively.
Review Questions:
1. Explain Self-Joins Using the ON Clause
2. Explain All Join in Relational algebra with example.
3. Explain types of Join query writing. Write both ANSI and Theta style query for
Exercise Queries: a to c.
4. Explain How Null values plays role in joining two tables.
3130703 DBMS
Data Aggregation
Theory
• AVG and SUM Functions: They are used for numeric data.
Example: SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary) FROM
employees WHERE job_id LIKE '%REP%';
Output:
• MIN and MAX Functions: They are used for numeric, character, and date data types.
Description: You can use the MAX and MIN functions for numeric, character, and date data
types.
Example: The below example displays the most junior and most senior employees.
SELECT MIN(hire_date), MAX(hire_date) FROM employees;
Output:
Example: The following example displays the employee last name that is first and the
employee last name that is last in an alphabetized list of all employees:
SELECT MIN(last_name), MAX(last_name) FROM employees;
Output:
Note: The AVG, SUM, VARIANCE, and STDDEV functions can be used only with numeric
data types. MAX and MIN cannot be used with LOB or LONG data types.
Example: The following example displays the number of employees in department 80 who
can earn a commission. Using the DISTINCT Keyword COUNT(DISTINCT expr) returns
the number of distinct non-null values of expr.
SELECT COUNT (commission_pct) FROM employees WHERE department_id = 80;
Example: To display the number of distinct department values in the EMPLOYEES table
SELECT COUNT (DISTINCT department_id) FROM employees;
You can return summary results for groups and subgroups by listing more than one GROUP
BY column. You can determine the default sort order of the results by the order of the columns
in the GROUP BY clause. In the slide example, the SELECT statement containing a GROUP
BY clause is evaluated as follows:
• The SELECT clause specifies the column to be retrieved:
o Department number in the EMPLOYEES table
o Job ID in the EMPLOYEES table
o The sum of all the salaries in the group that you specified in the GROUP BY
clause
• The FROM clause specifies the tables that the database must access: the EMPLOYEES
table.
• The GROUP BY clause specifies how you must group the rows:
o First, the rows are grouped by department number.
o Second, the rows are grouped by job ID in the department number groups.
• So the SUM function is applied to the salary column for all job IDs in each department
numbergroup.
• Illegal Queries Using Group Functions:
Description: Any column or expression in the SELECT list that is not an aggregate function
must be in the GROUP BY clause:
Example: SELECT department_id, COUNT(last_name) FROM employees;
Output: Error (Column missing in the GROUP BY clause)
Description: Whenever you use a mixture of individual items (DEPARTMENT_ID) and group
functions (COUNT) in the same SELECT statement, you must include a GROUP BY clause
that specifies the individual items (in this case, DEPARTMENT_ID). If the GROUP BY clause
is missing, then the error message “not a single-group group function” appears. You can correct
the error in the slide by adding the GROUP BY clause.
Theory
• Sub query:
Description: A query is called correlated sub query when both the inner query and the outer
query are interdependent. For every row processed by the inner query, the outer query is
processed as well. The inner query depends on the outer query before it can be processed.
Syntax: SELECT p.product_name FROM product p WHERE p.product_id = (SELECT
o.product_id FROM order_items o WHERE o.product_id = p.product_id);
A Subquery or Inner query or Nested query is a query within another SQL query, and embedded
within the WHERE clause.
A Subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.
Description: Sub queries are most frequently used with the SELECT statement.
Example: Consider CUSTOMERS table is having following records:
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Now let us check following sub-query with SELECT statement:
Output:
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Exercises:
1. To solve queries using the concept of sub query.
a) Write a query to display the last name and hire date of any employee in
the same department as SCOTT. Exclude SCOTT
b) Give name of customers who are depositors having same branch city of
Mr. Sunil.
c) Give deposit details and loan details of customer in same city where
Pramod is living.
d) Create a query to display the employee numbers and last names of all
employees who earn more than the average salary. Sort the results in
ascending order of salary.
e) Give names of depositors having same living city as mr. anil and having
deposit amount greater than 2000
f) Display the last name and salary of every employee who reports to ford.
g) Display the department number, name, and job for every employee in the
Accounting department.
h) List the name of branch having highest number of depositors.
i) Give the name of cities where in which the maximum numbers of
branches are located.
j) Give name of customers living in same city where maximum depositors
are located.
2. Manipulating Data
a) Give 10% interest to all depositors.
b) Give 10% interest to all depositors having branch vrce
c) Give 10% interest to all depositors living in Nagpur and having branch city
Bombay.
d) Write a query which changes the department number of all employees with
empno 7788’s job to employee 7844’current department number.
e) Transfer 10 Rs from account of anil to sunil if both are having same branch.
f) Give 100 Rs more to all depositors if they are maximum depositors in their
respective branch.
g) Delete depositors of branches having number of customers between 1 to 3.
h) Delete deposit of Vijay.
i) Delete borrower of branches having average loan less than 1000.
Review Questions:
1. Which of the following are the types of sub-queries?
2. The construct returns true if a given tuple is present in the sub query.
3. State true or false: We can use Sub queries inside the from clause.
4. Which of the following clause is mandatorily used in a sub-query? Justify your
answer.
a. SELECT
b. WHERE
c. ORDER BY
d. GROUP BY
5. Which of the following single-row operators can be used for writing a sub-query?
a. >=
b. <
c. =
d. All of the above
Transaction control commands
Theory
What Is a Transaction?
A transaction is a unit of work that is performed against a database. Transactions are units or
sequences of work accomplished in a logical order, whether in a manual fashion by a user or
automatically by some sort of a database program.
In a relational database using SQL, transactions are accomplished using the DML commands
(INSERT, UPDATE, and DELETE) A transaction is the propagation of one or more changes
to the database. For instance, you are performing a transaction if you performed an UPDATE
statement on a table to change an individual's name.
A transaction can either be one DML statement or a group of statements. When managing
groups of Transactions, each designated group of transactions must be successful as one entity
or none of them will be successful.
The following list describes the nature of transactions:
• All transactions have a beginning and an end.
• A transaction can be saved or undone.
• If a transaction fails in the middle, no part of the transaction can be saved to the
database.
Note: To start or execute transactions is implementation-specific. You must check your
particular implementation for how to begin transactions. There is no explicit start or begin
transaction in the ANSI standard.
Now that the three deletions have taken place, say you have changed your mind and decided to
ROLLBACK to the SAVEPOINT that you identified as SP2. Because SP2 was created after
the first deletion, the last two deletions are undone;
Input
ROLLBACK TO SP2;
Output
Rollback complete.
• RELEASE SAVEPOINT Command: It is used to remove a SAVEPOINT that you have
created.
Syntax: RELEASE SAVEPOINT SAVEPOINT_NAME;
Description: Once a SAVEPOINT has been released, you can no longer use the ROLLBACK
command to undo transactions performed since the SAVEPOINT.
Exercises:
1. Perform all the transaction command and write down 2 example of each.
Review Questions:
1. Explain SAVEPOINT with example.
2. Explain ROLLBACK with example.
3. List out TCL commands.
4. Save points divide a long transaction into smaller parts. This statement is true or
false.
5. What is the fundamental difference between COMMIT and COMMIT WORK?
Access Privileges
Theory
Introduction to Privileges
A privilege is a right to execute a particular type of SQL statement or to access another user's
object. Some examples of privileges include the right to:
• Connect to the database (create a session)
• Create a table
• Select rows from another user's table
• Execute another user's stored procedure
You grant privileges to users so these users can accomplish tasks required for their job. You
should grant a privilege only to a user who absolutely requires the privilege to accomplish
necessary work. Excessive granting of unnecessary privileges can compromise security. A user
can receive a privilege in two different ways:
• You can grant privileges to users explicitly. For example, you can explicitly grant the
privilege to insert records into the employees table to the user SCOTT.
• You can also grant privileges to a role (a named group of privileges), and then grant the
role to one or more users. For example, you can grant the privileges to select, insert,
update, and delete records from theemployees table to the role named clerk, which in
turn you can grant to the users Scott and Brian.
Because roles allow for easier and better management of privileges, you should normally grant
privileges to roles and not to specific users.
There are two distinct categories of privileges:
• System privileges
• Schema object privileges
System Privileges
A system privilege is the right to perform a particular action, or to perform an action on any
schema objects of a particular type. For example, the privileges to create table spaces and to
delete the rows of any table in a database are system privileges. There are over 60 distinct
system privileges.
Grant and Revoke System Privileges - You can grant or revoke system privileges to users
and roles. If you grant system privileges to roles, then you can use the roles to manage
system privileges. For example, roles permit privileges to be made selectively available.
Use either of the following to grant or revoke system privileges to users and roles:
• Oracle Enterprise Manager Console
• The SQL statements GRANT and REVOKE
U2 SCOTT
SCOTT SELECT NO
Table Security
Schema object privileges for tables allow table security at the level of DML and DDL
operations.
Data Manipulation Language Operations
You can grant privileges to use the DELETE, INSERT, SELECT, and UPDATE DML
operations on a table or view. Grant these privileges only to users and roles that need to query
or manipulate a table's data.
You can restrict INSERT and UPDATE privileges for a table to specific columns of the table.
With selective INSERT, a privileged user can insert a row with values for the selected columns.
All other columns receive NULL or the column's default value. With selective UPDATE, a
user can update only specific column values of a row. Selective
INSERT and UPDATE privileges are used to restrict a user's access to sensitive data. For
example, if you do not want data entry users to alter the salary column ofthe
employees table, selective INSERT or UPDATE privileges can be granted that exclude the
salary column. Alternatively, a view that excludes the salary column could satisfy this needfor
additional security.
Exercises:
1. Create different user and give the roles. Also gives the different access rights
according to roles.
Review Questions:
1. Explain GRANT with All Privilege.
2. Explain REVOKE with All Privilege.
3. GRANT ALL ON Table_1 to A;
i. In above statement ALL means:
4. DENY and REVOKE remove any GRANT permission on a securable. This
statement is true or false.