0% found this document useful (0 votes)
3 views

SQL_MANUAL_NEW

The document provides an overview of SQL, including data types, commands (DDL, DML, DCL), and functions. It explains how to create, modify, and manage tables, as well as how to manipulate data using various SQL commands. Additionally, it covers concepts such as data constraints, joins, and date functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

SQL_MANUAL_NEW

The document provides an overview of SQL, including data types, commands (DDL, DML, DCL), and functions. It explains how to create, modify, and manage tables, as well as how to manipulate data using various SQL commands. Additionally, it covers concepts such as data constraints, joins, and date functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

SQL

Department Of Computer Science Page No: 1


SQL
SQL Stands for Structured Query Language.

Data Types in SQL

1. CHAR(size) : This data type is used to store character strings values of fixed length.
The maximum number of characters (i.e. the size) this data type can hold is 255
characters.

2. VARCHAR (size) / VARCHAR2(size) : This data type is used to store variable length
alphanumeric data. The maximum this data type can hold up to 4000 characters.

3. DATE : This data type is used to represent date and time. The standard format is DD-
MON-YY as in 21 -JUN-04.

4. NUMBER (P, S) : The NUMBER data type is used to store numbers (fixed or floating
point). P:precision, S:scale.

5. LONG : This data type is used to store variable length character strings containing up
to 2 GB.

6. RAW / LONG RAW : The RAW / LONG RAW data types are used to store binary
data, such as digitized picture or image.

In SQL we have three types of commands or languages , They are DDL,DML,DCL

1. D.D.L ( Data Definition Language )

a. Create Table : This command is used to create a table

Syntax : create table tablename (Attr1 Datatype (size),


Attr2 Datatype (size),
…............
Attrn Datatype(size));

Ex : SQL> create table student


(Roll_No number(5),
Name varchar2(10),
Sec char(1),
Address varchar2(20),
Phone_No varchar2(8)); (Press Enter)

( Table Created )

b. Alter Table (Add/Modify) : This command is used to modify or add a new


column (attribute) to an already existing table.

Department Of Computer Science Page No: 2


Syntax : alter table tablename add/modify ( Attr_Name Datatype (size) .......... );

Ex : SQL> alter table student modify (Phone_No varchar2(10));


Table Modified
Ex: SQL> alter table student add (Gender char(1));
Table Modified

c. Rename Table : This Command is used to change the name of an already


existing table.

Syntax : Rename OldTableName to NewTableName;

Ex : Rename Student to stu;


Table Renamed.

d. Drop Table : This command is used to completely remove the table structure
along with the values from the database.

Syntax : drop table Table Name ;

Ex : drop table student;


Table Deleted .

e. Truncate Table : This command is used to remove all the values present in
the database. It does not remove the table (or) database structure.

This command is similar to a DML Command but cannot rollback

Syntax : truncate table tablename ;


Ex: truncate table student;

f. Describe Table : It displays the contents of the database structure.

Syntax : Desc Table Name ;

Ex : desc student;
Name varchar2(20)
Class varchar2(10)
Sec char(1)

2. D.M.L (Data Manipulation Language )

DML Commands are used to add/change/ remove/retrieve records from the


database.

a. Insert : This command is used always to create a new row and insert the values

Syntax 1 : Inserting data into all fields :

Department Of Computer Science Page No: 3


insert into tablename values (val1, val2, .... Valn);

Ex : 1 insert into student values (101,'Ram','B.Sc','A');

Syntax 2 : Insert data into multiple records :

insert into Table Name values (&val1,&val2, ....& Valn);

Syntax 3 : Insert data into specific fields :

insert into tablename (field1,field2,... fieldn) values (val1,val2,..... valn);

Ex:2 insert into student (Name,Class,Sec,Roll_No)


values('Robert','B.C.A','A',102);

b. Update : This command is used to modify an attribute value in the already


existing record. It is also used to add a value in an already existing record.

Syntax :
Update tablename
SET condition
where condition;

Ex: update student


set class = 'B.Sc', sec = 'B’; (Press Enter)
( 2 records modified )

If the user wants to update specific records then he should use 'Where' Clause.

Ex: (1) update student


set class='B.Sc', sec='B'
where rno=204;

(2) update student


set tot=m1+m2;

(3) update student


set avg=tot/2;

c. Delete : Delete Command removes the records from the table temporarily until
a commit command is used or a DDL command is executed.

Before using a Commit or a DDL command if we execute a rollback command


then whatever records have been deleted will be restored in the database.

