0% found this document useful (0 votes)
66 views46 pages

Structured Query Language: Features of SQL

1. SQL is a language that provides an interface to relational database systems and allows users to manipulate and retrieve data. It includes commands for data definition (DDL), data manipulation (DML), data control (DCL), and data queries (DQL). 2. The DDL commands like CREATE, ALTER, DROP, RENAME, and TRUNCATE are used to define and modify database schemas and structures but not data. The DML commands like INSERT, UPDATE, DELETE allow manipulating data within database tables. The DCL commands control access privileges. The DQL SELECT command retrieves data from tables. 3. The document then provides details on the syntax and use of various SQL commands to define tables

Uploaded by

shiva shantha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
66 views46 pages

Structured Query Language: Features of SQL

1. SQL is a language that provides an interface to relational database systems and allows users to manipulate and retrieve data. It includes commands for data definition (DDL), data manipulation (DML), data control (DCL), and data queries (DQL). 2. The DDL commands like CREATE, ALTER, DROP, RENAME, and TRUNCATE are used to define and modify database schemas and structures but not data. The DML commands like INSERT, UPDATE, DELETE allow manipulating data within database tables. The DCL commands control access privileges. The DQL SELECT command retrieves data from tables. 3. The document then provides details on the syntax and use of various SQL commands to define tables

Uploaded by

shiva shantha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 46

DBMS LAB DATE: PAGE NO :

Structured Query Language


SQL is a language that provides an interface to relational database system.SQL was developed
by IBM for use in system and is a de facto standard as well as ISO and ANSI standard.In
common usage, SQL also encompasses DML(Data Manipulation Language) and DDL(Data
Definition Language).

Features of SQL:-
1.SQL can be used a range of users, including those with little or no programming experience.
2.It is not a procedural language.
3.It reduces the amount of time required for creating and maintaining system.

Rules for SQL:-


1.SQL starts with a verb ex: select statement.
2.Each verb is followed by a number of clauses ex: from,where,having.
3.A space separate clauses.
4.A comma(,) separate parameters without a clause.
5.A ‘;’ is used to end SQL statement.
6.Statements may be split across line but keywords may not.
7.Reserved words cannot be used as identifiers unless enclosed with double quotes.
8.Identifiers can contain up to 30 characters and must start with an alphabetic character.

SQL Delimiters:-
Delimiters are symbols or compound symbols which have a special meaning within SQL and
PL/SQL statements.
+Addition
- Substraction
* Multiplication
/ Division
= > < Relational
( ) Expression or list
; Terminator
Components of SQL
1.DDL(Data Definition Language):
 It is a set of SQL commands used to create,modify and delete database structures but not
data.
 These statements are immediate,they are not susceptible to Rollback.
 Every DDL command would commit all the updates as every DDL command implicitly
issues a commit command to the database.
2.DML(Data Manipulation Language):
 It is the area of SQL that allows changing data within the database.
3.DCL(Data Control Language):
 It is the component of SQL statements that control access to data and to the database.
 DCL statements are grouped with DML statements.
4.DQL(Data Query Language):

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

 It is the component of SQL statements that allows getting data from the database and
imposing ordering upon it.It includes ‘select’ statement.
Examples of DDL,DML,DCL and DQL command:-
DDL:
Create: To create objects in the database.
Alter: Alters the structure of database.
Drop: Delete objects from the database.
Rename: Rename objects in database.
Truncate: Removes all records along with space allocated for the records.
Comment: Add comment to data dictionary.
Grant: Give users access privileges with grant command.

DML:
Insert: Inserts data into a table.
Update: Updates existing data within a table.
Delete: Delete all records from a table,the space for the record remains.
Call: Calls a PL/SQL or Java subprogram.
Lock: Table control concurrency.

DCL:
Commit: Saves works done.
Savepoint: Identify a point in a transaction to which you can later rollback.
Rollback: Restore database to original since the last commit.
Set transaction: Change transaction option like what rollback segment to use.

DQL:
Select: Retrieve data from the database.

Table Fundamentals:-
Table is a database object that holds user data.Each table has multiple columns and each column
of a table have a specific data type associated with them.

Basic Data types:-


Data types comes in several forms and sizes allowing the programmers to create tables suited to
the scope of the project.The decision made in choosing proper data type greatly influences the
performance of a database.
Ex:
CHAR(size)
This data type is used to store character strings values of fixed length.The size in brackets
determine the number of characters the cell can hold.The maximum number of characters(i.e
size) this data type can hold is 255 characters.
VARCHAR(size)/VARCHAR2(size)
This data type is used to store variable length alphanumeric data.It is more flexible form of the
CHAR data type.The maximum this data type can hold up to 400 characters.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

DATE
This data type is used to represent date and time.The standard format is DD-MON-YY as in 21-
JUN-04.Datetime stores date in the 24-hour format.
NUMBER
The number data type is used to store numbers(fixed or floating point).Numbers of vertically any
magnitude may be stored up to 38 digits of precision.Valid values are 0 and positive and
negative numbers with magnitude 1.0E-130 to 9.9..E1.25.
LONG
This data type is used to store variable length character strings containing up to 2GB.Long data
can be used to store arrays of binary data in ASCII format.Only one long value can be defined
per table.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

I.DEMONSTRATION OF DATA DEFINITION LANGUAGE


COMMANDS

1.CREATE COMMAND
The create table command defines each column of the table uniquely.Each column has a
minimum of three attributes a name and data type and size(i.e column width).Each table column
definition is a single clause in the create table syntax.Each table column definition is seperated
from the other by a comma.Finally,the SQL statement is terminated with a semicolon.
Rules for creating tables:
 A name can have maximum upto 30 characters.
 Alphabets from A-Z,a-z and numbers from 0-9 are allowed.
 A name should begin with an alphabet.
 The use of the special characters like-is allowed and also recommended.
 SQL reserved words not allowed.
Syntax:
Create table tablename(columnName1 Datatype(size),columnName2
Datatype(size),………..columnNamen Datatype(size));

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

2.ALTER COMMAND
Modifying the structure of tables:-
The structure of a table can be modified by using the Alter table command.With Alter table
command it is possible to add or delete columns,create or destroy indexes,change the data types
of existing columns or rename columns or the table itself.
Alter table works by making a temporary copy of the original table.The alteration is performed
on the copy then the original table is deleted and the new one is renamed.

