0% found this document useful (0 votes)
253 views91 pages

DDL DML New

This document provides an overview of SQL (Structured Query Language). It discusses that SQL is the standard language for relational databases, is non-procedural, and is used to access data. It also describes the main SQL statements for data manipulation (SELECT, INSERT, UPDATE, DELETE), data definition (CREATE, ALTER, DROP), transaction control (COMMIT, ROLLBACK), and data control (GRANT, REVOKE). Additionally, it provides brief explanations of SQL concepts like data types, constraints, creating tables and more.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
253 views91 pages

DDL DML New

This document provides an overview of SQL (Structured Query Language). It discusses that SQL is the standard language for relational databases, is non-procedural, and is used to access data. It also describes the main SQL statements for data manipulation (SELECT, INSERT, UPDATE, DELETE), data definition (CREATE, ALTER, DROP), transaction control (COMMIT, ROLLBACK), and data control (GRANT, REVOKE). Additionally, it provides brief explanations of SQL concepts like data types, constraints, creating tables and more.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 91

SQL

• Stands for Structured Query Language


• Accepted as Standard Language(ISO,ANSI)
for Relational database
• Non Procedural Language
(what should be done/not how it should be done)
• Interface used to access data from database
SQL Statements
SELECT
Data retrieval
INSERT
UPDATE Data manipulation language (DML)
DELETE
MERGE
CREATE
ALTER
DROP Data definition language (DDL)
RENAME
TRUNCATE
COMMIT
ROLLBACK Transaction control
SAVEPOINT
GRANT
REVOKE Data control language (DCL)
SQL
DDL DML TC

CREATE INSERT ROLLBACK


ALTER UPDATE COMMIT
TRUNCATE DELETE SAVEPOINT
RENAME MERGE DCL

DROP
REVOKE
GRANT
DDL commands

• DDL -Data Definition Language

– CREATE: to create a new data structure.

– ALTER: to change an existing data structure.

– DROP: to remove an entire data structure.

– TRUNCATE : to remove all rows from table

– RENAME : to rename existing table


DML commands

• DML-Data Manipulation Language

– INSERT: to add records into the table

– UPDATE: to change column value in the table

– DELETE: to remove rows from the table


DCL

• DCL-Data Control Language

– GRANT :Allow access privileges to users


– REVOKE:Revoke or cancel access privileges
TCL

• TCL-Transaction Control Language.

– COMMIT :Save or enable DML changes to


the database.
– ROLLBACK: To undo DML changes till in a
transaction
– SAVEPOINT: To divide a transaction
SELECT command query

Syntax : SELECT (column_list )


FROM (table_list )
WHERE (row restriction)
GROUP BY (attribute names)
HAVING (group restriction)
ORDER BY (attribute name or names)
Commands
1. To Create Table
Create Table Tablename
(
field Name DataType (Size)
)
2. To Display The Content Of Table
Select * From Tablename;

3. To Display Structure Of Table


Desc Tablename;

4.To Display All Tables (For Current User)


Select * From Tab;
Oracle datatypes

· The different Datatypes available are:


· CHAR :To store character type of data

· VARCHAR2 :Similar to CHAR but can store variable


number of characters

· NUMBER :Stores fixed and floating point numbers

· DATE : Stores point-in-time values (i,e. date and


time) in a table
· LONG : Can store upto 2 GB of characters.
Similar to MEMO fields in FoxPro
Oracle datatypes
· RAW : Used to store binary data such as graphics,
sound etc.

· LONGRAW : Contains raw binary data otherwise the same


as a LONG column.
The values entered must be in hex notation.

· CLOB : Character Large Objects

· BLOB : Binary Large Objects

· NCLOB : National Language Support Character Large


Object

· BFILE : Binary File

• BINARY FLOAT : Requires 5 bytes.


10G
FEATURE
• BINARY DOUBLE : Requires 9 bytes.
Naming Rules

• Table names and column names:


– Must begin with a letter
– Must be 1–30 characters long
– Must contain only A–Z, a–z, 0–9, _, $, and
#
– Must not duplicate the name of another
object owned by the same user
– Must not be an Oracle server reserved
word
Creating Tables
• Create the table.
create table tab_1(c1 int,
c2 timestamp);