Syntax : delete
from tablename
where condition;

Department Of Computer Science Page No: 4


Ex : (1) delete
from student; (Press Enter)

3 Rows deleted

(2) delete
from student
where rno=103;

1 Record deleted

d. Select : Select command is used to retrieve the values from the database based
on selection criteria.

Syntax :
select * or (column1,column2,..... )
from tablename
where condition;

Ex :1 select *
from student;

Ex :2 select rollno,class
from student
where sec=’c’;

3. D.C.L (Data Control Language )


The commands that are used to control the flow of data in the data base or
metadata are called as data control language commands.
They are Save point, commit, rollback, grant, revoke, etc..

Ex: SQL>commit;

SQL>rollback;

Dual Table
DUAL is a table owned by SYS.
Dual is a small Oracle worktable, which consists of only one row and one column, and
contains the value ‘x’ in that column.

The structure of the dual table

Department Of Computer Science Page No: 5


SQL>DESC DUAL;

Output:
NAME Null? TYPE
Dummy VARCHAR2 (1)

If the dual table is queried for records the output is as follows:

SELECT * FROM DUAL;


Output:
X

Ex : SELECT 2*2 FROM DUAL;


Output:
2*2
4

GROUP BY and HAVING Clause


The group by clause is another section of the select statement which is an optional
clause.
This clause groups rows based on distinct values that exist for specified column.
i.e, It creates a data set containing several sets of records grouped together based on
condition if possible using having clause.

Syntax : select (column_name1,column_name2,....)


from tablename
group by condition;

Ex : 1 select department,sum(salary)
from emp
group by department;

The above SQL Statement groups the employees based on departments and
calculates the sum of the salary.

ORDER BY Clause
Order by clause is used to retrieve the rows from the table in a sorted order.
The order can be either ascending order or descending order depending on the
condition specified in the select statement.
The order by clause by default displays the data in the ascending order.

For Descending order simply specify the word "desc" .

Department Of Computer Science Page No: 6


Syntax : select * from tablename
order by column_name1,column_name2 [sort_order];

Ex : select emp_id,ename,sal
from employee
order by sal desc;

ORACLE FUNCTIONS

1.Group Functions (Aggregate Functions) :


Functions that act on a set of values are called Group Functions.

For example, SUM.

2.Scalar Functions (Single Row Functions) : Functions that act on only one value at a
time

String Functions : For String Data type


Numeric Functions: For Number Data type
Conversion Functions: For Conversion of one Data type to another.
Date Functions: For Date Data type

Aggregate Functions

1. Avg : Avg function computes the average of the given data.

Syntax : Avg();

Ex: select Avg(salary) from emp;

2. Count : This function counts the number of rows in a given column

Syntax : Count();

Ex: select count(Deptno) from emp;

3. Count(*) : Returns the number of rows in the table including duplicates and those
with nulls.

Syntax : Count (*);

Ex: select count(*) from emp;

4. Max : This function returns the maximum value from a given column
Syntax : max ();

Ex : select max(sal) from emp;

Department Of Computer Science Page No: 7


5. Min : This function returns the minimum value from a given column or expression.

Syntax : min ();

Ex : select min(sal) from emp;

6.Sum : This function returns the sum of values in a given column or expression.

Syntax : sum ();

Ex : select sum(sal) from emp;

2. Scalar Functions
Department Of Computer Science Page No: 8
Department Of Computer Science Page No: 9
Department Of Computer Science Page No: 10
Department Of Computer Science Page No: 11
Department Of Computer Science Page No: 12
Department Of Computer Science Page No: 13
DATE CONVERSION FUNCTIONS

The DATE data type is used to store date and time information.

TO_DATE: Converts a character field to a date field.

Syntax: TO_DATE(char{format})

Ex:
INSERT INTO CUST (DOB) VALUES( TO_DATE(’25-JUN-1952 10:55 A.M.’,
‘DD-MON-YY HH:MI A.M.’));

DATE FUNCTIONS
ADD_MONTHS: Returns date after adding the number of months specified in the
function.
Syntax: ADD_MONTHS(d, n)

Ex:

SELECT ADD_MONTHS(SYSDATE, 4) FROM DUAL;

Output:
Add Months
01-NOV-04

LAST_DAY: Returns the last date of the month specified with the function.
Syntax: LASTDAY(d)

Ex: SELECT SYSDATE, LAST_DAY(SYSDATE) FROM DUAL;

Output:
SYSDATE - LastDay
01-JUL-04 31-JUL-04