Adding a new column using add clause:-


Syntax:
Alter table <tablename>
Add (<newcolumn name1> <Datatype> (<size>) <newcolumn name2> <Datatype> (<size>));

Dropping a column from a table:-


Syntax:
Alter table <tablename>
drop column <columnname>;

Modifying existing columns:-


Syntax:
Alter table <tablename> modify (<columnname> <newdatatype>(<new size>));

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

3. DROP COMMAND
 Drop table statement can be used to destroy a table and releasing the storage space held
by the table.
 Dropping a table deletes all the data stored (records) in the table and all the indexes
associated with it.
 We cannot roll back the drop statement.
Syntax:
Drop table <Table Name>;

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

4.RENAME COMMAND
 Oracle allows renaming of tables. The rename operation is done automatically, which
means that no other thread is can access any of the tables while the rename process is
running.
 To rename a table alter and drop privileges on the original table and create and insert
privileges on the new table are required.
Syntax:
Rename <Table Name> to <New Name>;

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

5.TRUNCATE COMMAND
 Truncate table statement removes all rows from a table and releases all the storage space
used by that table.
 The difference between Truncate and Delete statement is:
 Truncate operation drop and recreate the table which is much faster than deleting rows
one by one.
 Truncate does not generate roll back Information.
 Truncate operations are not transaction safe. (i.e. an error will allow if an active
transaction or an active table lock exist.)
Syntax:
Truncate table <Table Name>;

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

II.DEMONSTRATION OF DATA MODIFICATION LANGUAGE


COMMANDS

1.INSERT COMMAND
Once table is created,the most natural thing to do is load this table with data to be manipulated
later.When inserting a single row of data into the table the insert operation-
1.creates a new row(empty) in the database table.
2.loads the values passed(by the SQL insert) into the column specified.
Syntax:
Insert into <tablename> (<columnname1>,<columnname2>)
values(<expression1>,<expression2>);
Characters expressions placed within the insert into statement must be enclosed in single quotes.
In the insert into SQL sentence,table columns and values have one to one relationship(i.e the first
value described is inserted into the first column and the second column and so on).

Inserting data into a table from another table.


Syntax:
Insert into <tablename>
Select <columnname1>,<columnname2>
from <tablename>;

Inserting rows with null values:-


Implicit method omit the column from the column list.Explicit method specify the NULL
keyword in the values clause.
Ex: for department table containing
Name Null? Type
Department_id Not Null Number(4)
Department_name Not Null Varchar2(30)
Manager_id Number(6)
Location_id Number(4)

Implicit method syntax:


Insert into department (department_id,department_name) values(30,’purchasing’);
1 row created.

Explicit method syntax:


Insert into department values (100,’finance’,NULL,NULL);
1 row created.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

2.DELETE COMMAND
The delete command deletes rows from the table that satisfies the condition provided by its
where clause and returns the number of records deleted.The verb delete in SQL is used to
remove either all rows from a table or a set of rows from a table.
Syntax:
For all rows
delete from <tablename>;

Removal of specific rows.


Delete from <tablename>
where <condition>;
.
We can use subqueries in delete statement to remove rows from a table based on values from
another table.
Ex:
delete from employee
where department_id=(select department_id from department where departmentname like
‘%public%’);

We cannot delete a row that contains a primary key that is used as a foreign key in other table.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

3.UPDATE COMMAND
Update command is used to change or modify data values in a table.
Update is used to either update all the rows from a table,a select set of rows from a table.

Syntax:
For all rows
Update <tablename>
Set <columnname1> = <expression1>,<columnname2> = <expression2>;

A select set of rows


Update <tablename>
Set<columnname1> = <expression1>,<columnname2> = <expression2>
Where condition;

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

III.DEMOSTRATION OF DATA CONSTRAINTS


 Business rules, which are enforced on data being stored in a table are call constraint.
 Constraint super control the data being entered into a table for a permanent storage.
 Oracle permits data constraints to be attached to the table columns via SQL Syntax that
checks data integrity prior storage.
 Once data constraint are part of a table columns construct, the Oracle Database engine
checks the data being entered into a table column against the data constraint, the Oracle
Database stores the data in the table column. If the data passes the check, else the data is
rejected.
 Both the Create table and Alter table SQL verbs can be used to write SQL sentences that
attach constraints to a table column.
 Once a constraint is attached to a table column any SQL Insert or update statement
automatically causes these constraint to be applied to data prior it is being inserted into
the table column for storage.
 Constraints prevent the deletion of a table if these are dependencies.
 The following constraint types are valid:
1. Primary Key
2. Foriegn Key
3. Unique Key
4. Null
5. Check
 Constraint can be named.
 Constraint can be defined at table level, column level.
 Constraint are stored in data dictionary.

Types of Data Constraint


 There are two types of data constraint that can be applied to data being inserted into a
Oracle table.
 One type of constraint is called an I/O constraint (Input/output). This data constraint
determines the speed at which data can be inserted or extracted from a Oracle table.
 The other type of constraint is Business rule constraint.
 Constraints can be defined at either column level.
At Column Level,
Syntax:
<Column Name> constraint_type
At Table Level,
Syntax:
Constraint_type ( column ........)
Column Constraint
References a single column and is defined within a specification for the owning column
can define any type of integrity constraint.
Table Constraint
References one more column and is defined separately from the definitions of the
columns in the table, can define any constraints except NOT NULL.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

I/O Constraint
 The Input/output data constraint can be further divided into distinctly different
constraints:
i. Primary Key Constraint
ii. Unique Key Constraint
iii. Foreign Key Constraint

1.Primary Key Constraint


 A primary key is the one or more column in a table used to uniquely identify each row in
the table.
 None of fields that are the part of primary key can contain a Null value.
 A table can have only one primary key.
 It defines the column as a mandatory column (i.e. the column cannot be left blank) as the
not null attribute is active.
 The data held across the column must be unique.
 A single column primary key is called a simple key.
 A multicolumn primary key is called a composite key.
 A primary key cannot be defined in either a create table statement or an alter table
statement.
 Unique index is created automatically if there is a primary key.
Primary key constraint defined at column level.
Syntax:
<Column Name><Datatype>(<Size>) Primary Key
Primary Key constraint defined at table level
Syntax:
Primary Key(<Column Name>,<Column Name>)
A composite key is defined only by the table level definition.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