• Confirm creation of the table.

DESCRIBE tab_1

Name Null? Type

C1   NUMBER(38)

C2   TIMESTAMP(6)
What Are Constraints?

• Constraints enforce rules at the table


level.
• Constraints prevent the deletion of a
table if there are dependencies.
• The following constraint types are valid:
– NOT NULL
– UNIQUE
– PRIMARY KEY
– FOREIGN KEY
– CHECK
Constraint guidelines

• Name a constraint or the Oracle server will


generate a name by using the sys_cn
format
• Create a constraint:
– At the same time as the table is created
– After the table has been created
• Define a constraint at the column or table
level
• View a constraint in the data dictionary.
Defining Constraints

Column Constraint level

Column[Constraint constraint_name] constraint_type,

Table Constraint level

Column,…
[Constraint constraint_name] Constraint_type(column,…),
Not null Constraint

Ensures that null values are not permitted for the column

Empno Ename Job Comm Deptno


7839 King President 10
7698 Blake Manager 30
7782 Clark Manager 10
7566 Jones Manager 20

Not null Constraint Absence of Not null constraint


The NOT NULL constraint
Ensures values to be entered compulsorily
create table not_tab(i1 int not null,
i2 timestamp);
Table created.

SQL> insert into


not_tab values(1,systimestamp);
1 row created.
SQL> select * from not_tab;
I1 I2
116-OCT-16 09.56.03.864000 AM
Not null
SQL> insert into violation
not_tab(i2) values(systimestamp);
SQL> /
insert into
*ERROR at line 1:
ORA-01400: cannot insert NULL into (“scott"."NOT_TAB"."I1“)
The Unique key constraint
Allows Null
Ensures entered values to be unique

CREATE TABLE dept (


deptno number(2),
dname varchar2(12),
loc varchar2(13),
Constraint dept_dname_uk UNIQUE(dname));
The Unique key constraint

Ensures entered values to be unique


create table uni_tab(c1 int unique,
c2 varchar2(20));

Table created.

SQL> insert into


uni_tab values(100,'hp');

1 row created.
Unique
SQL >insert into violation
uni_tab values(100,'wipro')
SQL> /
insert into
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C005035) violated
The Unique key constraint
Allows Null
SQL> insert into
uni_tab(c2) values(‘tcs');

1 row created.

SQL >insert into


uni_tab(c2) values(‘cts‘)

SQL> select *
from uni_tab;

C1 C2
100hp
nulls  tcs
 cts
Primary Key
• What is a primary key?
– A primary key is a single field or combination
of fields that uniquely defines a record.
– A table can have only one primary key.

• Note: In Oracle, a primary key can not


contain more than 32 columns.
• A primary key can be defined in either a
CREATE TABLE statement or an ALTER
TABLE statement.
The Primary key constraint
Ensures entered values to be unique

create table pri_tab(c1 int primary key,


c2 date);

Table created.

SQL> insert into


pri_tab values(500,sysdate);

1 row created.
Unique
SQL >insert into violation
pri_tab values(500,‘12-feb-2010')
SQL> /
insert into
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C005036) violated
The Primary key constraint
Does not allow NULLS

SQL> insert into


pri_tab(c2)
values ('01-jan-2010');
insert into
*
ERROR at line 1:
ORA-01400: cannot insert NULL into
("SCOTT"."PRI_TAB"."C1")
Foreign Key
• What is a foreign key?
• A foreign key means that values in one table must also appear in
another table.
• The referenced table is called the parent table while the table with
the foreign key is called the child table. The foreign key in the child
table will generally reference a primary key in the parent table.
• A foreign key can be defined in either a CREATE TABLE statement
or an ALTER TABLE statement.

ALTER TABLE <TABLE_NAME>


ADD CONSTRAINT <constraint_name>
FOREIGN KEY (COL_NAME, COL_NAME)
REFERENCEs
PARENT_TABLE(COL_NAME1, COL_NAME2)
The Foreign key constraint
Ensures entered value depends on parent table
create table for_tab(c1 int references pri_tab,
c5 char(1));

Table created.
SQL> select * from pri_tab;

C1 C2
500 16-Oct-16

SQL> insert into


2 for_tab values Integrity
3 (501,'m'); constraint
insert into violation
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SYS_C005042) violated -
parent key not found
The Foreign key constraint
Ensures entered value depends on parent table

