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

Chapter 4

The document discusses SQL and its components like DDL, DML, DQL and DCL. It describes various SQL commands like CREATE, SELECT, INSERT, UPDATE, DELETE etc and how they are used to define, manipulate and control database objects and data. It also covers data types, constraints and transactions in SQL.

Uploaded by

A R P A N z
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)
37 views

Chapter 4

The document discusses SQL and its components like DDL, DML, DQL and DCL. It describes various SQL commands like CREATE, SELECT, INSERT, UPDATE, DELETE etc and how they are used to define, manipulate and control database objects and data. It also covers data types, constraints and transactions in SQL.

Uploaded by

A R P A N z
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/ 112

Chapter 4

Relational Database
Query Languages
Presented by : Er. Lali Manandhar
Assistant Senior Lecturer
Everest Engineering College
SQL (Standard Query Language)
 SQL is the standard query language to
communicate with a relational database
 SQL works with database programs like MS-

Access, MS-SQL server, Oracle etc.


 SQL is not a case sensitive language.
 IBM developed the original version of SQL,

originally called Sequel, whose name has now


been changed to SQL (Structured Query
Language).
Components of SQL
 DDL (Data Definition Language)
• DDL is the part of SQL that allows database
users to create and restructure database
objects.
• The main DDL statements are CREATE,
ALTER and DROP.
 DML (Data Manipulation Language)
• DML is the part of SQL that allows
manipulation of data within object of a
relational database.
• DML statements are INSERT INTO, UPDATE,
DELETE etc.
 DQL (Data Query Language)
• DQL is the part of SQL that is used to
compose queries against a relational
database.
• DQL statements are SELECT.

 DCL (Data Control Language)


• DCL is the part of SQL that provides control
access to data and to the database.
• DCL statements are COMMIT, ROLLBACK,
GRANT, REVOKE etc.
 DQL (Data Query Language)
• DQL is the part of SQL that is used to
compose queries against a relational
database.
• DQL statements are SELECT.

 DCL (Data Control Language)


• DCL is the part of SQL that provides control
access to data and to the database.
• DCL statements are COMMIT, ROLLBACK,
GRANT, REVOKE etc.
Data Types in SQL
 int
Its full form is Integer. It can store whole
numbers in the range 31
 smalllint
2 to 2  1 31

It is subset of integer. It can store whole


numbers in the range
 tinyint: 2 to 2  1
15 15

whole numbers (0-255)


 bigint:
whole number 2 to 2  1
63 63
 numeric(p,d):
fixed point number, with user specified
precision of p digits, with d digits to the right
of decimal point.
 datetime:

date and time data


 char(n):

the char data type stores fixed length


character string with user specified length n.
The maximum number of character the data
type can hold is 255 character. It uses static
memory allocation.
 varchar(n):
variable length character string with user
specified length n. It is slower than char but
is highly memory efficient as it uses dynamic
memory allocation.
 nvarchar(n):

nvarchar type is used to store multilingual


data using the Unicode representation.
 float(n):

A floating-point number, with precision of at


least n digits.
Data Definition Language
 DDL is the part of SQL that allows database
users to create and restructure database
objects.
 A database schema is specified by a set of

definitions expressed by a special language


called data definition language. So data
definition language is a set of SQL commands
which is used to create, modify and delete
database structure but not data. 
 The main tasks of DDL are: - Creating

database object like tables (CREATE) -


Modifying database objects. (ALTER) -
Destroying database objects. (DROP)
DDL also updates a special set of tables
called the data dictionary. The result of
compilation of DDL statement is a set of
tables that is stored in special files called
data dictionary. A data dictionary contains
metadata i.e. data of data. Data about
structure of a database is called metadata.
 The main DDL statements are CREATE, ALTER

and DROP.
1. CREATE DATABASE command
It is used to create a new database.
 Syntax:

CREATE DATABASE <database_name>;


 Eg. CREATE DATABASE db_mydatabase;
2. CREATE TABLE command
 It is used to create a table.
 Syntax:

CREATE TABLE <table_name>


(
Field1 datatype1,
Field2 datatype2, . . .
FieldN datatypeN
);
 E.g. CREATE TABLE tbl_student (id int, name

varchar,roll int);
3. DROP DATABASE command
 It is used to destroy the complete database
structure.
 Syntax:

DROP DATABASE <database_name> ;


 E.g. DROP DATABASE db_mydatabse;