2.Foreign Key
 Foreign Key represents relationship between tables.
 A Foreign Key is a column (or a group of columns) whose values are derived from the
primary key or unique of some other table.
 A table in which foreign key is defined is called a foreign table or detail table.
 The table that defines the primary or unique key and is referenced by the foreign key is
called the primary table or master table.
 Foreign key can be defined in either a create table statement or an Alter table statement.
 The master table can be referenced in the foreign key definition by using the clause
‘References’ when defining the foreign key, column attributes in the detail table.
 The constraint of the foreign key establishes a relationship between the records (i.e.
Column data across a master and a detail table. This relationship ensures:
*Records cannot be inserted into a detail table if corresponding records in the master
table does not exists.
*Records of the master table cannot be deleted if corresponding records in the detail table
actually exist.
 Foreign Key constraints:
*Rejects an insert /or update of a value does not currently exist in the master key table.
*Rejects a delete from the master table if corresponding records in the table exists.
*If on delete cascade option is set a delete operation in the master table will trigger a
delete operation for corresponding records in all detail tables.
*if on delete set Null option is set a delete operation in the master table will set the value
held by the foreign key of the detail table to Null.

Foreign key constraint defined at the column level


Syntax:
<Column Name><Data type>(<Size>) References
<Table Name> [<Column Name>] [ON delete cascade]
Ex:
Create table Account(a_no char(20) primary key, branch_name char(20) References branch,
balance integer);

Foreign Key constraint defined at the table level


Syntax:
Foreign Key (<Column Name>,<Column Name>) References <Table Name>(<Column
Name>, <Column Name>)

Ex:
Create table Account (a_no char (20) primary key, branch_name char(20),balance integer,
foreign key (branch_name) references branch (branch_name));

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

3.Unique Key Constraint


 Unique key constraint permits multiple entries of Null into the column. The NULL values
are clubbed at the top of the column in the order in which they were entered into the
table. This is essential difference between the primary key and the unique constraint
when applied to the table columns.
 Unique will not allow duplicate values.
 Unique index is created automatically.
 A table can have more than one unique key which is not possible in primary key.
 The column included in the definition of the unique key constraint is called the unique
key.
 If the unique constraint comprises more than one column, that a group of columns is
called a composite unique key.

Unique constraint can be defined either at the table level or column level.
Syntax:
<Column Name><Data type>(<Size>) Unique.
Ex:
Create table Customer ( c_id char(20) unique, c_name char(20),c_address char(20));

Unique constraint defined at the table level.


Syntax:
Create table TableName (Column Name><data type>(<size>). Column Name><data
type>(<size>),Unique(<Column Name1>, <Column Name2>));

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

Business Rule Constraint


 Oracle allows the application of business rules to table columns.
 The rules are applied to data prior the data is being inserted into the table columns. This
ensures that the data (records) in the table have integrity.
 Business rules can be implemented in Oracle by using Check Constraints.
 Check Constraint can be bound to a column or a table using the create table or alter table
command.
4. Check Constraint
check constraint defines a condition that each row must satisfy.
A single column can have multiple check constraints which refer to the column in its definition.
There is no limit to the number of check constraint which you can define on a column.
 Check constraint must be specified as a logical expression that evaluate either to True or
False.
Check Constraint defined at the column level.
Syntax:
<Column Name><Data type>(<Size>) Check (<Logical Expression>);
Check Constraint defined at the column level.
Syntax:
Check (<Logical Expression>)

Restricted on check constraints


A check integrity constraint require that a condition to be true or unknown for the unknown for
row to be processed. If an SQL Statement causes the condition to evaluate to false, an
appropriate error message is displayed and processing stops.
Check has following limitations:
*The Condition must be a Boolean expressing that can be evaluated using the values in the row
being inserted or update.
*The Construct cannot contain sub queries or sequences.
*The Condition cannot include the SYSDATE, UID, USER or USERENV SQL Functions.
Ex: Create table employee
( ....... Salary integer constraint emp_sal_min check(salary >0),........);

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

5. NOT NULL CONSTRAINT


 Often there may be records in a table that so not have values for every field. This could
be because the information is not available at the time of data entry or because the field is
not applicable in every case.
 If the column was created a Null able, Oracle will place a Null value in the column in the
absence of a user defined value.
 A Null value is different from a blank or zero. A Null value can be inserted into column
of any data type.
 Setting a Null value is appropriate when actual value is unknown, or when a value would
not be meaningful.
 A Null value is not equivalent to a value of zero if the data type is a number and is not
equivalent to spaces if the data type is character.
 A Null value will evaluate to Null in any expression.
 If column is defined as Not Null, then that column becomes a mandatory column. It
implies that a value must be entered into the column, if the record is to be accepted for
storage in the table.
Syntax:
<Column Name><Data Type>(<Size>) NOT NULL;

The User Constraint Table


A table can be created with multiple constraints attached to its columns.
In Order to view the constraint on the table a user constraint table can be used.
Querying user-constraint provide information bound to the names of all the constraints on the
table.
User_Constraint table has multiple Columns some of which are as given on the next page:

USER CONSTRAINT TABLE


Column Name Description
Owner Owner of the Constraint.

Constraint_Name The Name of the constraint.

Table_Name The Name of the table associated with the constraint.

Constraint_Type The type of constraint


P-Primary key
R-Foreign Key
U-Unique Constraint
C-Check Constraint
Search_Condition The Search Condition used (for check).

R_Owner The owner of the table referred by the foreign key constraint.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

R_Constraint_Name The name of the constraint referred by a foreign key constraint.

Defining Integrety Constraint via the Alter Table Command


 Integrity constraint can be defined using the constraint clause in the Alter table command.
Syntax:
Alter table tablename add primary key(A);

Drop an integrity constraint via the Alter table command:


Integrity constraints can be dropped if the rule that it enforces is no longer true, if the constraint
is no longer needed.
Syntax:
Alter table tablename Drop primary key;

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

IV. SIMPLE CONDITION QUERY CREATION


1.SELECT CLAUSE
A select statement retrieves information from the database. Using the select statement you can do
the following.
Projection: You can use the projection capability in SQL to choose the columns in a table that
you want returned by your query. You can choose as few or as many columns of the table as you
require.
Selection: You can use the selection capability in SQL to choose the rows in a table that you
want returned by your query.
Joining: You can use the Join capability in SQL to bring together data that is stored in different
tables by creating a link between them.
Syntax:
Select * | { [distinct] column | expression [alias]..}
From table;

Select identifies what column, from identifies which table.


Select-is a list of one or more columns.
*-select all columns.
Distinct-suppress duplicates.
Column|expression-selects the named column or the expression.
Alias-gives selected columns different headings.
From table-specifies the table containing the columns.

Multiple columns can be selected by specifying the column names separated by commas.
Arithmetic operators can be used in select statement.The order of precedence is * / + -
Ex: select ename,salary,12*salary
From emp;

AS: As is used for renaming a column heading.It is useful with calculations.


Ex: select ename,12*salary as annual sal
from emp;

|| : || is a concatenation operator. It concatenate columns or character strings to other column.


Ex: select last-name || job as “employee” from emp;

Lateral character string:


A lateral is a character, a number, or a date in the select list.
Date and character lateral value must be enclosed within single quotation marks.
Each character string is output once for each row returned.
Ex: select last-name || ‘is a’ || job-1 as “employee details”
from employees;

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

2.WHERE CLAUSE
We can restrict the rows returned by using the where clause.
Syntax:
Select * | {[distinct] column | expression [alias]..}
From table
Where condition(s);

Where clause contains a condition that must be met and it directly follows the from clause.
If condition is true the row meeting the condition is returned.
In the syntax;
Where: restricts the query to rows that meet a condition.
Condition: is composed of column names, expressions constants and a comparison operator.

Where clause can compare values in columns,literal values,arithmetic expression or function.


It consists of three elements
1) column name
2) comparison condition
3) column name, constant or list of values.
Character strings and data values are enclosed in single quotation marks.
 All character searches are case sensitive.
 Comparison conditions are =, >,>=, <, <=, < >, ! used in where clause as
 Where expr operator value.
 Ex: where salary>=6000.
 Other comparision conditions are between and -Between two values(inclusive),In(set)-