SQL> select * from pri_tab;

C1 C2
500 16-Oct-16

SQL> insert into


for_tab values Parent and
(500,'m'); child
matching
1 row created.
The Foreign key constraint
Allows NULL
SQL> insert into
for_tab(c5)
values (‘f’');
1 row created.

SQL> insert into


for_tab(c5)
values (‘m’);
1 row created.

SQL>select *
from for_tab;

C1 C5
500m
null  f
 m
Check Constraints

• Values within certain range

• Check constraints allow users to restrict possible attribute values for a


column to admissible ones.

Syntax
[constraint <name>] check(<condition>)

Example: The minimum salary of an employee is 500

create table EMP


(...,
SAL number(5,2) constraint check_sal check(SAL >= 500),

);

ALTER TABLE <table_name>


ADD CONSTRAINT <constraint_name> CHECK ( COL_NAME) CONDITION;
Check Constraints
SQL> create table
vote(age int check (age>=18),
name varchar2(10));

Table created.

SQL> insert into


vote values(17,'rahul');
insert into
*
ERROR at line 1:
ORA-02290: check constraint
(SCOTT.SYS_C005043) violated
CONSTRAINTS
P PRI_TAB
Not null NOT_TAB

I1 I2 C1 C2
1 14-JUL-12 08.06.16.870000 AM 500 14-JUL-12
13-JUL-12 08.06.16.870000 AM
x x
500 12-JUL-12

15-JUN-12
F x
UNI_TAB
UNIQUE FOR_TAB

C1 C5 Age>=18 VOTE
C1 C2
500 m
100 HP AGE NAME
100 WIPRO x 501 25 RAMU
x f x 17 RAHUL
TCS
m
CTS
CONSTRAINTS
UNIQUE Age>=18
ATM Not null RTO VOTE

REGNO VEHICLE AGE NAME


CARDNO PIN
KA04V9455 BYKE 25 RAMU
4321 1234

x
KA04V9455 CAR x 17 RAHUL
x 6789
TT

QUALIS
F
P ACCOUNTS
TRANS

ACCNO WD DEP
ACCNO NAME BALANCE
12345 NULL 10000
12345 RAHUL 5000
12345 NULL 10000
x 12345 SAYEN 10000
54321 NULL 5000
x SAYEN 5000 x
CONSTRAINT INFORMATION
select a.column_name,a.constraint_name,b.table_name,
b.constraint_type
from user_CONS_COLUMNS a,user_CONSTRAINTS b
where a.constraint_name=b.constraint_name
and a.table_name='&TABLE_NAME'
/

COLUMN CONSTRAINT TABLE CONSTRAINT SEARCH


_NAME _NAME _NAME _ TYPE _CONDITION
EMPNO PK_EMP EMP P
DEPTNO FK_DEPT EMP R
CONSTRAINT LEVEL

COLUMN LEVEL

TABLE LEVEL
34
CONSTRAINT LEVEL
create table Col_Tab(
cust_id int primary key,
cust_name varchar2(10),
address varchar2(50))

Create table Table_Tab(


order_id int ,
Ord_date timestamp,
Ord_qty number(11,2),
Constraint pk_tab primary key(order_id))
35
COMPOSITE KEY

Create table Comp_Tab(


empid int ,
Emp_name varchar2(15),
Passport number(15),
Constraint comp_key
primary key(empid,passport)
36
ALTER TABLE
Alter
Add clause
– Add new columns
– Add constraints

Modify clause
– Add not null constraint
– Change column data type
– Modify columnsize(width)

Drop clause
– Drop Columns
– Drop Constraints

RENAME clause
– Rename Columns
– Rename Constraints
ENABLE/DISABLE clause
– Enable Constraints
– Disable Constraints
TABLE
– Read Only --11G
– Read write --11G
SAMPLE TABLE
Create table Test1(
c1 int ,
c2 date,
c3 char(1),
c4 varchar2(10))
desc test1 Name Null? Type
C1   NUMBER(38)
C2   DATE
C3   CHAR(1)
38 C4   VARCHAR2(10)
Adding a Column
• Use the ADD clause to add columns.
New
colu
mn

alter table test1 add c5 timestamp;

• The new column becomes the last


column.
desc test1
Name Null? Type
C1   NUMBER(38)
C2   DATE
C3   CHAR(1)
C4   VARCHAR2(10)
C5   TIMESTAMP(6)
Adding a Constraint

SYNTAX

alter table <TABLENAME>


add constraint
<CONSTRAINT NAME>
<CONSTRAINT TYPE> ( Column name)

alter table test1


add constraint
pk_test1
primary key ( c1)
Modifying a Column
• You can change a column’s data
type, size, and default value.
alter table test1
modify c5 timestamp with time zone;

desc test1
Name Null? Type
C1   NUMBER(38)
C2   DATE
C3   CHAR(1)
C4   VARCHAR2(10)
C5   TIMESTAMP(6) WITH TIMEZONE
Dropping a Column
Use the DROP COLUMN clause to drop
columns you no longer need from the
table.

alter table test1 drop column c5;

desc test1
Name Null? Type
C1   NUMBER(38)
C2   DATE
C3   CHAR(1)
C4   VARCHAR2(10)
DROP COLUMN
SQL> CREATE TABLE TES_EMP AS SELECT * FROM EMP;
Table created.

SQL> ALTER TABLE TES_EMP ADD (NEWCOL


VARCHAR2(20));
Table altered.

SQL> ALTER TABLE TES_EMP SET UNUSED COLUMN


NEWCOL;
Table altered.
SQL> ALTER TABLE TES_EMP DROP UNUSED COLUMNS
Table altered.
Changing the Name of a column
• To change the column of a table

alter table <tablename>


rename column
<old column name> to <new column name>;

alter table test1


rename column c4 to c_4;

Name Null? Type


C1   NUMBER(38)
C2   DATE
C3   CHAR(1)
C_4   VARCHAR2(10)
Changing the Name of a constraint
• To change the name of the constraint
alter table <tablename>
rename constraint
<old constraint name> to <new constraint name>;

alter table test1


rename constraint pk_test1 to prk_test1;

select UC.column_name,UC.constraint_name,U.constraint_type
from user_constraints U join user_cons_columns UC
on u.constraint_name=uc.constraint_name
and U.table_name='TEST1'

COLUMN_NAME CONSTRAINT _NAME CONSTRAINT_TYPE

C1 PRK_TEST1 P
Dropping a Constraint

SYNTAX

alter table <TABLENAME>


Drop constraint
<CONSTRAINT NAME>

Alter table test1


drop constraint
prk_test1;
Enable a Constraint

SYNTAX

alter table <TABLENAME>


Enable constraint
<CONSTRAINT NAME>

Alter table e2
enable constraint
pk_pe;
Disable a Constraint

SYNTAX

alter table <TABLENAME>


disable constraint
<CONSTRAINT NAME>

Alter table e2
disable constraint
pk_pe;
CONSTRAINT STATUS
SELECT constraint_name,status
From user_CONSTRAINTS
Where table_name='&TABLE_NAME'
/

CONSTRAINT _NAME STATUS


PK_EMP ENABLED
FK_DEPT ENABLED
Disabling Constraints

• Execute the DISABLE clause of the


ALTER TABLE statement to deactivate
an integrity constraint
• Apply the CASCADE option to disable
dependent integrity constraints

ALTER TABLE emp


DISABLE CONSTRAINT emp_empno_pk CASCADE
READ ONLY TABLES
• Introduced in oracle 11G
READ
ONLY Prevents DDL,DML
changes during table
maintenance

SQL> ALTER TABLE EMP READ ONLY;


SQL> SELECT TABLE_NAME,READ_ONLY FROM
USER_TABLES;

TABLE_NAME READ_ONLY
------------------------------ -----------------
DEPT NO
BONUS NO
SALGRADE NO
EMP_1 NO
EMP YES
SQL> ALTER TABLE EMP READ WRITE;
WITHOUT CASCADE
EMP
DEPT EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7369 SMITH CLERK 7902 17-DEC-80 800 20


DEPTNO DNAME LOC
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
10 ACCOUNTIG NEWYORK
7521 WARD SALESMAN 7698 20-FEB-81 1250 500 30

20 RESEARCH DALLAS 7566 JONES MANAGER 7839 20-FEB-81 2975 20

30 SALES CHICKAGO 7654 MARTIN SALESMAN 7698 20-FEB-81 1250 1400 30

40 OPERATIONS BOSTON 7698 BLAKE MANAGER 7839 20-FEB-81 2850 30

7782 CLARKE MANAGER 7839 20-FEB-81 2450 10

7788 SCOTT ANALYST 7566 20-FEB-81 3000 20

ALTER TABLE emp 7839 KING PRESIDENT 20-FEB-81 5000 10

ADD CONSTRAINT 7844 TURNER SALESMAN 7698 20-FEB-81 1500 30

FK_DEPTNO 7876

7900
ADAMS

JAMES
CLERK

CLERK
7788

7698
20-FEB-81

20-FEB-81
1100

950
20

30

REFERENCES DEPT 7902 FORD ANALYST 7566 20-FEB-81 3000 20

7934 MILLER CLERK 7682 20-FEB-81 1300 10

DELETE *
FROM DEPT ERROR at line 1:
ORA-02292: integrity constraint
(SCOTT.FK_DEPTNO) violated - child
record found
WITH CASCADE
ALTER TABLE emp
ADD CONSTRAINT
FK_DEPTNO REFERENCES DEPT
ON DELETE CASCADE
EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
DEPT
7369 SMITH CLERK 7902 17-DEC-80 800 20
DEPTNO DNAME LOC 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
10 ACCOUNTIG NEWYORK
7521 WARD SALESMAN 7698 20-FEB-81 1250 500 30
20 RESEARCH DALLAS 7566 JONES MANAGER 7839 20-FEB-81 2975 20
30 SALES CHICKAGO 7654 MARTIN SALESMAN 7698 20-FEB-81 1250 1400 30

40 OPERATIONS BOSTON 7698 BLAKE MANAGER 7839 20-FEB-81 2850 30

7782 CLARK MANAGER 7839 20-FEB-81 2450 10

7788 SCOTT ANALYST 7566 20-FEB-81 3000 20

7839 KING PRESIDENT 20-FEB-81 5000 10


DELETE
FROM DEPT 7844 SALESMAN 7698 20-FEB-81 1500 30
TURNER

7876 ADAMS CLERK 7788 20-FEB-81 1100 20

7900 JAMES CLERK 7698 20-FEB-81 950 30

- DELETED ROWS 7902 FORD ANALYST 7566 20-FEB-81 3000 20

7934 MILLER CLERK 7682 20-FEB-81 1300 10


Dropping a Table
• All data and structure in the table is
deleted.
• Any pending transactions are committed.
• All indexes are dropped.
• You cannot roll back the DROP TABLE
statement.

DROP TABLE dept80;


Table dropped.
Changing the Name of an Object
• To change the name of a table, view,
sequence, or synonym, execute the
RENAME statement.
RENAME Test1 TO Test_1;
Table renamed.

• You must be the owner of the object.


FLASHBACK DROP
SQL> SELECT * FROM TAB;
TNAME TABTYPE CLUSTERID
BONUS TABLE  
DEFA_TAB TABLE  
DEPT TABLE  
EMP TABLE  
EMP1 TABLE  
SALGRADE
T1
TABLE
TABLE
 
  Drop table emp
T2 TABLE  
TIME_TAB TABLE  

SQL> SELECT * FROM TAB;

TNAME TABTYPE CLUSTERID


TIME_TAB TABLE  
T2 TABLE  
T1 TABLE  
SALGRADE TABLE  
EMP1 TABLE  
DEPT TABLE  
DEFA_TAB TABLE  
BONUS TABLE  
BIN$ePHAFq+3TeuRrejxb2wauQ==$0 TABLE  
FLASHBACK DROP
SQL> select original_name,object_name,droptime
from user_recyclebin

ORIGINAL_NAME OBJECT_NAME DROPTIME

EMP BIN$ePHAFq+3TeuRrejxb2wauQ==$0 2016-10-18:08:56:01

SQL> select * from “BIN$ePHAFq+3TeuRrejxb2wauQ==$0”;

TO RESTORE THE DROPPED TABLE

SQL> Flashback table emp to before drop;

SQL> Flashback table " BIN$ePHAFq+3TeuRrejxb2wauQ==$0“


to before drop;
FLASHBACK TABLE
20:05:00 SQL> select count(*) from new_emp;
COUNT(*)
----------------
Delete from
14 new_emp
where
SQL> select count(*) from new_emp; deptno=20
COUNT(*)
----------------
9
TO RESTORE THE DELETED ROWS

SQL> Flashback table new_emp to timestamp(sysdate-10/1440);

SQL> select count(*) from new_emp;


COUNT(*)
----------------
14
Truncating a Table
• The TRUNCATE TABLE statement:
– Removes all rows from a table
– Releases the storage space used by
that table

TRUNCATE TABLE detail_dept;


Table truncated.
• You cannot roll back row removal
when using TRUNCATE.
• Alternatively, you can remove rows
by using the DELETE statement.
DDL

STATEMENT DESCRIPTION
CREATE TABLE Creates a table

ALTER TABLE Modifies table structures

DROP TABLE Removes the rows & table structure

RENAME Changes the name of object (table, view etc)

TRUNCATE Removes all rows from table


DML/TC

STATEMENT DESCRIPTION
INSERT Adds a new row to the table

UPDATE Modifies existing rows in the table

DELETE Removes all/particular existing rows from the


table
COMMIT Makes all changes permanent

SAVEPOINT Used to divide the transactions

ROLLBACK Discards all pending data changes


INSERT Statement
• Add new rows to a table by using the
INSERT statement.

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


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

Only one row is inserted at a time with this


syntax
INSERT Statement

Default order Changed Substitution Copying Rows Inserting Nulls


order variable from Another
Default
Table
Value
INSERT Statement
DESCRIBE dept1

INSERT INTO
DEPT1 (DEPTNO,DNAME,LOC)
VALUES (50,’HR’,’MUMBAI’)

INSERT INTO
DEPT1 VALUES (50,’HR’,’MUMBAI’)

DEFAULT ORDER
INSERT Statement
DESCRIBE dept1

INSERT INTO
DEPT1 (DNAME,DEPTNO,LOC)
VALUES (‘HR’,50,’MUMBAI’)

CHANGED ORDER
INSERT Statement
DESCRIBE dept1

INSERT INTO
DEPT1 VALUES
(&DEPTNO,’&DNAME’,’&LOC’)

SUBSTITUTION VARIABLES
INSERT Statement
DESCRIBE dept1

INSERT INTO
DEPT1 SELECT DEPTNO,DNAME,LOC
FROM DEPT WHERE DEPTNO=30

USING ANOTHER TABLE


INSERT Statement
DESCRIBE dept1

INSERT INTO
DEPT1 ( DEPTNO,DNAME,LOC)
VALUES (50,NULL,NULL)

INSERT INTO
DEPT1 ( DEPTNO)
VALUES (50)

INSERTING NULLS
INSERT Statement
create table defa_Tab(c1 int primary key,
c2 timestamp default current_timestamp);

DESCRIBE Defa_tab
Name Null? Type
C1 NOT NULL NUMBER(38)
C2   TIMESTAMP(6)

INSERT INTO DEFA_TAB(C1) VALUES(100);

INSERT INTO DEFA_TAB VALUES(1000,DEFAULT);=>11G

C1 C2
10018-OCT-16 08.43.20.596000 AM
100018-OCT-16 08.43.32.004000 AM

INSERTING DEFAULT
UPDATE Statement
• Modify existing rows with the UPDATE
statement.
UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];

Update more than one row at a time,


if required.
UPDATE Statement
• Specific row or rows are modified if
you specify the WHERE clause.
ENAME SAL
SMITH 800

UPDATE emp
SET sal=1.1*sal
WHERE empno=7566;
1 row updated.

ENAME SAL
SMITH 880
UPDATE Statement

• All rows in the table are modified if


you omit the WHERE clause.

UPDATE emp
SET sal=1.1*sal;
14 rows updated.
DELETE Statement

You can remove existing rows from a table


by using the DELETE statement.

DELETE [FROM] table


[WHERE condition];
DELETE Statement

• Specific rows are deleted if you


specify the WHERE clause.
DELETE emp
WHERE ename=‘SMITH’;
1 row deleted.

• All rows in the table are deleted if you


omit the WHERE clause.
DELETE emp;

14 rows deleted.
MERGE

• DML Operation

• Introduced in Oracle 9i

• UPSERT
MERGE
SQL> INSERT INTO
2 S1 VALUES
SQL> CREATE TABLE 3 (555,'SACHIN');
S1(SL INT PRIMARY KEY, 1 row created.
NAME VARCHAR2(20));
SQL> INSERT INTO
2 S1 VALUES
Table created. 3 (666,'VEERU');
1 row created.
SQL> CREATE TABLE SQL> INSERT INTO
S2(SL INT PRIMARY KEY, 2 S2 VALUES
3 (666,'VIRAT');
NAME VARCHAR2(20)); 1 row created.

Table created. SQL> INSERT INTO


2 S2 VALUES
3 (777,'RAHUL');
1 row created.

SQL> COMMIT;

Commit complete.
MERGE
BEFORE MERGE AFTER MERGE

SQL> SELECT * SQL> SELECT *


FROM S1; FROM S1;
MERGE INTO S2 SL NAME
SL NAME
USING S1 ON ---------- --------------------
---------- -------------------- (S1.SL=S2.SL)
555 SACHIN 555 SACHIN
WHEN MATCHED THEN 666 VEERU
666 VEERU UPDATE SET
S2.NAME=S1.NAME
SQL> SELECT * SQL> SELECT *
WHEN NOT MATCHED
FROM S2; FROM S2;
THEN
INSERT VALUES
SL NAME (S1.SL,S1.NAME) SL NAME
---------- -------------------- ---------- --------------------
666 VIRAT 666 VEERU
777 RAHUL 777 RAHUL
555 SACHIN
INSERT
UPDATE
MERGE
1. Create a table EMP2 from emp table that contains the employee
numbers, employee names, and department numbers.

2. Add a column called SAL.

3. Insert a row into emp table with empno=9999 ename=‘test’

4. Implement MERGE operation on emp2


PRACTICE SESSIONS-1
1. Create the DEPT_tab table based on the following table instance chart.
Column name Datatype size

Id number 4

Name Varchar2
A. Populate the table with following data 25

Id Name
1001 Prithivi
1002 Agni
1003 Tejas
a. Add primary key constraint to the id column
1004
b. Add Trishulwith datatype varchar2 and size 15
a column called location
c. Update Location with ‘bangalore’,’chennai’,’hyderabad’,’delhi’ respectively for the rows
1,2,3,4.
d. Rename the column location as Place
e. Rename the table dept_tab as itpl_tab
f. Drop constraint primary key
g. Drop the table ITPL_tab
h. Flashback the dropped table itpl_tab.
PRACTICE SESSIONS-2
1. Create the IT_tab table based on the following table instance chart.
Column name Datatype size

Id number 2

Name Varchar2
A. Populate the table with following data 25

Id Name
Null TCS
5001 HP
B. Change
5001the datasize to fit the
INFIabove ID values

C. Try to Add a constraint primary key for the column id. Give your observations.

D. Try to Add a Unique constraint for the column id. Give your observations

E. Delete the row where name is INFI. Try to implement primary/unique constraint and give
your observations.
PRACTICE SESSIONS-3
1. Create a table called metrocities. Add appropriate columns
and datatypes with a check constraint on the city name
which should take only metro cities of India.

2. Create a table with 2 columns in which name should take


only upper names.
PRACTICE SESSIONS-4
1. Create a table called odd_even with 2 columns

Column name Datatype size


Id number 2
Description Varchar2 4

a. Insert 10 rows of data for Id column only.


(You should insert numbers from 1 to 10)
b. Update the description column with odd or even
depending upon the id column
PRACTICE SESSIONS-5
1. Create a table called emp5 as a
replica of emp.

a. Update the job column to change SALESMAN


to SALES_MAN. Select the job with ‘_’ using
Like operator.
b. Change the status of emp5 table to read only
c. Try inserting a row.
d. Try deleting a row.
e. Change the status of emp5 table to read write.
PRACTICE SESSIONS-6
Use employees table for the following:
1. Display employee data for a particular deptno. Value for deptno
should be taken by using substitution vairable.

2. Display the data by adding 100 to existing salary. Name the


increased salary as new salary. Sort the data on new salary.

3. Display the above data in descending order of ename.

4. Display the data in the format SMITH’s job is CLERK and SMITH’S
NEWSAL 900

5. Define a variable v_name with value ‘WARD’


6. Use v_name in select statement and display the details for
MR.WARD.
7. Define a variable v_date with value ‘03-dec-81’.
8. Use v_date in select statement and display all employees who have
joined after v_date.
PRACTICE SESSIONS-7
1. Create a table called STUDENT1

Column name Datatype Size CONSTRAINT

Student_id NUMBER 4 PRIMARY KEY


Student_name Varchar2 15
Result Char 1 Check ‘P’,’F’

a. Copy the rows from emp table for student_id,student_name


b. Update the result with ‘P’ for name containing ‘S’. For others
enter ‘F’
c. Display number of students along with each type of result
PRACTICE SESSIONS-8
1. Create a table called Leap_tab with 3 coumns.
Column name Datatype size
Id number 2
year Number 4
Remarks varchar2 15 id year
1 1990
a. Insert data for Id,year only as per the table 2 1986
Using substitution variable.
3 1972
b. Update Remarks column with Leap year /Not
Leap Year depending upon the year column 4 1966
5 2006
6 1954
7 2008
8 2010
PRACTICE SESSIONS-9
1. Create a table called student1
Column name Datatype Size CONSTRAINT
Student_id NUMBER 4 PRIMARY KEY
Student_name Varchar2 15

2. Create a table called phone


Column name Datatype Size CONSTRAINT
Student_id NUMBER 4 Foreign key
Phone_num number 10

a. Insert rows into both the tables

b. Display number of phones for each student_name


c. Display phone details for each student_name
TIMESTAMP

SQL> create table


time_tab(i int,i2 timestamp);
Table created.
SQL> alter table time_tab modify (i2 timestamp with time zone);
Table altered.
SQL> insert into time_tab values (1,'10-aug-2010 10:30:45.5555');
1 row created.
SQL> INSERT INTO TIME_TAB VALUES
(2,TIMESTAMP '2005-05-13 07:15:31.1234‘)
SQL> commit;
SQL> SELECT * FROM TIME_TAB;
I I2
213-MAY-05 07.15.31.123400 AM +05:30
110-AUG-10 10.30.45.555500 AM +05:30
BINARY FLOAT

REQUIRES 5 BYTES OF SPACE


INTRODUCED IN ORACLE 10G

CREATE TABLE binary_test (  


bin_float BINARY_FLOAT)

INSERT INTO binary_test


VALUES (39.5f)
BINARY DOUBLE

REQUIRES 9 BYTES OF SPACE


INTRODUCED IN ORACLE 10G

CREATE TABLE binary_test (  


Bin_double BINARY_DOUBLE)

INSERT INTO binary_test


VALUES (39.5d)
TOOLS FOR SQL

1.SQL * PLUS
2.ISQL * PLUS => obsolete
3.SQLPLUS WORK SHEET
4.TOAD
5.SQL DEVELOPER
6.ENTERPRISE MANAGER

You might also like