DROP TABLE command
 It is used to destroy the complete structure of
table.
 Syntax:

DROP TABLE <table_name>;


 E.g. DROP TABLE tbl_student;
5. ALTER TABLE command
 it is used to change the structure of table.

i. add new column


Syntax:
ALTER TABLE <table_name>ADD
<Newfield1 datatype1>, <Newfield2
datatype2>, .. <Newfield N datatypeN>;

E.g. ALTER TABLE student ADD maths int,


section char(20);
ii. delete existing column
Syntax:
ALTER TABLE <table_name> DROP COLUMN
<column_name1>, <column_name2>,…..,
<column_nameN>;
E.g. ALTER TABLE student DROP COLUMN
maths,section;

iii. Changing the datatype of existing column


Syntax: ALTER TABLE <table_name> ALTER
COLUMN <column_name new datatype>;
E.g. ALTER TABLE tbl_student ALTER
COLUMN name nvarchar(50) ;
DML (Data Manipulation Language)
1. INSERT INTO command
 It is used to insert new record into a table.
 Syntax:

a. INSERT INTO<table_name>
(field1,field2-----fieldN) VALUES (value1,
value2---------- valueN);
 This query can be used to insert values for

selected field. The non selected field will have


NULL value inserted upon execution of the
above query.
 Eg:
INSERT INTO tbl_student (id,name) VALUES
(2,’Ram’) ;//NULL value will be inserted for
roll field

b. INSERT INTO <table_name> VALUES (value1,


value2………..valueN);
 This is used when we have to insert values for

all the fields in the table.


 Eg:

INSERT INTO tbl_student values(1,’Ram’,10);


2. UPDATE command
 It is used to modify selected or all records

from a table.
 Syntax:

a. UPDATE <table_name>SET
field1=newvalue1, field2=newvalue2………
fieldN=newvalueN;
eg:
UPDATE tbl_student SET roll=5 ;
 b. UPDATE <table_name> SET
field1=newvalue2, field2=newvalue2………
fielnN=newvaluN WHERE <Expression>;

 Eg: UPDATE tbl_student SET roll=5 WHERE


name=‘Ram’;
3. DELETE command
 It is used to delete all or selected records

from a table.
 Syntax:

a. DELETE FROM<table_name>; // deletes all


records from table
Eg: DELETE FROM tbl_student ;// delete entire
records from tbl_student

b. DELETE FROM<table_name>
WHERE<Expression>;
Eg: DELETE from tbl_student WHERE id>10 //
delete all records whose id >10 ;
DQL (Data Query Language)
1. SELECT command
 It is used to display all or selected records
from a table.
 Syntax:
 a. SELECT <field1>,<field2>…..<fieldN> FROM
<table_name>;
Eg: SELECT id,name FROM tbl_student // display
field id and name with all records;

 b. SELECT * FROM <table_name>; // * represents


all the field name
Eg:SELECT * FROM tbl_student; // display all fields
with all records;
c. SELECT * FROM <table_name> WHERE
<Expression>;
Eg: SELECT * FROM tbl_student where id<10; //
display all the fields with only those records whose
id is less than 10

d. SELECT <field1>,<field2>…..<fieldN> ,…. FROM


<table_name> WHERE <Expression>;
Eg: SELECT id, age, age FROM tbl_student where
id<10 ;

e. SELECT DISTINCT <field_name >FROM


<table_name>; // to remove Duplicate Tuple we
use Distinct Keyword
Eg: SELECT DISTINCT name from tbl_student; //
display all the names from tbl_student without
duplication of values
f. SELECT TOP<N> <field1>,<field2>…..<fieldN> ,
…. FROM <table_name>;
Eg: SELECT TOP 10 * FROM tbl_student // display
first 10 records
DCL (Data Control Language)
 1. COMMIT and ROLLBACK commands
 DCL is a set of SQL commands for controlling

access to data and to the database.


 Syntax:

COMMIT TRANSACTION<transaction_name>;
ROLLBACKTRANSACTION <transaction_name>;
Eg:
BEGIN TRANSACTION Tr1
BEGIN TRY ;
INSERT INTO tbl_student VALUES (1,’Ram’,10);
DELETE FROM tbl_student WHERE name=’Ram’;
UPDATE tbl-student SET name=‘Bipin’ WHERE
COMMIT TRANSACTION Tr1
END TR1;
BEGIN CATCH ;

