0% found this document useful (0 votes)
19 views17 pages

DBMS CH.3 Notes

Dbms notes

Uploaded by

kaushikpg2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views17 pages

DBMS CH.3 Notes

Dbms notes

Uploaded by

kaushikpg2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Chapter 3

Introduction to SQL
Introduction to SQL:
SQL is the Structured Query Language.
Its main purpose is to write queries. It allows the user to request the data from the
database bywriting requests in SQL.
Using SQL a user can add. modify, and delete the contents of the database.

DDL Commands
DDL stands for Data Definition Language.
Adatabase schema specified by a set of definitions expressed by a special language is
called aData Definition Language (DDL).
By using DDL commands we can crate a table. update table and delete the table.

1. Create Table command:


Thiscommand is used to specify a relation by its name and attributes.
The attributes of relation are specified by the attribute name, its data type and constraints.

Syntax:
create table <table name>
column namel datatype(size).
column name2 datatype(size).

column nume n datatype (size) ;


Example:
To create a table with columns as roll no, name and percentage of student.

Create table Student(


roll nonumber(3).
stud name varchar2(15),
percentage number(3.2) ):

2.Alter command:
It is used to add nevw columns or to modify the existing columns in the table.
Alter Table

i. add clause ii. modify clause


clause.
i. We can add columns to a table using alter table statement with add
Syntax :
Alter table <table name>
Add(column namel datatype(size)
column name2 datatype(size)

column name n datatype(size));


Example:
To add a column branch name to the student table.
Alter table student
Add (branch name varchar2(15)):

statement
ii. We can modify the existing column in a table by using alter table
with modify clause.
Syntax :
Alter table <table name>
Modify (column namel datatype(size)
column name2 datatype(size)

column name n datatype(size);


Example: the student table.
To modify width of column branch name to 20 in
Alter table student
Modify (branch name varchar2(20):
4. Rename command:
It is used to rename a table or view.
Syntax:
Rename <old table name> to <new table name>

Example: details.
Rename the student table to student
Rename student to student details:
5. Drop table:
vwell as definition (structure) ofa table.
The drop table commandremoves the data as
When we drop a table the database
Syntax:
Drop table <table name>
Example:
To delete the student table
Drop table student:

DML commands

DML stands for Data Manipulation Language.


DML commands are used to access or manipulate data in the database.
Manipulation includes,
insertion of new data(Insert)
retrieval of data(Select)
modification of data(Update)
deletion of data(Delete)

1. Insert command:
Once a table can be created it can be loaded with data.
This can be done using insert command.

Syntax:
insert into <table name>
(column namel,column name2,.., column name n)
values(expressionl, expression2, ...expresion n):

Example:
1. insert into student(roll no,stud name.percentage):
values(01. john',79.52);
OR

2 insert intostudent values(01,'john',79.52);


OR

3. insert into student( &roll no,'&stud name' ,&percentage);

2. Select Command:
This command is used to retrieve the data values stored into the table.

3
To retrieve (select) allthe attribute values we can use asterisk (*) symbol.
Syntax:
select *
from <table name>;
OR
select column namel.column name2. ,column name n)
from <table name>:

3. Update Command:
This command is used tochange or modify data values in a table.
Update command can be usedto update.
1. All ihe rows from a table
2. Only selected set of rows from a table.

Syntax:
update <table name>
set column name-expression;
where condition:;

Example:
To increase percentage of every student by 0.15 9%

update student
sel percentage=percentage + 0.15;

4. Delete command:
It is uscd todelete specific roes or all rows from the table.

Syntax:
Todelete all rows
Delete from <table name>
Eg. delete from student;

Todelete specific rows


Delete from <table name>
Where condition;
Example:
Delete from student where roll no=703:

5. Truncate command:
It is used to remove all rows from a table and to release the storage space used by the
table.
Syntax :
Truncate table table name:

Example:
Truncate table student:

Logical operators

A logical operator is used to combine the results of


two of 2 or more conditions to
produce a single result.
There are three logical operators.
a. AND
b. OR
c. NOT

AND:
conditions given with AND are true.
AND operator gets evaluated ii all the

Example: enrolled for IF branch and lives in city


Latur.
To get details of student who have
Select * from stud info
Where branch code=°CO'AND activity='Project';

OR:
any one or all conditions given
with OR are true.
OR operator gets evaluated if

Example:
details of student who have enrolled for IF branch and is guided by some
To get
leader.
Select * from stud info
NOT NäLL:
Where branch code='IF OR leader is

NOT:
NOT is used as negation operator.

Example:
except activity as sports.
To get details of'studentfrom
Select * stud info
Where NOT(activity='sports' );
Set Operators

Set oprators combines the result of two or more


queries into a single result.

The various set operators are,


a. Union
b. Union all
c. Intersect
d. Minus

Union:
the result of queryl or in the
-lt is used to select all the distinct rows either appearing in
result of query2.
-Duplicate values are eliminated.

Example:
Select branch code from branch details
Union
Select branch code from stud info;
are present in branch details and
The above query will display the identical records that
stud info table without including the duplicates.
Union all:
the result of query I or in the result of
-It is used to select all the rows either appearing in
query2.
-Duplicate values are not eliminated..

Example: details
Select branch code from branch
Union all
Select branch code irom stud info;
present in branch details and
The above query will display the identical records that are
stud info table including the duplicates.
Intersect:
It returns all rows that appear in both queries result.

Example:
Select branch code from branch details
Interscct
Sclect branch code from stud info,
The above query will display the records that are present in branch_ details and stud into
table.
i.e. It returns common values from both tables.

Minus:
It returns those rows that appear in the result of queryl but not in the result of query 2.
Example:
Select branch code from branch details
Minus
Select branch code from stud info:

Aggregate Functions
a
Aggregate functions are fuctions that take a collection of values as input and returns
single value as output.
Following are the aggregate functions.
a. AVG
b. SUM
c. MIN
d. MAX
e. CoUNT

AVG:
column.
It returns the average value of the specified
Syntax:
Select AVG(column) from table name:
Example:
Select AVG(ssc per) from stud info:

SUM:
specified column.
It returns the sumnmation of the

Syntax:
Select SUM(column) trom table name:
Example:
Select SUM(ssc per) from stud info:
MIN:

It returns the minimum value of the specifiedcolumn.

Syntax:
Select MIN(column) from table_name;
Example:
Select MIN (ssc_per) from stud_info;
MAX:

It returns the maximum value of the specified column.


Syntax:
Select MAX (column) from table name;
Example:
Sclect MAX (Ssc per) from stud info;
COUNT:

-lt is used to count the number of rows from specified table.


-lt counts the number of values present in the specified column or in spccified table
excluding the NULL values.

Syntax:
Select COUNT(column) from table_ name;
Example:
Select COUNT(sSc per) from stud info;

8
String Functions
A. INITCAP
Returns char with first letter in uppercase.
Syntax
initcaplchar)
Example:
Sclect initcap"danish") from stud info;
Output:
INITCAP