match any of a list of values, is null- is a null value.
Logical condition-And- return true if both component conditions are true
Or- returns true if either component condition is true
Not- return true if the following condition is false

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

3.ORDER BY CLAUSE
The order by clause can be used to sort the rows. Order by must be the last clause of SQL
statement.
Syntax:
Select expr
From table
Where condition
Order by {column,expr} {Asc [desc]};

Asc- ascending order – order rows in ascending order, it is a default order.


Desc- order the rows in descending order.
 If a column contain Null value then null values are displayed last for ascending sequences
and first for descending sequences.
 Column all as can be used in order by clause.
 You can sort query results by more than one column.The sort limit is the number of
columns in the given table, separate multiple column names using commas.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

4.GROUP BY CLAUSE
Group by clause to divide the rows in a table into groups.
Syntax:
Select column, group-function (column)
From table
Where condition
Group by group_by_expression
Order by Column.

 Using where clause we can exclude rows before dividing them into groups.
 Columns alias cannot be used in group by.
 When using the group by clause, make sure that all columns in the select list that are not
group functions are included in the Group by clause.
Ex:
Select department_id, Avg(salary)
From employee
Group by department_id.
Average will be calculated for each department.
 You can return summary results for groups and subgroups by listing more than one group
by column.
Ex:
Select did, Job_id, sum(salary)
From emp
 Using the count Function

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

5.HAVING CLAUSE
Having clause can be used to satisfy which groups are to be displayed. Thus, further restricting
the groups on the basis of aggregate of Information.
Syntax:
Select column, group function
From table
Where condition
Group by group_by_expression
Having group_conditoin
Order by column

Oracle server performs the following steps when you use the Having clause
1. Rows are grouped
2. Group function is applied to the group
3. The groups that match the criteria in the having clause are displayed.
Ex:
Select did, Avg(Sal)
From emp
Group by did
Having max (Sal)>1000;

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

6.ORACLE FUNCTUIONS
Functions are a very powerful feature of SQL and can be used to do the following.
 perform calculations on data.
 modify individual data items.
 manipulate output for groups of rows.
 convert column data types.

SQL functions sometimes take arguments and always return a value.


Two types of SQL functions are,
a) Single row function
b) Multiple row function

Single row functions:


These functions operate on single row only and return one result per row.There are different
types of single row function.
1) Character
2) Number
3) Date
4) Conversion
Multiple row functions:
Functions can manipulate groups of rows to give one result per group of rows. These functions
are known as group functions.

Single row functions are;


1) Character function-Accepts character input and can return both character and number
values.
2) Numbers function-Accepts numeric input and returns numeric values.
3) Date function-Operates in values of the data type.
4) Conversion function-Converts a value from one data type to another.
5) General functions-are NVL, NVL2, NULLIF, COAL SELECT, CASE, DECODE.

1.CHARACTER FUNCTIONS:
Accepts character data as input and can return both character and numeric values.Character
values can be divided into;

I.Case manipulation functions.


Examples are;
LOWER: convert alpha character values to lowercase.
UPPER(column|expression): converts alpha character values to uppercase.
INIT CAP(column|expression): converts alpha character value to uppercase for the first letter of
each word, all other letters in lowercase.

II.Character manipulation functions.


Examples are;

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

CONCAT(column1|expression1,column2|expression2): concatenates the first character value to


the second character value, equivalent to concatenation operator( || ).
SUBSTR(column|expression,m,[n]): returns specified character position m, n characters long(if
m is negative count starts from the end of the character value).
LENGTH(column|expression): returns the number of characters in the expression.
INSTR(column|expression,’string’,[m],[n]): returns the numeric position of a named string,
optionally a position m to start searching can be provided and the occurrence n of the string. m
and n default to 1, meaning start the searching at the beginning of the search and report the first
occurrence.
LPAD(column|expression,n,’string’): pad character values right justified to a total width of n
character positions.
RPAD(column|expression,n,’string’): pad the character values left justified to a total width of n
character positions.

2.NUMBER FUNCTIONS:
Number functions accepts numeric input and returns numeric values.
Ex:
I.Round(column|expression,n)
Rounds the column,expression or value to n decimal places or if n is omitted,no decimal places.
If n is negative,numbers to left of the decimal point are rounded.
II.Trunc(column|expression,n)
Truncates the column expression or value to n decimal places or if n is omitted then n defaults to
zero.
III.Mod(m,n)
Returns the remainder of m divided by n.