ROLLBACK TRANSACTION Tr1


END CATCH ;
2. GRANT and REVOKE commands
 GRANT is a command used to provide access
right or privilege on the database objects to
the users. These commands are generally
used by DBA.
 REVOKE is a command which remove user

access right or privilege to the database


object
 Syntax:

◦ GRANT<Privilage_name> ON <object_Name>To
<User_Name>;
• REMOVE <Privilage_name>ON<object_Name>
FROM <User_Name>;
 Privilage_Name means access right. Some of the
access right are ALL, SELECT, INSERT, UPDATE,
DELETE, EXECUTE.
 Object_Name is the name of database object

such as TABLE, VIEWS, STORED PROC etc.


 User_Name is the name of user to whom an

access right is being granted.


Eg:
GRANT SELECT ON tbl_student TO user1 //
grants select permission on tbl_student to user1
REVOKE SELECT ON tbl_student FROM user1 //
restrict user1 from selecting data from
tbl_student
Data Constraints
 Constraints define rules that must be
followed to maintain consistency and
correctness of data.
 Generally constraints are created at the time

of creation of table; however they can be


added after table creation also.
 A constraint can be defined on a column

while creating a table. Constraint can be


defined into the following types.
1. Primary Key Constraint:
 A primary key constraint is defined on a column
or a set of columns whose values uniquely
identify all the rows in a table.
 A primary key column can’t contain NULL values.
 i. Creating primary key during table creation
 Syntax:
 a.
◦ CREATE TABLE<table_name>
(
Field1 datatype1 CONSTRAINT<constraint_name>
PRIMAY KEY,
Field2 datatype2, . . .
FieldN datatypeN
);
Eg:
CREATE TABLE tbl_student (id int CONSTRAINT
idcode PRIMARY KEY, roll int, class int, name
varchar(50));
b.
CREATE TABLE<table_name>
(
Field1 datatype1 PRIMAY KEY,
Field2 datatype2, . . .
FieldN datatypeN
);
Eg:CREATE TABLE tbl_student (id int PRIMARY KEY,
roll int, class int, name varchar(50)) ;
 c.
CREATE TABLE<table_name>
(
Field1 datatype1,
Field2 datatype2, . . .
FieldN datatypeN ,
CONSTRAINT<constraint_name> PRIMAY
KEY(<field1>,<field2>…..<fieldN> );
);
 d.
CREATE TABLE<table_name>
(
Field1 datatype1,
Field2 datatype2, . . .
FieldN datatypeN ,
Primary KEY(<field1>,<field2>…..<fieldN> );
 Eg:
CREATE TABLE tbl_student (id int ,roll
int,class int, name varchar(50), PRIMARY
KEY(id)) ;

ii) Adding primary key after table creation


 Syntax:
 a.

◦ ALTER TABLE<table_name> ADD PRIMARY


KEY(<field_name>);
Eg:ALTER TABLE tbl_student ADD PRIMARY KEY (id) ;
b.
ALTER TABLE<table_name> ADD
CONSTRAINT<constraint_name> PRIMARY
KEY(<field_name>);
Eg: ALTER TABLE tbl_student ADD CONSTRAINT idcode
PRIMARY KEY (roll);

 c.
ALTER TABLE<table_name> ADD PRIMARY
KEY(field1,field2);

 d.
ALTER TABLE<table_name> ADD
CONSTRAINT<constraint_name> PRIMARY
KEY(field1,field2)
iii) Removing primary key Constraint
 Syntax:

ALTER TABLE<table_name>DROP<constraint_name>;
Eg: ALTER TABLE tbl_student DROP idcode
2. Foreign Key constraint:
 A foreign key is imposed on a column of one
table which refers the primary key column of
another table.
 A foreign key constraint removes the

inconsistency in two tables when the data in


one table depends on data in another table.
 Simply it is the linking pin between two

tables.
 Syntax:
CREATE TABLE<foreign_table_name>
(
Field1 datatype1 CONSTRAINT<constraint_name>
REFERENCES<primary_table_name> (<
Primary_Key_column_name/primary key constraint name
>),
Field2 datatype2. .
FieldN datatypeN
);

