You are on page 1of 46

m 

M 
INTRODUCTION TO SQL
1. SQL Commands
2. Data Definition Language Commands (DDL)
3. Data Manipulation Language Commands (DML)
4. Transaction Control Language Commands (TCL)
5. Data Control Language Commands (DCL)
6. Logging onto the Database

DDL Commands
1. Creating a Table
2. Oracle¶s Naming Convention
3. Data Types
4. Constraints
5. The Primary Key Constraint
6. The Foreign Key Constraint
7. The Not Null Constraint
8. The Unique Constraint
M 
. The Check Constraint
10. Editing the scripts
11. Describe Command
12. Altering a table
13. Adding/dropping a Constraint
14. Dropping a table
15. SQL Command Files
16. SQL*Plus File and Set Commands

DML Commands
1. Select
2. Insert
3. Update
4. Delete
m 

4 SQL*Plus is a Structured Query Language supported by


Oracle. Through SQL*Plus we can store, retrieve, edit, enter
and run SQL commands and PL/SQL blocks.

4 Using SQL*Plus we can perform calculations, list column


definitions for any table and can also format query results in
the form of report
M
 

4 What is schema?

4 Overview of schema Objects


m
    

A m  is a collection of logical structures of data, or schema


objects. A schema is owned by a database user and has the same
name as that user. Each user owns a single schema. Schema objects
can be created and manipulated with SQL.
c  
 c 
K þ amples of schema objects include

‡ Tables
‡ Views
‡ sequences
‡ synonyms
‡ Inde es
‡ Database links
‡ Snapshots
‡ Procedures
‡ Functions
‡ Packages
       

Data definition language (DDL) statements enable you to


Create an object, alter the structure of an object and also
to drop the object created (c    
m 
    m 

      m ) :-

‡ CREATE
‡ ALTER
‡ DROP
‡ TRUNCATE
      

Data manipulation language (DML) statements query and


manipulate data in existing schema objects. These statements allow
to perform the following tasks.

‡ INSERT - Insert Data

‡ UPDATE - Update Data

‡ DELETE - Delete Data

‡ SELECT - Select Data


