You are on page 1of 34

Adding, Making changes and

Deleting rows-DML
commands
INSERTing new rows into a table:
Syntax:
INSERT INTO table_name[(col1,col2,...)]
VALUES (value1,value2,...);

Examples:

INSERT INTO dept VALUES(50,’MARKETING’,’SAN JOSE’);

Inserting to specific column

INSERT INTO dept (DEPTNO,LOC) VALUES(60,’LONDON’);


Inserting using substitution values:
INSERT INTO DEPT VALUES(&deptno,’&dname’,’&location’);

When the command is run, promps for data everytime.


INSERTing DATE and TIME information:
When inserting a DATE value, in oracle 9i century will be
rounded off. If year is <50 it returns century as 20 and if year
is >=50 return century as 19.The date also contains time
information, which if not specified defaults to midnight
(00:00:00). If a DATE needs to be entered with century along
with time then TO_DATE function is to be used:
INSERT INTO emp VALUES(....,....,
TO_DATE(‘8/06/2053 10:45PM’,’DD/MM/YYYY HH:MIPM’,
.....,.....);
COPYING ROWS from another TABLE:

INSERT INTO TABLE[(col1,col2,.....)]


SELECT col1,col2,... FROM table [WHERE condition];

UPDATE
(Making changes to existing data)
UPDATE <table_name>
SET col_name=value WHERE condition;

Example:
UPDATE EMP set JOB=‘SALESMAN’,HIREDATE=SYSDATE,
SAL=SAL*1.1 WHERE ENAME=‘SCOTT’;

If WHERE clause is omitted ALL the rows will be updated.


DELETE
(Removing rows from table)

Syntax:

DELETE [FROM] <table_name>


[WHERE condition];

DELETE EMP WHERE ENAME=‘SMITH’;

If WHERE clause is eliminated ALL the rows will be deleted.


MERGE – update & insert

CREATE TABLE empl


as SELECT * FROM EMP WHERE MOD(EMPNO,2)=1;

UPDATE EMPL SET SAL=SAL/2;

MERGE INTO EMPL E1


USING EMP E2
ON (E1.EMPNO=E2.EMPNO)
WHEN MATCHED THEN
UPDATE SET E1.SAL=E2.SAL
WHEN NOT MATCHED THEN
INSERT VALUES(E2.EMPNO,E2.ENAME,E2.JOB,
E2.MGR,E2.HIREDATE,E2.SAL,E2.COMM,E2.DEPTNO)
TRANSACTION’s - TCL commands
Transaction is an operation against the database which
comprises a series of changes to one or more tables
Transactions are based on ACID properties
ACID Properties
(Atomicity, Consistency, Isolation, Durability)
Atomicity - Transactions are "all or nothing."

Consistency - Any given transaction transforms a consistent state


of the database into another consistent state, without necessarily
preserving consistency at all intermediate points.[*]
[*] A database state is consistent if and only if it satisfies all
defined constraints (consistency is just another word for integrity
in this context).
Isolation - Any given transaction's updates are concealed from all
other transactions, until such time as the given transaction
commits.

Durability - Once a given transaction commits, its updates

survive in the database,even if there's a subsequent system crash.

There are two types of transactions:


DML transactions -consists of any no of DML statements which
ORACLE treats as a single entity or logical unit of work.

DDL transactions - consists of only one DDL statment.


A transaction begins when the first executable DML or DDL
statement is encountered and ends when one of the following occurs:
COMMIT/ROLLBACK
DDL command is used
LOGOFF
Making changes permanent -
COMMIT
COMMIT performs following when used:
•makes changes in the current transaction permanent.
•erases all save point in the transaction
•ends the transaction
Once the changes are made it cannot be reverted.
Syntax:
COMMIT [WORK] or COMMIT;
UNDOING changes -ROLLBACK
ROLLBACK performs following when executed:
•UNDOES the work done till previous save or SAVEPOINT
•ends a transaction
•erases all savepoints in current transaction if SAVEPOINT option
is not used.

Syntax:
ROLLBACK [WORK] to [SAVEPOINT] savepoint_name
SAVEPOINT
Savepoints are used to divide a transaction into smaller portions.
Savepoints allow us to “hold” our work at any point of time and
later committing or undoing all or portion of it.
AUTOCOMMIT: This option will commit changes immediately
when DML statements are executed:
SQL>SET AUTOCOMMIT ON
..... ... ... ... ... ...
SQL>SET AUTOCOMMIT OFF

Note : Examples will be covered online. Participants are instructed to


make note of the same
ORACLE LOCKS
Oracle uses locks to control concurrent access to data.
Locks are mechanisms intended to prevent destructive
interaction between users accessing Oracle data.
Locks are used to ensure consistency and integrity.
Consistency means that the data a user is viewing or changing
is not changed (by other users) until the user is finished with
the data.
Integrity means that the database’s data and structures reflect
all changes made to them in the correct sequence.
Automatic Locking

Oracle locking is performed automatically and requires no


user action.
Implicit locking occurs for SQL statements as necessary,
depending on the action requested.
Oracle’s lock manager automatically locks table data at the
row level. By locking table data at the rowlevel, contention for
the same data is minimized.
Manual Locking

Under some circumstances, a user might want to override


default locking.
Oracle allows manual override of automatic locking features at
both the row level (by first querying for the rows that will be
updated in a subsequent statement) and the table level.
SELECT …FOR UPDATE
Trans-1 Trans-2
SELECT loc UPDATE scott.dept
FROM scott.dept SET LOC='BLORE'
WHERE deptno = 20 WHERE DEPTNO=20;
FOR UPDATE OF loc;
Note : until Trans-1
commits/rollsback, Trans-2 waits
Lock Duration

All locks acquired by statements within a transaction are held


for the duration of the transaction
DEADLOCK
Trans-1 Trans-2
SQL> UPDATE EMP SET SQL>UPDATE EMP SET
SAL=1000 WHERE COMM=1000 WHERE
ENAME='SMITH'; EMPNO=7566;
Updated updated
SQL>UPDATE EMP SET SQL>UPDATE EMP SET
SAL=2000 WHERE JOB=‘MANAGER’
ENAME=‘JONES’; WHERE EMPNO=7369;

Deadlock is automatically detected by oracle and will undo one of


the transactions and end both the transaction
VIEWS
• A view is like a “window” through which data on
tables can be viewed or changed.
• A view is derived from another table or view
which is referred to as the base table of the
view.
• A view is stored as select statement only. It is a
virtual table- i.e a table that does not physically
exist but appears to the user as if it exists.
• A view has no data of its own. It manipulates
data in the underlying base table.
Usefullness of VIEWS
• Restricting access to the database. SELECTing
from a view can display a restricted portion of
database.
• Allowing users to make simple queries to
retrieve the results from complicated queries.
Types of views:
1. Simple views 2. Complex views
Simple views derive data from only one table.
Contains no functions or groups of data.
Complex views are derived from multiple tables
Syntax:
CREATE [OR REPLACE] [FORCE] VIEW view_name
[(col1,col2,col3,....)]
AS
SELECT statement
[WITH CHECK OPTION [CONSTRAINT constraint_name]]

Example: Simple view


SQL> CREATE VIEW DEPT10VIEW
2 AS
3 SELECT EMPNO,ENAME,SAL
4 FROM EMP
5 WHERE DEPTNO=10
6 WITH CHECK OPTION;

View created.
SQL> SELECT * FROM DEPT10VIEW;
Complex view:
SQL>CREATE VIEW DEPT_SUMMARY
2 (DEPTNAME,MINSAL,MAXSAL,AVGSAL)
3 AS
4 SELECT DNAME,MIN(SAL),MAX(SAL),AVG(SAL)
5 FROM EMP,DEPT
6 WHERE EMP.DEPTNO=DEPT.DEPTNO
7* GROUP BY DNAME;

View created.
SQL> SELECT * FROM DEPT_SUMMARY;

DEPTNAME MINSAL MAXSAL AVGSAL

-------------- ---------- ---------- ----------

ACCOUNTING 1300 5000 2916.66667


SQL> CREATE VIEW EMP_DEPT_SALGRADE(EMPNAME,DESIG,
2 SALARY,DEPTNO,DEPTNAME,LOCATION,GRADE)
3 AS
4 SELECT ENAME,JOB,SAL,E.DEPTNO,
5 DNAME,LOC,GRADE
6 FROM EMP E,DEPT D,SALGRADE S
7 WHERE E.DEPTNO=D.DEPTNO AND
8 E.SAL BETWEEN S.LOSAL AND S.HISAL;

View created.
SQL> SELECT * FROM EMP_DEPT_SALGRADE;

SMITH CLERK 800 20 RESEARCH DALLAS 1

ADAMS CLERK 1100 20 RESEARCH DALLAS 1


Note :
•Data cannot be inserted into view which is derived using
another view but can be updated or deleted.
•Without check option a row can be inserted which does not
satisfy the condition but cannot be updated or deleted.
•You can use the OR REPLACE option to change the
definition of the view without dropping and re-creating it or
regranting object privileges previously granted on it.
•When the definition of the base table or base view changes,
the derived view will be automatically updated.
•The WITH CHECK OPTION clause specifies that INSERTs
and UPDATEs performed through the view cannot create
rows which the view cannot select, and therefore it allows
integrity constraints and data validation checks to be enforced
on data being inserted or updated
INLINE VIEWS
An inline view is not a schema object. It is a subquery with an
alias (correlation name) that you can use like a view within a
SQL statement.

SELECT D.DEPTNO,D.DNAME,SUM(E.SAL)
FROM DEPT D,(SELECT DEPTNO,SAL FROM EMP) E
WHERE E.DEPTNO=D.DEPTNO
GROUP BY D.DEPTNO,D.DNAME

An inline view is nothing more than a named subquery that


derives its rows at run-time during the execution of the outer
query.
MATERIALIZED VIEWS or SNAPSHOTS
A materialized view is a database object that contains the
results of a query.
For replication purposes, materialized views allow you to
maintain copies of remote data on your local node.
CREATE MATERIALIZED VIEW MATVIEW
REFRESH ON COMMIT
ENABLE QUERY REWRITE --10g
AS
SELECT
EMPNO,ENAME,JOB,SAL,E.DEPTNO,DNAME,LOC
FROM EMP E,DEPT D
WHERE E.DEPTNO=D.DEPTNO
Exercise :
2. Create a view which return department details and all aggregate of
each department. Exclude deptno column.
3. Create a view which returns details of employee, department and
respective grade excluding grade 5.
Sequences
The sequence generator generates sequential numbers, which
can help to generate unique primary keys automatically.

Sequences eliminate serialization (programmatically) and


improve the concurrency of your application.

Creating sequences
CREATE SEQUENCE MYSEQ
START WITH 5
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10
CYCLE
CACHE 5
The NOCYCLE option indicates that the sequence cannot
generate more values after reaching its maximum or minimum
value.
The CACHE option of the CREATE SEQUENCE command
pre-allocates a set of sequence numbers and keeps them in
memory so that they can be accessed faster. When the last of
the sequence numbers in the cache have been used, another set
of numbers is read into the cache.
Altering Sequences
ALTER SEQUENCE myseq
INCREMENT BY 10
MAXVALUE 100
NOCYCLE
CACHE 20;
Referencing a Sequence

Pseudocolumns NEXTVAL and CURRVAL are used


NEXTVAL -Each new sequence number is generated
CURRVAL-while the current sequence number can be
repeatedly referenced.
NEXTVAL and CURRVAL can be used as pseudo-column
names in SQL statements such as SELECTs, INSERTs, or
UPDATEs.
*examples to be given
Dropping Sequences
DROP SEQUENCE sequence_name;
Synonyms

A synonym is an alias for a table, view, snapshot, sequence,


procedure, function, package, or object type.
Synonyms let you refer to objects from other schemas without
including the schema qualifier.
CREATE [PUBLIC] SYNONYM synonym_name FOR
user.table;
Data dictionary table - user_synonyms
Dropping Synonyms
DROP SYNONYM synonym_name
DATABASE SECURITY
Privileges
A privilege is a right to execute a particular type of SQL
statement or to access another user’s object.
Examples of privileges:
• Connect to the database (create a session)
• Create a table
• Select rows from another user’s table
• Execute another user’s stored procedure
There are two distinct categories of privileges:
1. System privileges 2. Schema object privileges
System Privileges
A system privilege is the right to perform a particular action.
For example, the privileges to create tablespaces and to delete
the rows of any table in a database are system privileges.
There are over 60 distinct system privileges.
Schema Object Privileges
A schema object privilege is a privilege or right to perform a
particular action on a specific schema object:
Table
View
Sequence
Procedure
Function
Package
Roles

Roles are named groups of related privileges that you grant to


users or other roles.
Roles are designed to ease the administration of end-user
system and schema object privileges.
Predefined Roles
The following roles are defined automatically for Oracle
databases:
CONNECT
RESOURCE
DBA
EXP_FULL_DATABASE
IMP_FULL_DATABASE
Indexes
Indexes are used in Oracle to provide quick access to rows in a
table.
Create an index when:
A column contains a wide range of values

 A column contains a large number of null values
One or more columns are frequently used together in a WHERE clause or a
 join condition
 The table is large and most queries are expected to retrieve less than 2% to
4% of the rows in the table
Do not create an index when:
The columns are not often used as a condition in the query

The table is small or most queries are expected to retrieve more than 2% to
 4% of the rows in the table
The table is updated frequently

The indexed columns are referenced as part of an expression

Creating index
CREATE INDEX index_name ON
table_name(col_name,col_name)
CREATE INDEX emp_ind ON emp(ename)
SELECT * FROM EMP WHERE ENAME='SMITH';
Internal Structure of a B-tree Index
Top ‘N’ Query
ROWNUM – pseudocolumn (not a real column)
SQL> SELECT rownum,ename,job from EMP;
Can be used to limit the number of rows returned by a query
SQL> SELECT Empno, Ename, Job, Mgr, Hiredate,
Sal FROM Emp WHERE ROWNUM <= 5;
If an ORDER BY clause follows ROWNUM in the same query,
the rows will be reordered by the ORDER BY clause.
SQL> SELECT * FROM Emp
WHERE ROWNUM <= 5 ORDER BY
Sal desc;
A ROWNUM value is assigned to a row after it passes the
predicate phase of the query but before the query does any
sorting or aggregation.

You might also like