Eg:CREATE TABLE Orders (


Order_ID int NOT NULL,
Order_Number int NOT NULL,
Person_ID int,
PRIMARY KEY (Order_ID),
FOREIGN KEY (Person_ID) REFERENCES Persons(Person_I
D)
);
 CREATE TABLE Orders (
Order_ID int NOT NULL PRIMARY KEY,
Order_Number int NOT NULL,
Person_ID int
FOREIGN KEY REFERENCES Persons
(Person_ID)
);

 ALTER TABLE Orders


ADD FOREIGN KEY (Person_ID) REFERENCES Pe
rsons(Person_ID);
3. Unique Constraint:
 The unique constraint is used to enforce
uniqueness on non-primary key columns.
 The unique constraint is similar to primary key

constraint except that it allows one NULL row.


 Also multiple unique constraints can be created

on a table.
 Syntax:

CREATE TABLE<table_name> (field1 datatype1


UNIQUE, field2 datatype2…..fieldN datatypeN) ;
Eg:
CREATE TABLE tbl_student( id int PRIMARY KEY,
name varchar(20), mobile_no int UNIQUE);
4. Check Constraint:
 A check constraint enforces domain integrity by
restricting the value to be inserted in a column.
 Syntax:

CREATE TABLE<table_name> (field1 datatype1


CHECK (expression),field2 datatype2,---fieldN
datatypeN);
Eg:
CREATE TABLE tbl_student(id int,roll int,maths
float CHECK(maths<99.99 and
math>0),full_name nvarchar(50)
CHECK(len(name)>5) ) // note: len() is a function
which return the number of characters.
5. Default Constraint:
 A default constraint can be used to assign a
constant value to a column and the user need not
insert values for such column.
 However if the user provides value then the

particular value will be stored.


 Syntax:

CREATE TABLE (field1 datatype1


DEFAULT<default value> ,field2 datatype2…
fieldN datatypeN);
Eg:
CREATE TABLE tbl_student(id int, name varchar(50),
address varchar(50) DEFAULT ‘Kathmandu’);
6. Not Null Constraint:
 If a column is declared as not null, a value
has to be necessary to be inserted for such
column.
 Syntax

CREATE TABLE (field1 datatype1 NOT


NULL,field2 datatype2, ……….fieldN
datatypeN);
Eg:
CREATE TABLE tbl_student(id int PRIMARY
KEY, name varchar(50) NOT NULL,roll int);
 Note:
CREATE TABLE tbl_student(id int identity(1,1),
name varchar(50),roll int) ;
 In the above table tbl_student has a field id

with identity() function, this type of field are


called auto increment field.
 It act as a default value for a column that

increments for each record.


 Syntax:

identity(seed,increment)
 Seed: start number
 Increment: incremental value for seed
Operators
 To conditionally select, update and delete
data from a table, a WHERE clause followed by
an expression involving several operators is
used.
 1. Arithmetic Operators:

◦ Arithmetic operators are used to perform


mathematical operations such as addition,
subtraction, multiplication and division on numeric
columns.
◦ Arithmetic operators are + ,-, *, / and %.
 Consider the following relation
tbl_Marks(id, name, address, maths, science,
english)
 Examples:
a. Increment the mark of math’s of all student by
10%.
UPDATE tbl_Marks SET maths=maths*1.1

 b. Display all the records if every student is given a


10 percent raise in science.
SELECT id,name,maths,science*1.1,English FROM
tbl_Marks
2. Comparison Operators:
 Comparison operators are used to select,
update and delete the records in the relation
based on condition specified in WHERE
clause.
 Comparison operators are =, <>, >, , != and

<=.
 Example:

◦ a. Display all the records from tbl_Marks for which


marks in maths is greater than 60.

SELECT * from tbl_Marks WHERE maths > 60


◦ b. Decrement the marks of English by 10 for
student whose id is1001.

UPDATE tbl_Marks SET english=english-10 WHERE


id=1001

◦ c. Delete all the records from tbl_Marks whose


marks in maths is less than 40.

DELETE FROM tbl_Marks WHERE maths<40


3. Conjunctive Operators / Logical Operators:
 Logical operators are used to select, update
and delete records based on one or more
conditions.
 Logical Operators are AND, OR and NOT.
 Example:

◦ a. Display all the records from tbl_Marks for which


marks in maths is greater than 60 or marks in
English is greater than 60
SELECT * FROM tbl_Marks WHERE maths>60 OR
english>60
 b. Delete all the records of failed student