[     


 [

A transaction is a logical unit of work. All changes made to


the database can be referred to as a transaction. Transaction
changes can be made permanent to a database only if they are
committed. A transaction begin with an executable SQL
statement and ends explicitly with either rollback or commit
statements and implicitly, ie. Automatically, when a DDL
statement is used. TCL commands are
‡ c
‡ mc
‡ c
      


 

Data Control Language provides users with privilege


commands. The owner can allow other database users
access to the objects as per his/her discretion. Granting
privileges to others allows them to perform operations within
their purview.

Ê 
 c 
m

 m  


‡ Data Definition Language (DDL) Commands

‡ Data Manipulation Language (DML) Commands

‡ Transaction Control Commands

‡ Data Control Language Commands


c  
    

D 0hile naming a table the first letter should be an alphabet


D Oracle reserved words cannot be used to name a table
D Maximum length for a table name is 30 characters
D Two different tables should not have the same name
D Underscore, numerals and letters are allowed but not blank
space and single quotes
D If the user uses double quotes for naming the table like ³inf´
then upper and lowercase are not equivalent.
D For instance ³inf´, ³INF´ and ³inF´ are not the same
c   
CHAR - 1 ± 2000 Bytes

VARCHAR2 - 1 - 4000 Bytes

LONG - 2 GB
D Only one column in a table can have long data type. This should
not contain unique or primary key constraints
D The column cannot be indexed
D Procedures or stored procedures cannot accept long data type as
arguments

NUMBER - p = 38, s = 0
NUMBER(P) - fixed point
NUMBER(p,s) - floating point
S varies from -84 to 127
c  [ 
DATE - 7 BYTES (DD-MON-YY)
Jan 1 4712 BC to Dec 31, 4712 AD
RA0 - 2000 Bytes
(binary data, byte strings)

LONG RA0 - 2 GB
(Binary data of variable Length)

LOB Data Type


‡ CLOB - 4 GB
‡ BLOB - 4 GB
‡ BFILE - 4 GB
[ 

‡ [  are the basic unit of data storage in an Oracle database.


‡ Data is stored in  and 
.
‡ You define a table with a 
 (such as EMP) and set of
columns. You give each column a 

 (such as EMPNO,
ENAME, and JOB), a  (such as CHAR,VARCHAR2, DATE,
or NUMBER) and a   (the width might be predetermined by the
datatype, as in DATE) or  and   (for columns of the
NUMBER datatype only).
‡ A row is a collection of column information corresponding to a
single record«
  [ m

Purpose : To create a 
  the basic structure to hold user
data

CREATE TABLE emp


(
empno NUMBER,
ename VARCHAR2(10) ,
job VARCHAR2(),
mgr NUMBER,
hiredate DATE,
sal NUMBER(10,2),
comm NUMBER(,0),
deptno NUMBER(2)
)
m
  



  



  

  
§PPþD › › § › › adds › › at the end of
a line
CH§þ /old/new C //  changes  to   in
a line
CH§þ /› › C /› › deletes › › from a
line
CLþ§ BUFFþ CL BUFF deletes all lines
DþL (none) deletes the current
line
DþL  (none) deletes line 
DþL * (none) deletes the current
line
DþL L§ST (none) deletes the last line
DþL  (none) deletes a range of
lines ( to )

  




  

  
IPUT I adds one or more lines

IPUT › › I › › adds a line consisting


of › ›
LIST L lists all lines in the SQL
buffer
LIST  L or  lists line 
LIST L lists the current line

LIST L§ST L L§ST lists the last line


LIST  L  lists a range of lines (
to )
mM 



DESCRIBE
Lists the column definitions for the specified table, view, or synonym or
the specifications for the specified function or procedure.

To describe the table EMP, enter

SQL> DESCRIBE EMP


Name Null? Type
------------------------------ -------- ------------
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2()
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2)
DESCRIBE lists the above information.
  

Constraint is a mechanism used by oracle to prevent invalid


data into the table. They are also called as Integrity
Constraints.

Different Types of Integrity Constraints:

4 Domain Integrity Constraints


ot ull
Check

4 þntity Integrity Constraints


Unique
Primary Key

4 eferential Integrity Constraints


Foreign Key
[    
   

CREATE TABLE emp


(
empno NUMBER cm ,
ename VARCHAR2(10) cm  c
cm      
job VARCHAR2(),
mgr NUMBER
cm  m

hiredate DATE mm,
sal NUMBER(10,2) cm m
 m
comm NUMBER(,0) ,
deptno NUMBER(2) cm 
c
cm
m

)
m  




Commenting in SQL

Two ways of commenting are:

4 Single Line Commenting

4 Multi-Line Commenting
m  



m  
  m 

You can use "--" within SQL statements, PL/SQL blocks, or


SQL*Plus commands for commenting. Since there is no ending
delimiter, the comment cannot span multiple lines. For PL/SQL
and SQL, enter the comment after a command on a line or on a line
by itself:

-- Commissions report to be run monthly


DECLARE --block for reporting monthly sales
m  



  
  m  

Enter the SQL comment delimiters, /*...*/, on separate lines in your


command file, on the same line as a SQL command, or on a line in a
PL/SQL block. The comments can span multiple lines, but cannot be
nested within one another.

/* Commissions report
to be run monthly. */
COLUMN ENAME HEADING SALESMAN
COLUMN SAL HEADING SALARY FORMAT $,
COLUMN COMM HEADING COMMISSION FORMAT $,0
SELECT EMPNO, ENAME, SAL, COMM
FROM EMP
0HERE JOB = 'SALESMAN' /* Includes only salesmen. */
m      m    

mc
Followed by V6 or V7, sets compatibility to the version of Oracle
you specify. Setting COMPATIBILITY to V6 allows you to run
command files created with Version 6 of Oracle.
mc
Followed by a number format (such as $,), sets the default
format for displaying numbers in query results.
mm 
Followed by a number, sets the number of lines per page.
mm
Followed by ON, causes SQL*Plus to pause at the beginning of
each page of output (SQL*Plus continues scrolling after you enter
[Return]). Followed by text, sets the text to be displayed each time
SQL*Plus pauses (you must also set PAUSE to ON).
m  



m
Defines the substitution character (by default the ampersand "&")
and turns substitution on and off.
mm
The escape character instructs SQL*Plus to treat the substitution
character as an ordinary character rather than as a request for
variable substitution. The default escape character is a backslash
(\).
mc
Lists each line of the command file before and after substitution.
mcc
No AUTOTRACE report is generated. This is the default.
mcc
The AUTOTRACE report shows only the optimizer execution
path.
m  



mcc
The AUTOTRACE report includes both the optimizer execution
path and the SQL statement execution statistics.
mcc
Like SET AUTOTRACE ON, but suppresses the printing of the
user's query output, if any.
mccc
Turns autocommit on.
mccc
Turns autocommit off (the default).
mcc?
Commits changes after SQL commands or PL/SQL blocks.
m  



m  
 

Use the REMARK command on a line by itself in the command


file, followed by comments on the same line. To continue the
comments on additional lines, enter additional REMARK
commands. Do not place a REMARK command between different
lines of a single SQL command.

REMARK Commissions report


REMARK to be run monthly.
COLUMN ENAME HEADING SALESMAN
COLUMN SAL HEADING SALARY FORMAT $,
COLUMN COMM HEADING COMMISSION FORMAT
$,0
REMARK Includes only salesmen.
SELECT EMPNO, ENAME, SAL, COMM
FROM EMP
0HERE JOB = 'SALESMAN'
m  


  
To clear the buffer contents
SQL> CLEAR BUFFER

SQL> INPUT
1 COLUMN ENAME HEADING SALESMAN
2 COLUMN SAL HEADING SALARY FORMAT $,
3 COLUMN COMM HEADING COMMISSION FORMAT $,0
4 SELECT EMPNO, ENAME, SAL, COMM
5 FROM EMP
6 0HERE JOB = 'SALESMAN'
7
SQL> SAVE SALES
Created file SALES

You can also create a command file with a host operating system text
editor by entering EDIT followed by the name of the file, for example:
SQL> EDIT SALES
m  



  
 
you can retrieve a query from a file to the buffer with the GET
command:
SQL> GET ÷


  
 m
The START command retrieves a command file and runs the
command(s) it contains. Use START to run a command file
containing SQL commands, PL/SQL blocks, and/or SQL*Plus
commands. Follow the word START with the name of the file:

START file_name
(or)
SQL> @SALES
m  



m 
 m
To run a series of command files in sequence, first create a
command file containing several START commands, each
followed by the name of a command file in the sequence. Then run
the command file containing the START commands. For example,
you could include the following START commands in a command
file named SALESRPT:

START Q1SALES
START Q2SALES
START Q3SALES
START Q4SALES
START YRENDSLS
m  




mm   m


m
 
You can bypass the prompts for values associated with substitution
variables by passing values to parameters in a command file
through the START command

mc
 c!"Ê!
m"

m m #$
m  




 
   m    m
Through PROMPT and ACCEPT, you can send messages to the end user and
accept values as end-user input. PROMPT simply displays a message you specify
on-screen; use it to give directions or information to the user. ACCEPT prompts
the user for a value and stores it in the user variable you specify.


%
SQL> Clear buffer
Buffer cleared
SQL>input
1 Prompt ³Enter any one of 0the department Number 10,20,30,40 ´
2 Accept dno prompt ³Department Number : ³
3 Select * from emp where deptno = &dno
4
SQL> save prompt2
SQL> @prompt2
"Enter the department no 10,20,30,40"
Department Number : 10
m  



m    m
Bind variables are variables you create in SQL*Plus and then reference in
PL/SQL. If you create a bind variable in SQL*Plus, you can use the
variable as you would a declared variable in your PL/SQL subprogram
and then access the variable from SQL*Plus.
     m
You create bind variables in SQL*Plus with the VARIABLE command.
For example
VARIABLE ret_val NUMBER
      m
You reference bind variables in PL/SQL by typing a colon (:) followed
immediately by the name of the variable. For example
:ret_val := 1;
m     m
To display the value of a bind variable in SQL*Plus, you use the
SQL*Plus PRINT command. For example
PRINT ret_val
m  



mm
 
m
Executes the SQL command or PL/SQL block currently stored in the SQL
buffer.
m 

/
  m   
To define a user variable EMPLOYEE and give it the value
"SMITH", enter the following command:
SQL> DEFINE EMPLOYEE = SMITH
To confirm the definition of the variable, enter DEFINE followed by
the variable name:
SQL> DEFINE EMPLOYEE
SQL*Plus lists the definition:
DEFINE EMPLOYEE = "SMITH" (CHAR)
m  



m m 
  m
A substitution variable is a user variable name preceded by one or
two ampersands (&). 0hen SQL*Plus encounters a substitution
variable in a command, SQL*Plus executes the command as
though it contained the value of the substitution variable, rather
than the variable itself.
For example, if the variable SORTCOL has the value JOB and the
variable MYTABLE has the value EMP, SQL*Plus executes the
commands
SQL> BREAK ON &SORTCOL
SQL> SELECT &SORTCOL, SAL
2 FROM &MYTABLE
3 ORDER BY &SORTCOL;
as if they were
SQL> BREAK ON JOB
SQL> SELECT JOB, SAL
2 FROM EMP
3 ORDER BY JOB;
        m  

‡ A new table can be created using the data selected from


an existing table.

Example:-

Create table emp_bkup as Select * from Emp


  [ m

Purpose : To alter the definition of a Table

Example :-

Alter table emp add new_column number(2) default 10

Alter table emp add constraint ck_val check (new_column > 5)

Alter table emp modify column new_column number(4)

Alter table emp modify constraint ck_val disable

Alter table emp drop constraint ck_val

Alter table emp drop column new_column


   [ m


w  

Purpose : To remove a T§BLþ object and all its definitions

þ ample:-
Drop Table emp;

[
 

Purpose : To remove the entire set of data from the T§BLþ object.

þ ample:-
Truncate table emp;
m   m


Purpose:- To view the data in the table

Example:-

Select * from emp

Select column1, column2,« from emp;


M  m

Purpose:- To add rows to a table

INSERT INTO <table name> VALUES (a list of values)

Examples:-

INSERT INTO emp (empno, ename, job, sal, comm, deptno)


VALUES (780, 'JINKS', 'CLERK', 1000, NULL, 40)

INSERT INTO emp (empno, ename,deptno)


VALUES (780, 'JINKSµ,10);

INSERT INTO emp select empno, ename, job, sal, comm, deptno
From emp_bkup

 m


Purpose:- To change existing values in a table or in a view's


base table

Example:-

UPDATE emp set comm = 100


   m


Purpose:- To remove rows in a table or in a view's


base table

Example:-

Delete emp;

Delete from emp;