MONTHS_BETWEEN: Returns number of months between dl and d2.

Syntax: MONTHS_BETWEEN(d1, d2)


Ex: SELECT MONTHS_BETWEEN(2-FEB-92’, ‘02-JAN-92’)
FROM DUAL;
Output:
Months
1

NEXT_DAY : Returns the date of the first weekday named by char that is after the
date named by char must be a day of the week.

Syntax: NEXT_DAY(date, char)


Ex: SELECT NEXT_DAY(’06-JULY-02’, ‘Saturday’) FROM DUAL;
Department Of Computer Science Page No: 14
Output:
NEXT DAY
13—July—02

MANIPULATING DATES IN SQL USING THE DATE()

TO CHAR : The TO CHAR function facilitates the retrieval of data in a format


different from the default format.
Syntax : TO_CHAR(< date value> [,<frmt>])

Example 1:
SELECT TO_CHAR(SYSDATE, ‘DD-MM-YY’) FROM DUAL;

Example 2:
SELECT TO_DATE (‘06/07/02’, ‘DD/MM/YY’) FROM DUAL;

Department Of Computer Science Page No: 15


DATA CONSTRAINTS
TYPES OF DATA CONSTRAINTS

The PRIMARY KEY Constraint


A primary key is one or more column(s) in a table used to uniquely identify each
row.

Features of Primary key


1. Primary key is a column or a set of columns that uniquely identifies a row. Its main
purpose is the Record Uniqueness
2. Primary key will not allow duplicate values
3. Primary key will also not allow null values
4. Primary key is not compulsory but it is recommended
5. Primary key helps to identify one record from another record and also helps in
relating tables with one another
6. Primary key cannot be LONG or LONG RAW data type
7. Only one Primary key is allowed per table
8. Unique Index is created automatically if there is a Primary key
9. One table can combine upto 16 columns in a Composite Primary key

PRIMARY KEY Constraint Defined At Column Level


Syntax: Column Name Data type(size) PRIMARY KEY

Ex 1:
Create table student (Roll_No number(4) primary key,
Name varchar2(20),
class varchar2(15),
Sec char(1));

The Foreign Key (Self Reference) Constraint


Foreign keys represent relationships between tables.
A foreign key is a column (or a group of columns) whose values are derived from
the primary key or unique key of some other table.

Features of Foreign Keys


1. Foreign key is a column(s) that references a column(s) of another table (it can refer
the same table also).
2. Parent that is being referenced has to be unique or Primary key
3. Child may have duplicates and nulls
4. Foreign key constraint can be specified on child but not on parent
5. Parent record can-be deleted provided no child record exist
6. Master table cannot be updated if child record exist
Department Of Computer Science Page No: 16
FOREIGN KEY Constraint Defined At The Column Level

Syntax : ColumnName DataType(Size)


REFERENCES tablename( ColumnName)
[ON DELETE CASCADE]

The Unique Key Constraint

Key point about Unique Constraint:


1. Unique key will not allow duplicate values
2. Unique index is created automatically
3. A table can have more than one Unique key which is not possible in Primary key
4. Unique key can combine upto 16 columns in a Composite Unique key
5. Unique key can not be LONG or LONG RAW data type

UNIQUE Constraint Defined At The Column Level


Syntax : ColumnName Datatype (Size) UNIQUE

NULL Value Concepts

Principles Of NULL Values


➢ Setting a NULL value is appropriate when the 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 number and is not
equivalent to spaces if the data type is character
➢ A NULL value will evaluate to NULL in any expression (e.g. NULL multiplied by 10 is
NULL)
➢ NULL value can be inserted into columns of any data type
If the column has a NULL value, Oracle ignores any UNIQUE, FOREIGN KEY,
CHECK constraints that may be attached to the column

The CHECK Constraint

CHECK constraint defined at the column level:


Syntax :ColumnName Datatype(Size) CHECK (Logical Expression)

DEFAULT:
-------------------------------------------------------------------
Syntax:ColumnName Datatype(Size) default(value)

Department Of Computer Science Page No: 17


JOINS
To retrieve data based on multiple tables having column constraints applied on
the tables,we us Joins.
In Joins, we combine two tables.
Tables are joined on columns that have the same data type and data within the tables.

Different Types of Joins :


1. Cartesian Join
2. Equi Join
3. Self Join
4. Outer Join

Stu Table
RNO NAME Group Stu_marks Table
2001 Ram M.P.Cs RNO Maths Computer
2002 Robert M.E.Cs 2001 95 85
2003 Rahim M.S.Cs 2002 75 95