from tbl_Marks. The pass mark for each
subject is 40.
DELETE FROM tbl_Marks WHERE maths<40 OR
english<40 OR science<40
 c. Delete all the records of students from

tbl_Marks who are failed in all three subjects.


DELETE FROM tbl_Marks WHERE maths<40
AND english<40 AND science<40
4. Range Operators:
 The range operators can be used to select,
update and delete the records based on the
condition specified by certain range.
 Range Operators are BETWEEN and NOT

BETWEEN.
 Syntax:

◦ SELECT <field1>,<field2>…..<fieldN> FROM


<table_name> WHERE <Field_name> BETWEEN
<Expression1> AND <Expression 2>
◦ a. Display all the records from tbl_Marks whose id
is between 200 to 300.
SELECT * FROM tbl_Marks WHERE id BETWEEN 200
AND 300 // 200 and 300 are inclusive
Or
SELECT * FROM tbl_Marks WHERE id>=200 AND
id<=300

◦ b. Display all the records from tbl_Marks whose id


in not in the range 200 to 300
SELECT * FROM tbl_Marks WHERE id NOT BETWEEN
200 AND 300

◦ c. Delete all the records from tbl_Marks whose id is


between 200 to 300
DELETE FROM tbl_Marks WHERE id BETWEEN 200
AND 300
5. List Operators:
 The list operators are used to select, update
and delete the records based on the condition
specified by the list of values.
 List Operators are IN and NOT IN. The IN

operator selects values that match any one


values given in the list.
 Syntax:

SELECT <field1>,<field2>…..<fieldN> , …
from <table_name> WHERE <field_name> IN
<item1,item2…..itemN>
 Example:
◦ a. Display all the records of students from
tbl_Marks who are from Pokhara, Kathmandu or
Butwal.

SELECT * FROM tbl_Marks WHERE address


IN(‘Pokhara’,’Kathmandu’,’Butwal’)
OR
SELECT * from tbl_Marks WHERE
address=‘Pokhara’OR address=‘Kathmandu’OR
address=‘Butwal’
◦ b. Display all the records from tbl_Marks whose id
is not 20, 30, 45, 78 and 92

SELECT * FROM tbl_Marks WHERE id NOT


IN(20,30,45,78,92)
OR
SELECT * FROM tbl_Marks WHERE id<>20 AND
id<>30 AND id<>45 AND id<>78 AND id<>92
OR
SELECT * FROM tbl_Marks WHERE NOT( id=20 OR
id=30 OR id=45 OR id=78 OR id=92)
6. String Operator:
 SQL includes a string-matching operator for
comparison on character strings.
 The Operator LIKE matches the given string

with the specified pattern.


 The pattern includes combination of wildcard

characters and regular characters.


 Some of the wild card characters are
Wildcard Description
%(Percent) Represent any string of zero or
more characters
_ (Underscore) Represent any single character

[] Represent any single character


within specified range
[^] Represent any single character
not within the specified range
 Eg:
 a. Display all the records from tbl_Marks for which
name start with ‘M’.
SELECT * from tbl_Marks WHERE name LIKE ‘M%’

 b. Display all the records from tbl_Marks for which


name ends with ‘ma’
SELECT * FROM tbl_Marks WHERE name LIKE ‘%ma’

 c. Display all the records from tbl_Marks for which


the address is three letters and ends with ‘rt’.
SELECT * FROM tbl_Marks WHERE address LIKE ‘_rt’
 d. Display all the records from tbl_Marks for which
the name begins with ‘a’, ‘x’, ‘y’ or ‘z’ .
SELECT * FROM tbl_Marks WHERE name LIKE ‘[axyz]%’

 e. Display all the records from tbl_Marks for which


the name begins with any letter from ‘p’ to ‘w’ and
ends with ‘eta’
SELECT * FROM tbl_Marks WHERE name LIKE ‘[p-w]
%eta’

 f. Display all the records from tbl_Marks for which


the name begins with ‘d’ and not having ‘c’ as the
second letter and ends with ‘a’.
SELECT * FROM tbl_Marks where name LIKE ‘d[^c]%a’
Sorting
 Data can be sorted either in ascending or
descending by using the Y clause
 Syntax: ORDER B
SELECT <field1>,<field2>, ……..<fieldN>
FROM <table_name> ORDER BY<field_name>
[ASC/DESC]
 Eg:
