Sunteți pe pagina 1din 65

SQL

Stands for Structural 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
INSERT
UPDATE
DELETE

Data retrieval
Data manipulation language (DML)

CREATE
ALTER
DROP
RENAME
TRUNCATE

Data definition language (DDL)

COMMIT
ROLLBACK
SAVEPOINT

Transaction control

GRANT
REVOKE

Data control language (DCL)

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

VARCHAR2 :Similar to CHAR but can store variable


number of characters

NUMBER
numbers

DATE

:To store character type of data

:Stores fixed and floating point

: 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
sound etc.

: Used to store binary data such as graphics,

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
Object

BFILE

BINARY FLOAT : Requires 5 bytes.

BINARY DOUBLE

: National Language Support Character Large


: Binary File

: Requires 9 bytes.

10G
FEATURE

Creating Tables
Create the table.
CREATE TABLE dept1
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13));
Table created.

Confirm creation of the table.


DESCRIBE dept1

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

7839

King

President

10

7698

Blake

Manager

30

7782

Clark

Manager

10

7566

Jones

Manager

20

Not null Constraint

Comm

Deptno

Absence of Not null constraint

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
violation

SQL >insert into


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;

nulls

C1 C2
---------- -------------------100 hp
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
violation

SQL >insert into


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 06-OCT-10
SQL> insert into
Integrity
2 for_tab values
constraint
3 (501,'m');
violation
insert into
*
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 06-OCT-10
SQL> insert into
for_tab values
(500,'m');
1 row created.

Parent and
child
matching

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;

null

C1 C5
----- --f
500 m
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

Alter
ALTER TABLE
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

Adding a Column
New column
DEPT80

Add a new
column to the
DEPT80 table.

DEPT80

Adding a Column
Use the ADD clause to add columns.
ALTER TABLE dept80
ADD
(job_id VARCHAR2(9));
Table altered.

The new column becomes the last


column.

Adding a Constraint
SYNTAX

alter table <TABLENAME>


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

alter table e2
add constraint
pk_pe
primary key ( empno)

Modifying a Column
You can change a columns data
type, size, and default value.
ALTER TABLE dept80
MODIFY
(last_name VARCHAR2(30));
Table altered.

A change to the default value affects


only subsequent insertions to the
table.

Dropping a Column
Use the DROP COLUMN clause to drop
columns you no longer need from the
table.
ALTER TABLE dept80
DROP COLUMN
job_id;
Table altered.

Changing the Name of a column


To change the column of a table
SQL> alter table <tablename>
rename column
<old column name> to <new column name>;

SQL> alter table emp1


rename column
sal to salary;
Table altered.

Changing the Name of a constraint


To change the name of the constraint
SQL> alter table <tablename>
rename constraint
<old constraint name> to <new constraint

SQL> alter table emp1


rename constraint
pk_emp1 to pk1_emp1;
Table altered.

name>;

Dropping a Constraint
SYNTAX

alter table <TABLENAME>


Drop constraint
<CONSTRAINT NAME>

Alter table e2
drop constraint
pk_pe;

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;

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

WITHOUT CASCADE
EMP

DEPT
DEPTNO

EMPNO

DNAME

ENAME

JOB

MGR

HIREDATE

SAL

COMM

DEPTNO

7369

SMITH

CLERK

7902

17-DEC-80

800

20

7499

ALLEN

SALESMAN

7698

20-FEB-81

1600

300

30

7521

WARD

SALESMAN

7698

20-FEB-81

1250

500

30

7566

JONES

MANAGER

7839

20-FEB-81

2975

7654

MARTIN

SALESMAN

7698

20-FEB-81

1250

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

7839

KING

PRESIDENT

20-FEB-81

5000

10

7844

TURNER

SALESMAN

7698

20-FEB-81

1500

30

7876

ADAMS

CLERK

7788

20-FEB-81

1100

20

950

30

3000

20

1300

10

LOC

10

ACCOUNTIG

NEWYORK

20

RESEARCH

DALLAS

30

SALES

CHICKAGO

40

OPERATIONS

BOSTON

ALTER TABLE emp


ADD CONSTRAINT
FK_DEPTNO
REFERENCES DEPT
DELETE
FROM DEPT