1. Cartesian Join : In Cartesian Join each record of table A is associated with all the records of
table B without any condition.

Syntax : select *
from Table A, Table B; (Press Enter)

Ex: select *
from Stu , Stu_marks ;

RNO NAME Group RNO Maths Computers


2001 Ram M.P.Cs 2001 95 85
2001 Ram M.P.Cs 2002 75 95
2002 Robert M.E.Cs 2001 95 85
2002 Robert M.E.Cs 2002 75 95
2003 Rahim M.S.Cs 2001 95 85
2003 Rahim M.S.Cs 2002 75 95

2. Equi Join : In Equi Join we combine two tables and get the desired task by applying an equality
condition in the where clause.

Syntax : select *
from Table A, Table B
where Equality_Condition;

Ex : select Stu.Rno,Name,Computers
from Stu,Stu_marks
where Stu.Rno=Stu_marks.Rno;

Department Of Computer Science Page No: 18


RNO NAME Computers
2001 Ram 85
2002 Robert 95

3. Outer Join : Outer Joins are used to display those rows which are common. ( i.e,
Satisfying the condition ) and even those rows which are not satisfying the condition.
There are 3 types of outer joins :
a. Left Outer Join
b. Right Outer Join
c. Full Outer Join

Dept Table : Project Table :

Dept_Id D. No. P. No P. No P. Name


101 2 11 44 D
97 5 22 11 A
120 4 33 22 B

a.) Left Outer Join : It displays all those rows which are common to both the tables that are
satisfying the condition and also those unmatched rows of the table which is specified at the
left hand side. The values of attributes corresponding to second table are considered as
'NULL' Values.

Syntax : select * from Table A left outer join Table B where condition ;

Ex : select * from dept left outer join project where Dept.P.No=Project.P.No ;

Dept_Id D.No. P.No P.No P.Name


101 2 11 11 A
97 5 22 22 B
120 4 33 NULL NULL

b.) Right Outer Join : Right Outer Join is same as left outer join but the only difference is the
unmatched rows of 2nd Table which is specified on the right hand side are displayed along
with the common rows of both the tables

Syntax : select * from Table A right outer join Table B where condition ;

Ex : select * from dept right outer join project where Dept.P.No=Project.P.No ;

Dept_Id D.No. P.No P.No P.Name


NULL NULL NULL 44 D
101 2 11 11 A
97 5 22 22 B

Department Of Computer Science Page No: 19


c.) Full Outer Join : It is same as left or right outer join, but the only difference is unmatched
rows of both tables are displayed along with the matched rows.

Syntax : select * from Table A right outer join Table B where condition ;

Ex : select * from dept full outer join project where Dept.P.No=Project.P.No ;

Dept_Id D.No. P.No P.No P.Name


101 2 11 11 A
97 5 22 22 B
120 4 33 NULL NULL
NULL NULL NULL 44 D

4. Self Join : In some situation we find it necessary to join a table to itself, this is referred as Self
Join.
In self Join two rows from the same table combine to form a resultant row.
To join a table to itself, Two Copies of the same table have to be opened in memory in
different locations and opened with temporary names , using aliasing.

Eg :stud

RNO NAME address


2001 Ram Hyd
2002 Robert Hyd
2003 Rahim Sec

Find all the students who has the same address as Ram.(Ans : Robert)

Select s1.name
From stud s1,stud s2
Where s1.address=s2.address and s2.name=’Ram’;

Output:
Name
Ram
Robert

Department Of Computer Science Page No: 20


Explanation:
Cartesian product of stud s1*stud s2 is
S1.RNO S1.NAME S1.address S2.RNO S2.NAME S2.address
2001 Ram Hyd 2001 Ram Hyd
2001 Ram Hyd 2002 Robert Hyd
2001 Ram Hyd 2003 Rahim Sec
2002 Robert Hyd 2001 Ram Hyd
2002 Robert Hyd 2002 Robert Hyd
2002 Robert Hyd 2003 Rahim Sec
2003 Rahim Sec 2001 Ram Hyd
2003 Rahim Sec 2002 Robert Hyd
2003 Rahim Sec 2003 Rahim Sec

In this case

S1.address=s2.address are same in rows 1,2,4,5,7,8


But the condition s1.address=s2.address and s2.name=ram is satisfied only for rows 1,4
There fore : select s1.name will result in Ram and Robert.