Danish

B. LOWER

Returns char with all letters in lowercae.


Syntax:
Lower(char)
Example:
Select lowerlDANISH") from stud info;
Output:
LOWER

danish

C. UPPER
Returns char with all letters inuppercae,
Syntax:
upperlchar)
:xample:
Sclect upper"danish") from stud info,
Jutput:
UPPER

DAISH

D. SUBS
Petins a portion of char, egins at charater'n' cedny spto '1htr
SLBSTP(String mt1)
Example:
Select SUBSTRCIiangle',4,5) from dual;
Output:
SUBSTR

angle
E. LPAD char2.
Returns char I, left padded to length 'n' with the sequence of characters in
Syntax:
LPAD(charl,n,char2)
Example:
Select LPAD(sky',8,'*') from dual;
Oulput:
LPAD

*****sky

F. RPAD characters in char2.


Returns charl, right padded to length 'n' with the sequence of
Syntax:
RPAD(charl,n,char2)
Example:
Select RPAD('sky',8,' *') from dual;
Output:
RPAD

sky *****

G. LTRIM
in the set.
Returns character with first character removed to the last character not
Syntax:
LTRIM(char,set)
Example:
Select LTRIM ('manas khan','manas') from dual:
Output:
LTRIM

khan

H. RTRIM
Returns character with final character removed to the last character not in the set.
Syntax:
RTRIM(char,set)
Example:
Select RTRIM (manas khan', khan') from dual;
Output:
RTRIM

manas

I. LENGTH

Returns the length of character.


Syntax:
LENGTH(char)
Example:
Select LENGTH ('hello') from dual;
Output:
LENGTH

J. TRANSLATE
corresponding character in string.
It returns all occurrences of character by its
Syntax:
TRANSLATE (char, from string, to string)
Example: dual;
Select TRANSLATE ('sky'"k,'h') from
Output:
TRANSLATE

shy

K. REPLACE corresponding character in string


It replaces all occurrences of character by its
Syntax:
REPLACE (char,search string, rep string)
Example:
Select REPLACE (Tick and Tock''t','cl') from dual;
Output:
TRANSLATE

click and clock


Is Null and Is Not Null:
Is Null operator checks for the value which is null.
Is Not Nulloperator checks for the value which is null.
Examplel: (Is Null)
To get details of student who have not taken any activity
Select *from stud info
Where activity is null;
Example 2: (Is Not Null)
To get details of student who have enrolled for activity
Select * from stud info
Where activity is not null:

Clauses

1. Group By :
the rows in a table into groups.
A group by clause can be used to divide in
attribute in the group by clause are placed
Tuples with the same value on all the
one group.
Example branch wise
Todisplay number of students studying
Select branch code.count(stud id)
From stud info
Group by branch code:

2. Having clause:
groups are to be displayed.
Having clause is used to specify which
Example
Display the branch_code having highest percentage>80
Select branch code,max(ssc per)
From stud info
Group by branch code
Having max(ssc per)>80;

2. Order by clause:

12
Nested Sub Queries

Subquery is a select-from-where expression that is nested within another query.


A
ACOmmon use of subqueries is to
perform test for set membership,set comparision.

a. Set Membership:
SQL allows testing of tuples for membership in a relation.
presence of set membership.
The in connective is used to test for the the absence of set membership.
The not in connective is used to test for

Examplel: (in) account at bank.


Find customers who havea both loan and
Select cust name
From borrower
fromdepositor);
Where cust name in (select cust name

Example2: (not in) butdo not have account.


Find customers who have loan at bank
Select cust name
From borrower
Where cust name not in (select cust name fromdepositor);

b. Set comparision
operators such as,
SQL allows set comparision using comparision
<,<=,>,=,!= etc.

Example:

13
PL SQL
There are several disadvantages of SQL:
1. SQL does not have any procedural
capabilities.
1.e SQL does not provide programming techniques of condition
checking,looping,branching.
di The speed of data processing is decreased as SQL statements are passed to
oracle engine at a time.
3. SQL has no facility for programmed handling of errors that arise during
manipulation of data.

-A fully structured programming language is PL/SQL ie. Programming Language


SQL.
-It is a superset of SQL. It is a block structured language that enables developers to
combine the power of SQL with procedural statements.
-PL/SQL is extension of SQL.

Advantages of PL/SQL:
1. It is a development tool that not only supports SQL data manipulation but also
provides facilities of condition checking, branching and looping.
2. It sends an entire block of statements to the oracle engine at a time.
3. It processes the code much faster than SQL.
4. It permits dealing with errors as required and displays user friendly messages
when errors are encountered.
5. It allows declaration and use of variables in block of code.
6. Applications written in PL/SQL are portable to any computer hardware and
operating system.

PL/SQL Block Structure


A single PL/SQL code block consist of a set of SQL statements, grouped together and
passed to oracle engine.
A PL/SQL block has a definite structure.
The minimum sections ofPL/SQL block are,
Declare section
The master Begin and End section
The Declare Section:
obËects
Code block start with a declaration section in which variables and other oracle
can be declared.

14
The Begin section:
be
t consist of SQL and PL/SOL statements which describes processes that have to
applied to the data.
Actualdata manipulation, retrieval, looping and branching constructs are specitiedm
this section.

The End Seetion:


It marks the end of PL/SQL block.

Structure of PL/SQL block

DECLARE
Var datatype:= value;

BEGIN
SQL statements

END;

Variables and Constants:


declare a variable follow the
Variables in PL/SQL blocks are named variables. To
conventional rules given below,
character.
I. Variable name must begin with a characters.
2. The lengthof variable can be maximum 29 unless enclosed within double
3. Reserved words cannot be used as variable names
quotes.
name.
4. A space cannot be used in variable

15
PL/SQL control structures:
If-Then-Else
Syntax:
IF condition THEN
Statements;
[ELSE IF condition THEN
Statements:]
[ELSE
Statements;
END IF:

Example:
Declare
Age number:=10
Begin
IF (age<18)THEN right");
Dbms_output.put line(""wait for some time to enjoy your voting
ELSE
Dbms_output.put line(Use your intellect to vote")
END IF;
END

Loops in PL/SQL
1. LOOP and END LOOP
2. WHILE LOOP
3. FOR LOOP

1. LOOP and END LOOP

Syntax:
LOOP
Statements;
END LOOP;
Or
LOOP
Statements;
EXIT WHEN(condition):
END LOOP:

Example: To display the numbers from 1 to 10


Declare
X nunber:- 1
Begin
LOOP
Dbms_output.put line('Number is'|| x);
X:= X+1;
EXIT when x>10;
END LOOP:
END

2. WHILE LOOP
Syntax:
WHILE condition LOOP
Statements;
END LOOP:

Example: To display square roots of numbers from 1 to 10.


Declare
X number:=1
Begin
WHILE x<|| LOOP
Dbms output.put Iine('square root of 'l|x|'issqrt(x));
X:=x+l:
END LOOP:
END;

3. FOR....LOOP:

Syntax:
bound LOOP
For LOOP VARIABLE in[Reverse] lower bound...upper
Statements;
END LOOP;
96
Example: To convert ASCII values from 65 to

BEGIN
FOR x IN 65...96 1LOOP
Dbms output.put line(CHARACTER FOR || x |is'chr(x):
END LOOP;
END;

17

You might also like