a. Display all the records from tbl_Marks by
sorting the names in descending order.
SELECT * FROM tbl_Marks ORDER BY name
DESC
The Rename Operation
 The SQL allows renaming the attributes as
well as relation using the AS clause.
 Syntax:

 Select <field1>AS<NewField>,<field2>,…..

<fieldN>FROM<table_name>

 Select <field1>..<fieldN> From


<table_name>as<new_table_name>
where,<NewField1> and <new_table_name>
are the aliase i.e. alternative name for and
respectively.
i. SELECT id AS student id, name, maths,
science, English, (maths+science+english) AS
total from tbl_Marks
 The above query displays all the records from

tbl_Marks such that attribute id is renamed as


student id and new field whose name is total
displays total mark of each student.

ii. SELECT * from tbl_Marks as t


 An identifier,such asT and S,that is used to

rename a relation is referred to as a


correlation name in the SQL standard, but is
also commonly referred to as a table alias, or a
correlation variable, or a tuple variable.
Set Operations
 The set operators combines results from two
or more queries into a single result set.
 SQL support few set operations to be

performed on table data.


 Different set Operators are

1. UNION:
 This operation is similar to UNION. But it also

shows the duplicate rows The UNION ALL


query is
2. INTERSECT:
 Intersect operation is used return the records
which are common to both SELECT statement.
 This operation eliminates the duplicate rows

from its result set.


 INTERSECT ALL operation can be used if we

want to keep duplicate rows in the result


table. The INTERSECT query is
3. EXCEPT:
 Except operation returns all records from first
table that are not in second table.
 This operation eliminate the redundant rows

from its result set.


 EXCEPT ALL operation can be used if we want

to keep duplicate rows in the result table.


 The EXCEPT query are
Grouping and Summarizing Data
 Summary of the data contains aggregated
value that helps in data analysis at broader
level.
 We can summarize the data using the

following aggregate functions.

1. AVG():
 Returns the average values in a numeric

expression.
 E.g. Display the average math mark for the

whole school.
SELECT AVG(maths) (AS Averagemathsmarks)
FROM tbl_Marks
2. COUNT():
 Return the numbers of values in an

expression.
 E.g. Display the total number of records in

table tbl_Marks.
SELECT COUNT(*) AS total FROM tbl_Marks
or
SELECT COUNT(ID) AS total FROM tbl_Marks

 Count the total number of unique name in


tbl_mark
SELECT COUNT(DISTINCT name) from
tbl_Marks
3. MIN():
 Returns the lowest value in the numeric

expression.
 E.g. Display the lowest mark obtained in

maths.
SELECT MIN(maths) AS lowestmathmark FROM
tbl_Marks

4. MAX():
 Returns the highest value in the numeric

expression.
 E.g. Display the highest mark obtained in

maths.
SELECT MAX(maths) AS highestmathmark FROM
tbl_Marks
5. SUM():
 Returns the sum of values in a numeric

expression.
 E.g. Display the sum of marks in maths for all

students.
SELECT SUM(maths) AS
totalmathsmarksofallstudent FROM tbl_Marks
Grouping Data
 The GROUP BY clause summarizes the result set