SET OPERATORS
Set Operators are used to generate queries based on multiple tables.

The different Set Operators availabe are :


1. Intersect
2. Union
3. Minus
4. Union all

1.Intersect : The intersect clause will merge the common rows retrieved by multiple tables into a
single set.

Syntax : select *
from Table A
where Condition
INTERSECT
select *
from Table B
where Condition;

Ex : select deptno
from dept
INTERSECT
select deptno
from emp;

Department Of Computer Science Page No: 21


2. Union : The union clause will merge the rows retrieved by multiple tables into a single set.

Syntax : select *
from Table A
where Condition
UNION
select *
from Table B
where Condition;

Ex :
select deptno from dept
union
select deptno from emp;

3. Minus : The Minus clause will remove the rows retrieved from Table B that are present in
Table A and outputs the remaining available rows in Table A

Syntax : select *
from Table A
where Condition
Minus
select *
from Table B
where Condition;

Ex : select deptno from dept


Minus
select deptno from emp;

NESTED QUERIES
A nested query is a form of an SQL statement that appears inside another SQL
statement.
The statement containing a sub query is called a parent statement.
The parent statement uses the rows returned by the sub query.

Ex: select * from student_marks where rno=(select rno from student where name='Ram');

The above Nested Query will display All the Details of the Student Ram. The inner query will
generate the roll_number of ram which will be passed to the outer query.

Note : If the Inner query uses the value produced by the outer query then that query is called as
Co-related sub query.

Department Of Computer Science Page No: 22


VIEWS

A View is an object which is used to prevent all users from accessing all columns of a table for
data security reasons.

A View is stored only as a definition in ORACLE System Catalogue. When a reference is made to
a view , the definition is scanned and base table is opened along with view created on base table.

Syntax : create view View Name as (select col1,col2,....


from tablename
where condition
Group by …….) ;

Ex: create view Student_View as


(select Rno,name,Address,email
from student_master);

1 view created.

Destroying a View.
To destroy a view ae use "Drop" Command.
Syntax : Drop view View_Name;

INDEXES

An Address that identifies the location of the record in the oracle database is called as Row_Id.
Row_Id is an integral generated and maintained binary value which identifies a record.

Creation of Index :
Syntax: create index index_name on table_name(col1,col2,....);

Destroying an Index:
Syntax : Drop index index_Name;

Department Of Computer Science Page No: 23


SEQUENCES

In Oracle, you can create an autonumber field by using sequences. A sequence is an object in
Oracle that is used to generate a number sequence. This can be useful when you need to create a
unique number to act as a primary key.

Create Sequence

Syntax
The syntax to create a sequence in Oracle is:

CREATE SEQUENCE sequence_name


MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;

sequence_name
The name of the sequence that you wish to create.

Example

CREATE SEQUENCE supplier_seq


MINVALUE 1
MAXVALUE 999999999999999999999999999
START WITH 1
INCREMENT BY 1
CACHE 20;

This would create a sequence object called supplier_seq.


The first sequence number that it would use is 1 and each subsequent number would increment
by 1 (ie: 2,3,4,...}.
It will cache up to 20 values for performance.
If you omit the MAXVALUE option, your sequence will automatically default to:

MAXVALUE 999999999999999999999999999

So you can simplify your CREATE SEQUENCE command as follows:

CREATE SEQUENCE supplier_seq

Department Of Computer Science Page No: 24


MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 20;

To retrieve the next value in the sequence order, you need to use nextval.
For example:

supplier_seq.NEXTVAL;

This would retrieve the next value from supplier_seq. The nextval statement needs to be used in a
SQL statement. For example:

INSERT INTO suppliers


(supplier_id, supplier_name)
VALUES
(supplier_seq.NEXTVAL, 'Kraft Foods');

This insert statement would insert a new record into the suppliers table. The supplier_id field
would be assigned the next number from the supplier_seq sequence. The supplier_name field would
be set to Kraft Foods.

Drop Sequence
Once you have created your sequence in Oracle, you might find that you need to remove it from
the database.

Syntax
The syntax to a drop a sequence in Oracle is:

DROP SEQUENCE sequence_name;

Ex:

DROP SEQUENCE supplier_seq;

This example would drop the sequence called supplier_seq.


u've created a sequence object to simulate an autonumber field, we'll cover how to retrieve a
value from this sequence object. To retrieve the next value in the sequence order, you need to
use nextval.
For example:

supplier_seq.NEXTVAL;

Department Of Computer Science Page No: 25

You might also like