*
ERROR
line 1:CLERK
7900 atJAMES
7698
20-FEB-81
ORA-02292: integrity constraint
7902
FORD
ANALYST
7566
(SCOTT.FK_DEPTNO)
violated
-20-FEB-81
child
record
found
7934
MILLER
CLERK
7682
20-FEB-81

20

1400

30

WITH CASCADE
ALTER TABLE emp
ADD CONSTRAINT
FK_DEPTNO REFERENCES DEPT
ON DELETE CASCADE
EMP

DEPT
DEPTNO

EMPNO

DNAME

ENAME

JOB

MGR

HIREDATE

SAL

COMM

DEPTNO

7369

SMITH

CLERK

7902

17-DEC-80

800

20

7499

ALLEN

SALESMAN

7698

20-FEB-81

1600

300

30

7521

WARD

SALESMAN

7698

20-FEB-81

1250

500

30

7566

JONES

MANAGER

7839

20-FEB-81

2975

7654

MARTIN

SALESMAN

7698

20-FEB-81

1250

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

7839

KING

PRESIDENT

20-FEB-81

5000

10

7844

TURNER

SALESMAN

20-FEB-81

1500

30

LOC

10

ACCOUNTIG

NEWYORK

20

RESEARCH

DALLAS

30

SALES

CHICKAGO

40

OPERATIONS

BOSTON

DELETE
FROM DEPT

- DELETED ROWS

7698

20

1400

30

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 dept TO detail_dept;
Table renamed.

You must be the owner of the object.

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
INSERT INTO
INTO table
table [(column
[(column [,
[, column...])]
column...])]
VALUES
(value
VALUES
(value [,
[, value...]);
value...]);

Only one row is inserted at a time with this


syntax

INSERT Statement

Default order

Changed Substitution Copying Rows Inserting Nulls


order
from Another
variable
Table

INSERT Statement
DESCRIBE dept1

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

INSERT
DEPT1

INTO
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

UPDATE Statement
Modify existing rows with the UPDATE
statement.
UPDATE
UPDATE
SET
SET
[WHERE
[WHERE

table
table
column
column == value
value [,
[, column
column == value,
value, ...]
...]
condition];
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.
UPDATE
UPDATE emp
emp
SET
sal=1.1*sal
SET
sal=1.1*sal
WHERE
WHERE empno=7566;
empno=7566;
11 row
row updated.
updated.

UPDATE Statement
All rows in the table are modified if
you omit the WHERE clause.
UPDATE
UPDATE emp
emp
SET
sal=1.1*sal;
SET
sal=1.1*sal;
14
14 rows
rows updated.
updated.

DELETE Statement
You can remove existing rows from a table
by using the DELETE statement.
DELETE
DELETE [FROM]
[FROM]
[WHERE
[WHERE

table
table
condition];
condition];

DELETE Statement
Specific rows are deleted if you
specify the WHERE clause.
DELETE
DELETE FROM
FROM emp
emp
WHERE
WHERE ename=SMITH;
ename=SMITH;
11 row
row deleted.
deleted.

All rows in the table are deleted if you


omit the WHERE clause.
DELETE
DELETE FROM
FROM emp;
emp;
14
14 rows
rows deleted.
deleted.

PRACTICE SESSIONS-1
1.

Create the DEPT_tab table based on the following table instance chart.
Column name

Datatype

size

Id

number

Name

Varchar2

25

A. Populate the table with following data

Id

Name

1001

Prithivi

1002

Agni

1003

Tejas

a. Add 1004
primary key constraintTrishul
to the id column
b. Add a column called location with datatype varchar2 and size 15
c. Update 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

PRACTICE SESSIONS-2
1.

Create the IT_tab table based on the following table instance chart.
Column name

Datatype

size

Id

number

Name

Varchar2

25

A. Populate the table with following data

Id

Name

Null

TCS

5001

HP

b. Try to5001
Add a constraint primary
INFI key for the column id. Give your observations.
c. Try to Add a Unique constraint for the column id. Give your observations
d. 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.

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
------- -------------------------------------------------1 10-AUG-10 10.30.45.555500 AM +05:30
2 13-MAY-05 07.15.31.123400 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
3.SQLPLUS WORK SHEET
4.TOAD
5.SQL DEVELOPER
6.ENTERPRISE MANAGER

S-ar putea să vă placă și