into groups as defined in the SELECT statement
by using `aggregate function.

 The GROUP BY clause is used to group a set of


tuples having same value on given attribute. The
attribute or attributes given in the GROUP BY
clause are placed in one group.

 The HAVING clause further restricts the result


set to produce the data based on a condition.
The HAVING clause is used to specify a selection
condition on groups rather than on individual
tuples.
 Syntax:
SELECT <coloumn_name>,
aggregate_functinions (Column_name) FROM
<table_name> WHERE<Expression> GROUP
BY <column_name> HAVING<Expression
with/without aggregate function>

 Example 1: Consider the below Relation


1. Display the minimum and maximum salary
paid for a employee of different addresses.
SELECT Address, MIN(Salary) AS
minsalary,MAX(Salary) AS maxsalary FROM
tbl_emp GROUP BY address

2. Display the average salary paid for all


address except Btl.
SELECT Address, AVG(Salary) AS
AverageSalary FROM tbl_emp WHERE
Address<>’Btl’ GROUP BY Address
Or
SELECT Address, AVG(Salary) AS AverageSalary
FROM tbl_emp GROUP BY Address HAVING
Address<>'Btl'
3. Display the maximum salary for each
address where the maximum salary is greater
than 10000
SELECT Address, MAX(Salary) AS maxsalary
FROM tbl_emp GROUP BY address HAVING
MAX(Salary)>10000
Address maxsalary

Pkr 12000
Subquery / Inner query / Nested query

 Subquery is a query that is used within


another query i.e. query in query.
 Subqueries are nested inside the WHERE

clause of SELECT, INSERT, UPDATE and


DELETE statement.
 The query that represents the parent query is

called outer query and the query that


represents the subquery is called inner query.
 The Database engine first executes the inner

query and then outer query to calculate the


result set.
 Example 1: Consider the tbl_emp relation
1. Display all the record of employee who have
the salary greater than that of Rita
SELECT * FROM tbl_emp WHERE salary >
(SELECT salary FROM tbl_emp WHERE name
= 'rita')
2. Display all the records of employee whose
salary is greater than average salary of all
employees
SELECT * FROM tbl_emp WHERE salary >
(SELECT AVG(salary) FROM tbl_emp)

Name Address Salary


Hari Btl 8000
Sita Pkr 12000
3. Display all the records of employee who
have same address as Rita
SELECT * FROM tbl_emp WHERE address =
(SELECT address FROM tbl_emp WHERE
name='rita’)
4. Display address for employes whose address
is that of Rita or Sita.
SELECT address FROM tbl_emp WHERE
address IN (SELECT address FROM tbl_emp
WHERE name='Rita' OR name='Sita‘)
Class work
Null Values
 With insertions, we saw how null values might
be needed if values were unknown. Queries
involving nulls pose problems.

 If a value is not known, it cannot be


compared or be used as part of an aggregate
function. However, we can use the keyword
null to test for null values:
 Example:
◦ select * from tbl_student where middlename is null
◦ i.e. the above queries displays only those records
for which the middle name is null.
Join Operation
 Join operation is done to retrieve records
from multiple tables.
 We can join more than one table based on a

common attributes. Join operations take two


or more relations as input and return a single
relation as result.
 There are four types of join which are

explained below.
1. Inner join (Natural Join):
 When an inner join is applied, only rows with values
satisfying the join condition in the common column
are displayed.
 Records in both the tables that do not satisfy the
join condition are not displayed.

 Syntax:
SELECT <column_names>FROM<table1> INNER
JOIN <table2> ON<table1>.<common_field><join
operator><table 2>.<common field>

Notes: we can simply use JOIN keyword instead of


INNER JOIN keyword in above statement because the
inner join is the default join.
 E.g. Let us consider the following two
relations.
 Join the two table tbl_filmname and tbl_actor
using inner join.
 SELECT Filmid, Filmname,

Firstname,Lastname FROM tbl_filmname JOIN


tbl_actor ON
tbl_filmname.filmid=tbl_actor.filmid
Or
 SELECT * FROM tbl_Filmname tf, tbl_actor ta

where tf.filmid=ta.filmid
2. Outer Join:
 The outer join displays the result set
containing all the rows from one table and
matching rows from another table.
 An outer join displays NULL for the columns

of the related table where it doesn’t find


matching records.
 An outer join is of following types.
a. Left Outer join:
 A left outer join returns all the rows from the
table specified on left side of LEFT OUTER
JOIN keyword and the matching rows from
the table specified on the right side.
 It displays NULL for the columns of the table

specified on the right side where it doesn’t


find matching records.
 Syntax:

SELECT <column_name> FROM


<table1> LEFT OUTER JOIN <table 2> ON
<table1>.<common_field><join
operator><table2> .<common_field>
b. Right Outer join:
 A right outer join returns all the rows from
the table specified on the right hand side of
the RIGHT OUTER JOIN keyword and the
matching rows from the table specified on
the left side.
 It displays NULL for the columns of the table

specified on the left side where it doesn’t find


matching records.
 Syntax:

SELECT <column_name> FROM <table1>


RIGHT OUTER JOIN <table 2> ON
<table1>.<common_field><join
operator><table2> .<common_field>
c. Full Outer join:
 A full outer join is the combination of left
outer join and right outer join which returns
all the matching and non matcing rows from
both the tables. In case of non matching
rows, a NULL values is displayed for the
columns for which the data is not available.
 Syntax:

SELECT <column_name> FROM <table1>


FULL OUTER JOIN <table 2> ON
<table1>.<common_field><join
operator><table2> .<common_field>
Eg:
1) Join the two table tbl_filmname and tbl_actor
using left outer join
SELECT * FROM tbl_filmname LEFT OUTER
JOIN tbl_actor ON
tbl_filmname.filmid=tbl_actor.filmid
2) Join the two table tbl_filmname and tbl_actor
using right outer join
SELECT * FROM tbl_filmname RIGHT OUTER
JOIN tbl_actor ON
tbl_filmname.filmid=tbl_actor.filmid
3) Join the two table tbl_filmname and tbl_actor
using full outer join
SELECT * FROM tbl_filmname FULL OUTER
JOIN tbl_actor ON
tbl_filmname.filmid=tbl_actor.filmid
3. Cross join:
 A cross join also known as Cartesian product
joins each row from one table with each row
on the other table.
 If P is the number of rows in first table and Q

be in second table, then the total number of


rows in the result set is P *Q.
 Syntax: SELECT<column_names>

FROM<table1> CROSS JOIN<table 2>


4. Equi join:
 A equi join is similar to the inner join with
joining condition which is based on the
equality between values in the common
columns.
Q. How equi-join is different from inner join?
 The difference is, equi join is used to retrieve

all the columns from both the tables but


inner join is used to retrieve selected columns
from tables. So using this join operation
results a common column to appear
redundantly in the resultant table.
Stored Procedure
 When a batch of SQL statements needs to be
executed more than once, we need to recreate SQL
statement and submit them to the server. This
leads to an increase in the overhead, as the server
needs to compile and create the execution plan
for these statements again. Therefore, if we need
to execute a batch multiples times, we can save it
within a stored procedure. A stored procedure is a
precompiled object stored in a database data
dictionary.

 A stored procedure is also called as proc, sproc or


sp and is similar to the user defined functions.
Stored procedure can invoke both DDL and DML
statements and can return values.
 Advantages:
1. Faster
2. Better Security because calls are
parameterized.

 Disadvantages:
1. Less flexible because we need DBA to
make changes
Creating Stored Procedure
 We can create stored procedure using CREATE
PROCEDURE statement.
 Syntax

CREATE PROCEDURE <procedure_name> AS


BEGIN
Sql_statement1
Sql_statement2

Sql_statementN

END
 E.g.
CREATE PROCEDURE sp_mobile AS
BEGIN
SELECT * FROM tbl_mobile
END

 When the CREATE PROCEDURE command is


executed, the server compiles the procedure
and save it as a database object.
 The procedure is then available for various

applications to execute.
Executing a Stored Procedure
 A procedure can be executed using EXECUTE
or EXEC statement.
 Syntax:

EXECUTE | EXEC <procedure_name>


 E.g.

EXEC sp_mobile
Altering Stored Procedure
 A stored Procedure can be modified by using
ALTER PROCEDURE statement.
 Syntax:

ALTER PROCEDURE<procedure_name> AS
BEGIN
Sql_statement1
Sql_statement2
Sql_statementN
END
Dropping a stored Procedure
 We can destroy a stored procedure form
database by using DROP PROCEDURE
statement.
 Syntax:

DROP PROCEDURE <procedure_name>


Creating a Parameterized Stored Procedure
 A parameterized stored procedure is
necessary when we need to execute a
procedure for different values of a variable
that are provided at runtime.
 Parameters are used to pass values to stored

procedure during run time. Each parameter


has a name and its data type
 Syntax:
CREATE PROCEDURE <procedure_name>
@parameter1 data type1,
@parameter2 data type2, . .

@parameterN data typeN


As
BEGIN
Sql_statement1
Sql_statement2 .

Sql_statementN
END
E.g.
CREATE PROC sp_mob
@mobile_type varchar(50)
AS
BEGIN
SELECT * FROM tbl_mobile WHERE
mobile_type=@mobile_type
END
Query By Example (QBE)
 QBE is a graphical query language which is
based on the domain relational calculus.
 A user needs minimal information to get

Started and the whole language contains


relatively few concepts. QBE is especially
suited for queries that are not too complex
and can be expressed in terms of a few
tables.
 QBE provide a tabular interface that has

expressive power of relational calculus in a


user friendly form i.e queries look like table.
 Here queries are expressed by ‘example’.
 E.g. Let us consider the following three
relations.
 Sailors (sid, sname, age)
 Boats(bid, bname,color)
 Reserve(sid,bid,day)

You might also like