Ex: select Round(45.923,2) , Round(45.923,0) , Round(45.923,-1)


from dual;

O/P: Round(45.923,2) = 45.92


Round(45.923,0) = 46
Round(45.923,-1) = 50
If second argument is 0 or is missing the value is rounded to zero decimal places.If the second
argument is 2 the value is rounded to two decimal places.If -2 the value is rounded to two
decimal places to the left.
Dual table:-
Dual table is owned by the user system and can be accessed by all users. It contain one column
dummy and one row with the value X, dual table is useful when you want to return a value once
only,dual table is generally used for select clause syntax completeness, because both select and
from clause are mandatory and several calculations do not need to select from actual tables.
3.DATE FUNCTIONS
Dates:-Oracle database stores dates in an internal numeric format.
Century,year,month,day,hours,minutes,seconds.

Default: date display format is


DD – month – year

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

19-oct-2000

Sysdate : is a date function that returns the current database server date and time.
Sysdate can be used as any other column name.
Ex: select sysdate from dual;

Arithmetic with dates :


since the database stores dates as numbers, you can perform calculations using arithmetic
operators such as addition and substraction.
Operation Result
Date + Number Date
Date – Number Date
Date – Date Number of days
Date + Number/24 Date

Arithmetic operators ex:


Select name, (sysdate – hiredate)/7 as weeks from emp;
Date functions:-
1.Months-Between (Date1, Date2)
Finds the number of months between date1 and date2. The result can be positive or negative.
2.Add_months (Date, n)
Adds n number of calander months to date, the value of n must be an integer and can be
negative.
3.Next_day (date, ‘char’)
Finds the date of the next specified day of the week (‘Char’) following date. The value Char can
be number representing a day or a character string.
4.Last_day (date)
Finds the date of the last day of the month that contains date.
5.Round (date, [‘fmt’])
Returns date rounded to the unit specified by the format model FMT. If FMT is omitted then date
is rounded to the nearest day.
6.Trunc (date, [‘fmt’]
Returns date with the time portion of the day truncated to the unit specified by the format model
FMT. If FMT is omitted, date is truncated to the nearest day.
Ex:
Assume sysdate = ‘25 – jul – 1995’
Round (sysdate, ‘month’) – 01 – aug – 1995
Round (sysdate, ‘year’) – 01 – jan – 1996
Trunc (SysDate, ‘Month’) 01-JUL-95
Trunc(SysDate, ‘YEAR’) 01-JAN-1995
*fmt can be month and year.

4.CONVERSION FUNCTION:
Data type conversions can be either:
Implicit Data type conversion;
Explicit Data type conversion.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

Implicit Data type conversions are done implicitly by Oracle Server.


Explicit Data type conversion are done by using the conversion Functions.
Ex for Implicit data type conversion (For Assignments)
From To
Varchar 2 or char Number
Varchar 2 or char Date
Number Varchar 2
Date Varchar 2

Implicit Data Type conversion (For Expression Evaluation.)


From To
Varchar 2 or char Number
Varchar 2 or char Date
Ex: For Explicit Data Type Conversion

To_char: (number | date, [fmt], [nLsparams]) converts a number or date value to a varchar 2
characters string with format model fmt. nLsparam (Number Conversion) specifies the following
characters which are returned by numbers format elements.
 Decimal Character
 Group Separator
 Local currency symbol
 International currency symbol

If nLsparams or any other parameter is omitted, this function uses default parameter values for
the session.

To_Number: (Char,[fmt],[nLsparams])
Converts a character string containing digits to a number in the format specified by the optional
format model fmt.

To_Date:(char,[fmt][nLsparams]
Converts a character string representing a date to a date value according to a fmt specified. If
fmt is omitted the format is DD-MON-YY.

5.GENERAL FUNCTION:
These Functions work with any data type and pertain to using nulls
 NVL( expr1, expr2)
Converts a null value to an actual value

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

 NVL2( expr1, expr2, expr3)


If expr1 is not null, NVL2 returns expr2. If expr1 is null, NVL2 returns expr3. The
argument expr1 can have any data type.
 NULLif( expr1, expr2)
Compares the two expressoins in and returns null if they are equal. Or the first
expression. If they are not equal.
 Coalesce(( expr1, expr2,..................,exprn)
Returns the first non-null expr expressions in the expression list

NVL Function
NVL converts a null to an actual value.
Syntax:
NVL(expr1,expr2)
Expr1 is the source value or expression that may contain null
Expr2 is the target value for converting the null.

Data types that can be used are at date, character and number.
Ex:
NVL(commisiion-pet,0)
NVL(hire_date, ’01-JAN-97’)
NVL(Job-id, ‘No Job Yet’)

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

7.GROUP FUNCTIONS
 Group Functions operate on sets of rows to give one result per group.
 Type of group functions
o Avg
o Max
o STDDEV
o VARIANCE
o Count
o Min
o Sum
 Avg(costinct [All] n)-Average value of n ignoring null values
 Count({*|Distinct|All}expr})-Number of rows,where expr evaluate to something other
than null.
 Max(Distinct|All]expr)
Maximum value of expr, ignoring null values.
 Min(Distinct|All]expr)
Minimum value of expr, ignoring null values.
 Stddiv([Distinct|All]x)
Standard derivation of n ignoring null value
 Sum([Distinct|All]n)
Sum value of n, ignoring null value.
 variance([Distinct|All]x)
Variance of n, ignoring null value

Group Function Syntax


Select [Column] group functions (column ..........) from table
[Where condition]
[Group by column]
[order by column];

 Distinct makes the function considers only non duplicate value.


 All makes it consider every value including duplicates.
 All group functions ignore null values. To substitute a value for null value use the NVL,
NVL2 or COALESCE functions.
 The oracle server implicitly sorts the results set ascending order when using a Group by
clause.
 Using the count function
Count Function has three formats:
i. Count(*)
ii. Count(expr)
iii. Count(Distinct expr)
 Count(*) returns the number of rows in a table that satisfy the criteria of the select
statement including duplicates rows and rows containing null values in any of the select
statement, count(*) returns the number of rows that satisfies the condition in the where
clause.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

 Count(expr)
Returns the non_null values in the column identified by expr.
 Count(Distinct expr)
Returns the number of unique, non_null values in the column identified by expr.

Using NVL Function with group functions


The NVL Functions forces group functions to include null values.
Ex:
Select Avg(NVL(commisiion-pet,0))
From emp;
The average is calculated based on all rows on all rows in the table, regardless of whether null
values are stored in commission-pet column.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

V.COMPLEX CONDITION QUERY CREATION


1.Subquery (Nested Query):
-Subquery is also known as nested queries.
-A Subquery is usually a select query within one of the clause in another select query
-Very powerful queries can be designed by using simple subqueries.
-Subqueries are of two types.
a)Single Row Subquery:
A Subquery that returns only one row of data. It is also known as scalar Subquery.
b)Multiple Row Subquery:
A Subquery that returns more than one row of data

i.SINGLE ROW SUBQUERY


Syntax
Select column list
From tablename
Where columnname operator
(select columnnames
From tablenames
Where condition)
*Subquery must be enclosed in parentheses
*Order by clause cannot be used in subquery
*subquery is used on the right side of the condition
* relational operators are used in the outer query condition.
* creating a table can be carried by using a subquery
Syntax
Create table tablename As select query;
*an existing table can be populated with a subqueryi.e insert with in a subquery does not create a
new table
Syntax
Insert into tablename(column list)
Select columnnames from tablenames where condition;
*update using a subquery as
Syntax
Update tablename
Set columnname=value or expression
Where column operator
(select subquery);
*delete using subquery
Syntax
Delete from tablename
Where columnname=(select subquery);
ii.MULTIPLE ROW SUBQUERY
Multiple row subquery returns more than one row.the operators used in single row subquery
cannot be used in multiple row subquery
Special operators used in multiple row subquery are
In:equals to any value in a list

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

All:compares the given value to every value returned by the subquery


Any or Some:compare the given value to each value returned by the subquery
*Any operator can be used in combination with other relational operators,it serves as or operator
As
<Any means less than the maximum value
>Any means higher than minimum value in the list
=Any means equal to any value in the list (similar to in)

*All operator can be used with relational operator it serves as And operator
>All means more than maximum value in the list
<All means less than the minimum value
=All is meangingless because no value can be equal to all values in the list

iii.CORRELATED SUBQUERY
In Correlated subquery the inner query can reference columns from the outer subquery .the inner
query is executed once fro each row in the outer query
EXISTS AND NOT EXISTS OPERATOR
The Exist and Not exist can be used in correlated queries.
The Exist operator checks if the inner query returns at least one rowit returns true or false
Not exist check if the inner query does not return a row,it is opposite of exist operator.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

VI.PL/SQL
There many disadvantages of SQL:
1.SQL does not have any procedural capabilities i.e.,SQL does not provide the programming
techniques of condition checking looping and branching.
2.SQL statements are passed to the oracle engine one at a time.
While processing an SQL sentence if an error occurs, the oracle engine displays its own error
messages.
*PL/SQL is a superset of SQL,
*PL/SQL is a block structured language that enables developers to combine the power of SQL
with procedural statements.
Advantages of PL/SQL:
1.PL/SQL sends an entire block of SQL statements to the oracle engine all in one go.
2.PL/SQL also permits dealing with errors as required, and facilitates displaying user-friendly
messages when errors are encountered.
3.PL/SQL allows declaration and use of variables in block code. There variables can be used
to store intermediate results of a quiery for later processing or calculate values and insert them
into an oracle table later.
4.Application written in PL/SQL are portable to any computer hardware and os.

GENERIC PL/SQL BLOCK:


PL/SQL permits the creation of structured logical block of code that describe processes which
have to be applied to data. A single PL/SQL block consists of a set of SQL statement clubbed
together and passed to the oracle engine entirely.
PL/SQL block has definite structure, which can be divided into
1.Declare Section:
Code blocks starts with a declaration section in which memory variables and other oracle
objects can be declared and if required initialize.

2.Begin Section:
It consists of a set of SQL and PL/SQL statements, which describe processes that have to be
applied to table data, actual data manipulation, retrieval, looping and branching constructs are
specified in this section.
3.Exception Section: This
section deals with handling of errors that arises during exception of data manipulation statement
which make up the PL/SQL code block.
4.End Section: This
marks the end of a PL/SQL block.

PL/SQL DATA TYPES:


The default data types that can be declared in PL/SQL are:
Number
Char
Date
Boolean
%type declares a variable or constant to have the same data type as previously defined variable
or of a column in a table or in a variable.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

PL/SQL VARIABLES
Variables in PL/SQL blocks are named variables.A variable mane must begin with a character
and can be followed by a maximum of 29 characters.
Assigning values to variables
The assigning of a value to a variable can be done in two ways:
1)Using tha assignment operator:=
2)Selecting or fetching table data values into variables.
Displaying message
DBMS-OUT PUT:This a package that include a number of procedures and function that
accumulate information in a buffer so that it can be retruved later.These function can also be
used to display message.
Put-line
It put a plece of information in the package buffer followed by an end of line marke.It can be
used to display a message.
To display message the server output should be on.

CONTROL STRUCTURES
The flow of control statement can be classified into following categories
1)conditional control
2)interative control
3)sequential control

1)CONDITIONAL CONTROL
PL/SQL allows the use of an IF statement to control the execution of a block of code.
Syntax
If condition then
Action
ELSE condition then
Action
ELSE
Action
ENDIF
2)ITERATIVE CONTROL
Iterative control indicate the ability to repeat or skip sections of code block.A loop marks of
sequence of statement that has to be repeated. A conditional statement that controls the number
of times a loop is executed always a companies loops
Syntax:Loop
Loop
<sequence of statement>
End loop;
Syntax:While loop
Syntax
While condition
Loop
Action

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

End loop
For loop
Syntax:For loop
For variable in[Reverse] start..end
Loop
<Action>
End loop
3)SEQUENTIAL CONTROL
Goto statement change the flow of control within apl/SQL block.This statement allows execution
of a section of code which is not in the normal flow of control.
Syntax
Goto <codeblockname>

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

VII.PROCEDURE AND FUNCTIONS


Procedures and functions are made up of
Declarative part
Executable part
An optional exception-handling part
Declarative part
the declarative part may contain the declaration of cursors,constants,variables,exceptions and sub
programmes.these objects are local to rthe procedures or functions.
Executable part:
The executable part is a PL/SQL block consisting of SQL and PL/SQL.statements that design
values, control executions and manipulate data .Actions are coded here.The data that is to be
returned back to the calling environment is also returned from here.
Exception handling part:
This part contain code that deal with exception that may be raised during the execution of code
in there executable part.
Advantages of using procedures or functions
security
Stored procedures and functions can help enforce data security.
Performance:
It improves the performance of DB system by reducing information sent over the
network,removing compilation step to execute the code
Memory allocation
The amount of memory used reduces as stored procedures or functions of have shared memory
capabilities.Only one copy of procedure needs to be loaded for execution by multiple users.
Productivity:
By writing procedures and functions redundant coding can be avoided increasing productivity.
Procedures versus functions:
The differences between procedures and functions are
A function must return a value back to the caller.a function can return only one value to the
calling SQL block.
By defining multiple out parameters in a procedure ,multiple values can be passed to the caller.
SYNTAX(procedure):
Create or replace procedure(schema)<procedure N.
(<Argument>{IN,OUT,INOUT} <data type >…..)
{IS,AS}
Variable declaration;
Constant declaration;
Begin
PL/SQL program body;
Exception
Exception PL/SQL block;
END;
SYNTAX (function)
Create or replace function [schema]<function var
(<Argument>1N<Datatype>…)
Return<Datatype> {IS, AS}

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

Variable declaration;
Constant declaration;
Begin
Pl/sql program body
Exception
Exception plo/sql block;
End;
Deleting a stored procedure/Function
Syntax:
Drop procedure<procedure Name>;
Drop function<function Name>;

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

VIII.CURSORS
The oracle engine used a work area for its internal processing in order to execute an SLQ
statement They work are is private to SQL operation and is called cursor.
The data that is stored in the cursor that is called the active data set.
The values that is retruved from the table are held in a cursor opened in memory by the oracle
engine.
This data is then transferred to the chent machine via network
In order to hold this data, a cursor is opened at the chent end.
Types of cursors
Cursor are classified depending on the circumstances under which they are opened.
If the oracle engine opened a cursor for its internal processing it is known as impuclt cursor.
A cursor opened for processing data through a PL?SQL block on demand is known as expucrt
cursor.
General cursor atttibutes
When an oracle engine creats an impuct or expuct cursor, cursor control variables are also
created to control the execution of cursor.
These are a set of four system variables which keep track of the current status of cursor .
The cursor variables can be accessed and used in PL/SQL code block.

ATTRIBUTR NAME DESCRIPTION


%ISOPEN Return true if cursor is opened,
False otherwise
%FOUND Return true If record was fetched success,
False otherwise
%NOT FOUND Return True If record was not fetched
success,False otherwise
%ROW COUNT Return Number of records processed from the
cursor

EXPLICT CURSOR:
When individual records in a table have to be processed inside a PL/SQL code a cursor is
used.Thus cursor will be declared and mapped to an SQL query in the declare section of the
PL/SQL block and used within its executable section.
Cursor declaration:
A cursor must be named and a query has to be mapped to it.
Three commands are used to control the cursor subsequently are OPEN,FETCH, and CLOSE
Open:
Initialization of a cursor takes place via the open statement
It defines a private SQL area named after the cursor name.
Executes the query associated with cursor.
Retrieves table data and populate them in private SQL area in memory.
Sets the cursor row pointer in Active Data Sets to the first record .
SYNTAX FOR CREATING A CURSOR:

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

Cursor cursorname is select statement:


Syntax for open:
Open cursor name.
Fetch:
The fetch statement retrieves the rows from the active set opened in the server into memory
anables declared in PL/SQL code block on client one row at a time.each time the fetch is
executed. The cursor pointer is advanced to the next row in the Active Data Set.
SYNTAX FOR FETCH:
Fetch cursor name into variable1, variable2………
CLOSING A CURSOR:
The close statement disables the cursor and the active set becomes undefined.This will release
the memory occupied by the cursor and the data set on the client and on the server.
Syntax:
Close cursor name;

Parameterized cursors:
The contents of the parameterized cursor will constantly change depending upon the value
passed to the parameter.
Syntax:
Cursor or cursorname(variable name Datatype) is
<select statement>
Opening:
Open cursorname(value/variable/expression)

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

IX.Database Triggers:
-Database triggers is stored in the database and is called automatically when a triggering event
occurs. A user cannot call a trigger explicitly.
-Triggering event is based on data manipulation language (DML) statement such as insert,
update or delete.
-A trigger can be created to fire before or after the triggering event.
-Execution of triggers is also known as firing the trigger.
Syntax:
Create [or replace] trigger triggername
Before [after|instead of triggering event on table|]
[for each row]
[when condition]
Declare
Declaration statement
Begin
Executable statement
Exception
Exception handling statement
End;

-Triggers are very useful for generating values for derived column keeping track of table access
preventing invalid entries, performing validity checks and maintaining security.
-Restrictions on triggers
->Triggers cannot use transaction control language statements such as commit, rollback or
savepoint.
->Variables in a triggers cannot be declared with long or long raw data type.-Instead of trigger
is based on view and it is a row trigger.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

X.Views:
-A view is an oracle object that gives the user a logical view of data from an underlying table or
tables.
-You can restrict what users can view by allowing them to see only a few columns from a table.
-Views can be either simple view or complex view.
a)Simple view:
It is based on a one table. It can contain group function. Data manipulation is always possible.
b)Complex view:
It is based on one or more tables. It may contain group function. Data manipulation is not always
possible
Syntax:
Create [or replace] view viewname [column aliases]
As <query expression>
[With check option [constraints constraintsname]]
[With read only]

-Every exception can use all clauses except order by.


-with check option applies to the where clause condition in the subquery. It allows insertion and
updating of rows based on the condition that satisfies the view.
Constraints name can be given to with check option.
-The read only option is to make sure that the data in the underlying table are not changed
through the view.
-user_view table contains data about views.
->select view_name from user_view;
This will give the list of all view_names.
->altering a view
When you alter an underlying table, the view becomes invalid. You need to recompile that
view to make it valid again. The alter view statement is used to recompilations of a view.
Alter view deptsal compile;

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

XI.Index:
-An index is another oracle object that is used for faster retrieval of rows from a table.
-Index can be created explicitly by using the create index statement.
-Once an index is created the user does not have to open or use the index with a command or a
statement the oracle serer uses the index to search for a row rather than scanning through the
entire table.
-Indexing reduces both search time and disk I/O.
-All indexes are maintained separately from the tables on which they are bared.
-Creating and removing an index does not affect the table at all.
-When a table is dropped all indexes based on that table are also removed.
Implicit indexes:
Implicit indexes are created when the primary key or unique constraints is defined such indexes
get the name of the constraints.
Explicit indexes:
A user can create explicit indexes based on non primary key or non unique columns or on any
combinations of columns for faster table access.
Simple indexes:
It is defined on a single column.
Composite indexes:
It is based on the combination of columns.
Syntax-for creating index
Create index indexname
On tablename(column1,column2……);
-Information of indexes is stored in user_indexes table.
-ex:
Create index stuidx
On student(last, first)
Index created

-Select index_name,table_name
From user_indexes
Where table_name=’student’

Gives result as
Index_name Table_name
Student_studentid_pk Student
Stu_idx Student
-First index was created automatically for the primary key constraints.
-Every insertion and deletion in a table updates the index which is added overhead on the system.
Rebuilding of an index:
-When a table goes through many changes(insertion, deletion, updating). Its advisable to rebuild
indexes based on that table
-Rebuilding compacts index data and improves performance.
Alter index stu_idx Rebuild;

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

XII.Transactions:
-In oracle the transaction starts with the first executable SQL statement that you issue.
-Transaction ends when one of the following occurs
->A comment or rollback transaction control statement is used.
->A DDL (create, alter, drop, rename or truncate) statement is executed (automatic
commit)
->A DCL (grant or revoke) statement is execution (automatic commit)
->A user properly exists (commit)
->The system crashes (rollback)
-Once a transaction ends, the new transaction starts with your next executable SQL statement.
-There is an environment variable Autocommit by default. It is set to OFF a user can set it to ON
or immediate by typing
Set Autocommit ON
Set Autocommit immediate

-When Autocommit is on every DML statement is written to the disk as soon as it is executed.
Every DML statement is committed implicitly and no rollback occurs with autocommit.
-Autocommit can be toggled back to off for an explicit commit.
-If system crashes any statement after the last commit are rolled back, so partial changes to tables
are not permanently written.
TCL (Transaction Control Language):
There are three TCL statements
a)Commit:
Ends the current transaction and write all changes permanently to the disk.

b)Savepoint n:
Makes a point in the current transaction.

c)Rollback [To savepoint n]:


Ends the current transaction by undoing all changes to the last commit, if a ‘To Savepoint’ clause
is not used. If its used it rollbacks the savepoint, removing the savepoint and any changes after
the savepoint, but it does not end the transaction.

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

XIII.PRIVILEGES
A user access needs s to be controlled in a shared multi-user oracle environment. Security can be
classified into two types.
a)System Security:
system security defines access to the database at the system level. It is implemented by assigning
a username and password allocation disk spaces and providing a user with the ability.
b)Database Security:
Database security defines a user access to various objects and the task a user can perform on
them.
-DBA can create users with create user statement. Once a user is created and a password
assigned the user needs privileges to do anything.
Syntax-for creating user
Create user username [profile profilename]
Identified by password
[Default tablespace tablespacename]
[Temporary tablespace tablespacename]
[Password expire] [Account unlock];

-A user needs at minimum two roles connected and resource by


Grant connect to username
Grant resource to username

-A user can change his own password with the password command.
-DBA assigns privileges based on the level of a views or on a user or on a users needs these
levels are called Roles.
-Roles are created by DBA.
-Object privileges specifies what a user can do with a database object such as table, sequence or
view. These are basic 11 objects privileges and each object has a set of privileges out of a total of
11 privileges.
1) Alter (table, sequence)
2) Insert (table, view)
3) Update (table, view)
4) Delete (table, view)
5) Select (table, view, and sequence)
6) References (table, view)
7) Index (table)
8) Execute (procedure, function, and package)
9) Under (view, user defined type)
10) Read (directory)
11) Write (directory)

-A user has his objects in his own schema. An owner has all possible privileges on the owner’s
objects. A user (owner) can grant privileges on objects from his own schema to other users or
rolls.
Syntax:

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

Grant objectprivileges (columnnames)/All


On objectname
To user/role/public
[With grant option];

-Column on which privileges are to be granted is specified by columnnames.


-Public grants privileges to all users.
-With grants option clause allows the guarantee to grant privileges to other users and rolls.
-Ex:
a) Grant select
On dept
To xman;

o/p-Grant succeeded

b) Grant select, insert, update


On emp
To student, xman
With grant option;

o/p-Grant succeeded
Revoke:
The revoke statement takes privileges not only from the granter but also from the users granted
privileges by the granter. If with grant option is given.
Syntax:
Revoke object privileges
On objectname
From user/role/public
[Cascade constraints]

-Ex:
Revoke ALL
On employee
From xman

NAME: ROLL NUMBER :


DBMS LAB DATE: PAGE NO :

XIV.Locking:
-Oracle uses automatic locking in the least restrictions to provide sharing of data with integrity.
-Oracle has two lock classes
a) Share lock
b) Exclusive lock

-Shared mode lock is used when users requires only a read on the data item.
-Exclusive mode lock is used when users want to insert, update and delete data items.

Syntax:
Lock table tablename in Share/Exclusive mode nowait

-Ex:
To lock emp in Exclusive mode
Lock table emp in Exclusive mode
Releasing locks:
A lock is released when either of the following occurs
->The transactions is committed successfully using commit.
->Rollback is performed
->Rollback to a savepoint will release lock set after the specified savepoint.

Locking rows for update:


-When DML query changes are done rows are locked until changes are committed.
-Suppose we want to view rows and also change them i.e. we want to lock rows for future
changes we use select for update of statement for such manual lock.

Syntax:
Select columnnames
From tablename
[Where condition]
For update of columnnames
[Nowait];

-Use of columnnames in for update of does not that the locking is at the column level. The entire
row is locked. Column names are just used for information.
-Nowait clause, tell the user instantaneously if another user has already locked the row if it is
omitted (Nowait clause) then we have to wait for any rows that have been locked by other
application to be released, you will not be able to do any processing on those rows until then.

-Ex:
Select ename, salary, commission
From emp
Where cid=544
For update of salary, commission
Nowait

NAME: ROLL NUMBER :

You might also like