SlideShare a Scribd company logo
1
SQL (Structured Query Language)
SQL is a database language.
It is a comprehensive database language that
facilitates data definition, data manipulation &
view definition.
SQL follows ANSI & ISO standard.
2
We will refer to this
schema in our
discussion on SQL.
Company database schema
3
4
Creating table
5
Creating table
6
Creating table
7
Creating table
8
Creating table
9
Defining foreign key on a table
alter table employee add foreign
key(dno) references
department(dnumber);
alter table employee add foreign
key(super_ssn) references
employee(ssn);
10
You may assign name to a constraint
alter table employee add constraint
empfk1 foreign key(super_ssn)
references employee(ssn);
alter table employee add constraint
empfk2 foreign key(dno) references
department(dnumber);
11
Defining primary key and secondary key
on table
alter table employee add primary key(ssn);
alter table department add primary
key(dnumber);
alter table department add unique(dname);
alter table works_on add primary key(essn, pno);
12
Assigning name to a constraint
alter table employee add constraint emp_pk
primary key(ssn);
alter table department add constraint dept_pk
primary key(dnumber);
alter table works_on add constraint works_on_pk
primary key(essn, pno);
alter table department add constraint dept_sk
unique(dname);
13
Removing constraint
alter table employee drop constraint empfk1;
(no quotes in constraint name)
14
Disabling & enabling constraint
alter table employee disable constraint empfk2;
alter table employee enable constraint empfk2;
15
Adding new column to a table
alter table employee
add email varchar2(20);
alter table employee
add email varchar2(20) not null;
alter table employee
add mobile char(10) not null;
16
Adding new columns to a table
alter table employee add
(email varchar2(20), mobile char(10));
alter table employee add
(email varchar2(20) not null,
mobile char(10));
17
Removing columns from a table
alter table employee drop column minit;
alter table employee drop (mobile, email);
18
Modifying column
alter table employee
modify address varchar2(40);
alter table employee
modify address varchar2(40) not null;
19
Modifying multiple columns
alter table employee modify
(email varchar2(24) not null, mobile char(13));
20
Making column value mandatory
To make a column value mandatory qualify its
definition with
not null.
Examples:
alter table employee modify super_ssn not null;
alter table employee modify dno not null;
21
Defining default value
To assign a default value to a column
you need to use the keyword default.
Examples:
alter table employee modify
dno default 1;
alter table employee modify
super_ssn default ‘888445555’;
22
Defining default value & making column value
mandatory
Examples:
alter table employee modify
super_ssn default ‘888445555’ not null;
alter table employee modify
dno default 1 not null;
If fname column of employee table is already declared
as not null. To declare it as null use:
alter table employee modify fname null;
23
Altering default value &
Removing default value
Altering default value
alter table employee modify dno default 4;
Removing default value
alter table employee modify dno default null;
New value of default
24
Declaring default in table definition
create table employee (
Fname varchar2(15) not null,
Minit char(1),
Lname varchar2(15) not null,
Ssn char(9) not null,
Bdate date
Address varchar2(30),
Gender char(1),
Salary number(10,2),
Super_ssn char(9),
Dno number(1) default 1 not null,
constraint emppk primary key(ssn),
constraint empfk1 foreign key(super_ssn) references
employee(ssn),
constraint empfk2 foreign key(dno) references
department(dnumber) );
25
Declaring check constraint in table definition
create table employee (
Fname varchar2(15) not null,
Minit char(1),
Lname varchar2(15) not null,
Ssn char(9), not null,
Bdate date
Address varchar2(30),
Gender char(1),
Salary number(10,2),
Super_ssn char(9),
Dno number(1) default 1 not null,
constraint emppk primary key(ssn),
constraint empfk1 foreign key(super_ssn) references employee(ssn),
constraint empfk2 foreign key(dno) references department(dnumber),
check (gender = 'F' or gender = 'M'),
check (salary > 50000));
26
Declaring check constraint in table definition
create table department (
dnumber number(1) not null
check (dnumber > 0 and dnumber < 6),
…
);
create table department (
dnumber number(1) not null
check (dnumber in (1, 5, 4)),
…
);
27
Declaring check constraint in table definition
create table dependent (
essn char(9) not null,
dname varchar2(12) not null,
gender char(1),
relationship varchar2(8)
check (relationship in (‘spouse’, ‘son’, ‘daughter’,
‘parent’)),
…);
28
Assigning name to check constraint
create table employee (
Fname varchar2(15) not null,
Minit char(1),
Lname varchar2(15) not null,
Ssn char(9) not null,
Bdate date,
Address varchar2(30),
Gender char(1),
Salary number(10,2),
Super_ssn char(9),
Dno number(1) default 1 not null,
constraint emppk primary key(ssn),
constraint empfk1 foreign key(super_ssn) references employee(ssn),
constraint empfk2 foreign key(dno) references department(dnumber),
constraint gender_cons
check(gender = 'F' or gender = 'M'),
constraint salary_cons check(salary > 50000));
30
Adding check constraint to existing table
alter table employee add
check (gender = ‘F’ or gender = ‘M’);
alter table employee add constraint emp_gender
check (gender = ‘F’ or gender ‘M’);
alter table employee add check
(salary > 25000 and salary <= 140000);
A check constraint allows you to restrict value of a column.
31
Changing table name
alter table employee rename to employee1;
alter table <old_table_name> rename to
<new_table_name>
32
Changing column name
alter table project rename column dnum to dno;
alter table dependent rename column essn to ssn;
alter table works_on rename column essn to ssn;
33
Remove a table
drop table employee;
34
Data entry (insert statement)
insert into employee values (
‘Richard’, ‘K’, ‘Marini’,
‘653653653’, ’30-dec-1982’, ’98 Oak Forest, Katy, TX’, ‘M’,
37000, ‘888665555’, 4 );
insert into employee (
fname, mint, lname, ssn, bdate, address, gender, salary,
super_ssn, dno)
values (
‘Richard’, ‘K’, ‘Marini’, ‘653653653’, ’30-dec-1982’,
’98 Oak Forest, Katy, TX’,‘M’, 37000, ‘888665555’, 4 );
Mentioning column name here is not mandatory.
35
Data entry (insert statement)
insert into employee (
ssn, fname, mint, lname, bdate, address, gender, salary,
super_ssn, dno)
values
(‘653653653’, ‘Richard’, ‘K’, ‘Marini’, ’30-dec-1982’,
’98 Oak Forest, Katy, TX’,‘M’, 37000, ‘888665555’, 4 );
Entering data into selective column
insert into employee (
fname, lname, ssn, super_ssn, dno)
values (
‘Richard’, ‘Marini’, ‘653653653’, ‘888665555’, 4 );
36
Column that may be left out
 null column may be left out.
 column with default (but not declared as not
null) may be left out.
 not null column without default must be
mentioned.
37
Failure of insert statement
 Insert statement fails if one of the following
constraints is violated
 Domain constraint
 Entity integrity constraint
 Key constraint
 Referential integrity constraint
38
Failure of insert statement
Domain of a column is the set of all possible values that the
column can assume. While entering data domain
constraint is said to have been violated if an attempt is
made to assign value to a column outside its domain. In this
case the DBMS restricts the data entry and the insert
statement fails.
Entity integrity constraint (EIC) states that primary key
value cannot be null.
Any attempt to leave out the value in the primary key
column (s) results in violation of EIC and in case of such
violation DBMS restricts data entry and the insert statement
fails.
39
Failure of insert statement
Key constraint states that key value across rows
of a table cannot have duplicate (e.g. you cannot
enter duplicate values in the ssn column of
department table). Any attempt to enter duplicate
value in key (primary / secondary) is restricted by
DBMS and data entry fails.
Referential integrity constraint (RIC) states that a
row can refer to an existing row only. RIC is
specified using foreign key. Insert statement fails
if RIC is violated.
40
Changing existing data (update statement)
update employee set salary = 65000
where ssn = ‘888665555’;
update employee set salary = salary + 5000
where dno = 5;
update employee set dno = 5, salary = salary*1.2
where dno = 4;
update employee set salary = null
where ssn = ‘123456789’;
41
Update statement
update employee set dno = default
where ssn = ‘123456789’;
update employee set
salary = null, dno = default
where ssn = ‘123456789’;
42
Update statement can update only one
table
An update statement can update only one table.
One update statement cannot update multiple tables
together.
An update statement cannot update dnumber column of
department and dno column of employee together.
Syntax of update statement
update <table_name>
set <column_name> = <expression>
[,<column_name = <expression>]
[where <condition>]
43
Failure of update statement
 Update statement fails if one of the following
constraints is violated
 Domain constraint
 Entity integrity constraint
 Key constraint
 Referential integrity constraint
Referential integrity
constraint is violated
whenever an attempt is
made to delete a row
from department table or
update Dnumber column
to any value other than
1, 5, 4.
45
Failure of update statement
 To avoid violation of referential integrity
constraint, when you define foreign key in the
Employee table do one of the following.
 alter table employee add foreign key(dno)
references Department(dnumber) on update
cascade
 alter table employee add foreign key(dno)
references Department(dnumber) on update
set null
 alter table employee add foreign key(dno)
references Department(dnumber) on update
set default
Removing rows from table (delete
statement)
delete from employee where ssn = ‘888665555’;
delete from employee where salary > 30000;
delete from employee where salary > 30000 and dno = 4;
delete from employee where salary between 30000 and
40000;
delete from employee;
One delete command can delete data from one table only.
46
47
Failure of delete statement
 Delete statement fails if Referential integrity
constraint is violated. To resolve this
problem you do one of the following:
 alter table Employee add foreign key(dno)
references Department(dnumber) on delete
cascade
 alter table Employee add foreign key(dno)
references Department(dnumber) on delete set
null
 alter table Employee add foreign key(dno)
references Department(dnumber) on delete set
default
48
You may combine actions on update with
delete
 alter table Employee add foreign key(dno)
references Department(dnumber) on delete
cascade on update cascade
 And the likes
49
Select statement (Retrieving data from database)
• Retrieves data from database
• Can only read database, cannot modify it
Examples of data retrieval
 Reading balance in bank account
 Viewing term end results
 Viewing attendance status
 Looking for availability of rail/flight ticket
 Browsing through www.flipcart.com to find out the
available books on database systems
50
Company database schema
EMPLOYEE(Fname, Minit, Lname, Ssn, Bdate, Address,
Gender, Salary, Super_ssn, Dno)
DEPARTMENT(Dname, Dnumber, Mgr_ssn, Mgr_strat_date)
PROJECT(Pname, Pnumber, Plocation, Dnum)
DEPT_LOCATIONS(Dnumber, Dlocation)
WORKS_ON(Essn, Pno, Hours)
DEPENDENT(Essn, Dependent_name, Gender, Bdate,
Relationship)
51
Select statement (Retrieving data)
Retrieve all information of all projects.
select * from project;
Retrieve name of all projects and its location.
select pname, plocation from project;
52
Select statement
Find out the name of the employees, their address
and salary.
select fname, minit, lname, address, salary
from employee;
53
Select statement (WHERE clause)
Find out the last name & first name of the
employees with salary higher than $40000.
select lname, fname
from employee
where salary > 40000;
54
WHERE clause
select lname, fname from employee
where salary >= 30000 and salary <= 55000;
select lname, fname from employee
where salary between 30000 and 55000;
<> or != Not equal to
Find out the birth date and address of the employee (s)
whose name is John B. Smith.
Select bdate, address from employee
where fname = ‘John’ and minit = ‘B’ and lname = ‘Smith’
Output of a query is displayed as a table.
55
Substring pattern matching
using % (zero or more character) in WHERE
clause
Retrieve name of employees whose last name
starts with an S.
select fname, minit, lname from employee
where lname like ‘S%’; (%  zero or more characters)
Retrieve lname & fname of employees who live in
Texas.
select lname, fname from employee
where address like ‘%TX%’;
56
Using _ (exactly one character)
Retrieve first name and last name of employees whose first
name has an o as the second character.
select fname, lname from employee where fname like ‘_o%’;
( _  exactly one character)
Retrieve the first name and last name of employees whose
last name has an e as the fourth character.
select fname, lname from employee where lname like
‘___e%’;
57
What if the string contains _ or % ?
Find out first name and last name of employees
with _ as one of the characters in their email
address.
select fname, lname from employee where email
like ‘%_%’ escape ‘’;
58
What if the string contains _ or % ?
Find out first name and last name of employees
with % as one of the characters in their email
address.
select fname, lname from employee
where email like ‘%%%’ escape ‘’;
Any character that has not been used in the string
may be used as escape character.
59
is null & is not null
(Testing presence of data in a column)
Tell me the name of the employee who do not have a
supervisor.
select fname, minit, lname from employee where super_ssn
is null;
Tell me the name of the employees who do not have email
address.
select fname, lname from employee where email is null;
60
is null & is not null
Tell me the name of the employees who have
email address but did not provide their mobile
number.
select fname, lname from employee
where email is not null and mobile is null;
61
Eliminating duplicate rows from the output of a
query
Output of a select statement is a table.
To eliminate duplicate rows
use distinct clause.
Show me the distinct salary values.
select distinct salary from employee;
Show me the supervisor`s ssn only.
select distinct super_ssn from employee;
Null is treated as different from any other values.
62
Arithmetic operators in query
What would be the salary of the employees if they
get a hike of 10%?
select 1.1*salary from employee;
63
ORDER BY clause
Sorts output of select statement. Default order ascending
select fname, lname, salary from employee order by salary;
select fname, lname from employee order by salary desc;
select fname, lname, salary from employee
order by fname, salary desc;
select fname, lname from employee
order by fname, lname, salary;
64
ORDER BY with WHERE clause
select fname, lname, salary
from employee
where salary < 60000
order by salary desc;
65
Aggregate functions
sum, avg, max, min, count are SQL aggregate
functions
Aggregate functions compute summary of data.
sum (column header) computes total value in this
column.
You may also use distinct keyword before
column header.
Aggregate functions
Similarly, avg, max, min
computes the arithmetic mean, maximum and
minimum respectively of a column.
The count function computes number of values
present in the column.
In all these functions the column header can be
preceded by keyword distinct.
66
67
Aggregate functions
Sum and avg function can be applied on numeric
data only,
but count, max and min can be applied on
numeric as well as alphanumeric data.
68
Aggregate functions
Examples:
select sum(salary) from employee;
select avg(salary) from employee;
select sum(salary), avg(salary), max(salary),
min(salary), count(*) from employee;
Find out the number of supervisors in the
company.
69
Group by clause
Group by clause is used when you want to apply
aggregate function on groups of rows in a table. In these
cases we need to partition the relation into non
overlapping groups of rows. Each group (also called
partition) will consist of the rows that have the same
value of some column (s), called the grouping column
(s). We can then apply the function to each such group
independently to produce summary information about
each group.
If null value exists in the grouping column, then a
separate group is created for all rows with a null value in
the grouping column.
70
GROUP BY clause
Tell me the average salary of each department and the
number employees who work in the department.
71
How does GROUP BY work?
72
Using GROUP BY clause
Tell me the number of projects each employee
works on.
Select count(pno) from works_on group by essn;
Tell me the number of employees working in each
project.
Select count(essn) from works_on group by pno;
73
HAVING clause in select statement
HAVING <condition>
condition should be on an aggregate function and (or)
grouping column.
having avg(salary) > 30000;
having salary > 30000; (incorrect)
HAVING clause operates on summery data & grouping
column (s).
74
HAVING with GROUP BY clause
Tell me those departments that have average salary of
employees higher than $40000;
Select dno from employee group by dno having avg(salary)
> 40000
Give me those project numbers that involve at least three
employees.
Select pno from works_on group by pno having count(essn)
>= 3;
75
Format of select statement
SELECT <list of columns, summary data>
FROM <list of tables>
WHERE <condition>
GROUP BY <list of columns>
HAVING <condition on summary data, grouping column>
ORDER BY <list of columns, summary data>
76
Joining tables - Multiple tables in select statement
Tell me the name of project & the name of
controlling department.
77
Joining tables
Consider two tables namely,
PROJECT and DEPARTMENT.
Now concatenate each row of
PROJECT table with each row of
DEPARTMENT table and by this
process you get join of two tables.
The output of this join is shown
in the next slide, along with the
query that produces this output.
Output of
select * from project, department;
There are some rows that are invalid e.g. the second row which gives two different
values of department number for the project ProductX, but a project is under the
control of a single department. To avoid this, use join condition (Fkey = Pkey)
79
Joining tables - Multiple tables in select statement
Retrieve the name of project and name of controlling
department.
select pname, dname from project , department
where dnum = dnumber;
Retrieve the name of employee and name of department
he/she works.
select fname, minit, lname, dname
from employee, department where dno = dnumber;
The above SQL statement may also be written as:
select fname, minit, lname, dname from
employee join department on dno = dnumber;
80
Joining tables - Multiple tables in select statement
Find out first name, last name and address of all employees
who work in administration department.
select fname, lname, address from employee, department
where dno = dnumber and dname = ‘Administration’;
select fname, lname, address from employee join
department on dno = dnumber and dname =
‘Administration’;
81
Join
Retrieve name of project and name of controlling
department
select pname, dname from project, department
where dnum = dnumber;
82
Join
Tell me the first name, last name and address of
employees who work in administration
department
select fname, lname, address from employee,
department where dno = dnumber and dname
= ‘Administration’;
83
Natural join
If name of the foreign key is the same as that of
primary key you may use natural join as
illustrated in the following example.
Find out name of department name and its
location.
Select dname, dlocation from department
natural join dept_locations
84
Join
Tell me the first name and last name of employees and the
project number they are involved in.
select fname, lname, pno from employee, works_on where
essn = ssn;
Tell me the first name and last name of employees and the
name of the project (s) they are involved in.
select fname, lname, pno from employee, works_on, project
where essn = ssn and pno = pnumber;
85
Join
For every project located in ‘Stafford’, list project number,
controlling department number and the department
manager’s last name.
For the SQL query see the next slide.
86
Query
select pnumber, dnum, lname
from project, department, employee
where dnum = dnumber and mgr_ssn = ssn
and plocation = ‘Stafford’;
select pnumber, dnum, lname
from ((project join department on dnum = dnumber) join
employee on mgr_ssn = ssn)) where plocation = ‘Stafford’;
select pnumber, dnum, lname
from project natural join department natural join employee
where plocation = ‘Stafford’;
87
Self join
For each employee, retrieve the employee’s first and the
first name of his or her immediate supervisor.
select e.fname, s.fname
from employee e, employee s
where e.super_ssn = s.ssn;
88
Set theoretic operations
union, intersect, minus.
You may combine the output of two or more queries using
these set operations provided that the query outputs have
the same schema.
e.g.
Find out name of employees who do not have dependent.
(select fname, minit, lname from employee)
minus
(select fname, minit, lname
from employee, dependent where essn = ssn);
89
Set theoretic operations
Find out project number where Franklin Wong
works either as a manager or as a worker.
(Select pnumber from employee, department,
project where mgr_ssn = ssn and
dnum = dnumber and fname = ‘Franklin’
and lname = ‘Wong’)
union
(Select pno from employee, works_on
where essn = ssn and fname = ‘Franklin’
and lname = ‘Wong’)
90
Union all, intersect all, minus all
Union, intersect and minus eliminates duplicates
(if any) before displaying the results of the query.
If you need to retain duplicates then use union all,
intersect all and minus all.
91
Nested queries
 If there is a query inside another query then
the SQL statement is called a nested query.
 You may have any number of levels of nesting.
 The general look of nested query is
 Outer query (inner query);
 Outer query (inner query1 (inner query2));
In the following nested query is illustrated with
examples.
92
Nested queries
Find out name of the department where John
Smith works.
select dname from department where dnumber =
(select dno from employee where fname =
‘John’ and lname = ‘Smith’)
93
Nested queries
 Retrieve the department name where last
name of persons working in the department
starts with an S.
select dname from department
where dnumber in (select dno from employee
where lname like ‘S%’ );
 Find out the name of the employee who draws
the highest salary.
select fname, minit, lname from employee where
salary = (select max(salary) from employee)
94
Nested queries
Retrieve the ssn of employees who work on the
same project as Smith does.
select distinct essn from works_on where pno in
(select pno from works_on where essn =
(select ssn from employee where lname
=‘Smith’));
95
Uncorrelated & Correlated nested query
When an inner query does not access the columns
of the table used in outer query then the nested
query is called uncorrelated nested query.
But when an inner query accesses the columns of
the table used in outer query then the nested
query is called correlated nested query.
Nested queries that you have seen so far are
uncorrelated nested query.
96
Correlated nested query
Retrieve the name of employees whose dependent
has the same name as the last name of the
employee.
select fname, lname from employee where
ssn in (select essn from dependent where
dependent_name = lname);
97
Correlated nested query
Retrieve the last name of employees who has a
dependent with the same gender as that of the
employee.
select e.lname from employee e where e.ssn in
(select essn from dependent
where e.gender = gender);
98
Correlated nested query
Retrieve the names of all employees who have
two or more dependents.
select lname, fname from employee
where (select count(*) from dependent
where essn = ssn) >= 2;
N.B. The outer query is colored.
99
exists & not exists function
exists and not exists functions are used in relation
to nested query.
Usage:
(outer query) where exists (inner query);
(outer query) where not exists (inner query);
100
exists & not exists function
not exists (inner query)
returns true if inner query does not return
result, otherwise it returns false.
exists (inner query)
returns true if inner query returns one or more
rows, otherwise it returns false.
101
not exists function - example
Retrieve the name of employees who do not have
dependent.
select fname, lname from employee
where not exists (select * from dependent where
ssn = essn);
102
exists function - example
Retrieve the name of employees who have at
least one dependent.
select fname, lname from employee
where exists (select * from dependent
where ssn = essn);
103
Correlated vs. uncorrelated nested queries
In case of correlated nested query, the inner is
executed once for every row of the table in the
outer query whereas, in case of uncorrelated
nested query, the inner query is executed only
once, and the output of the inner query is used to
evaluate outer query.
How many times does the inner query execute in
correlated nested query?
How many times does the inner query execute in
uncorrelated nested query?
104
Outer join
• Left outer join
• Right outer join
• Full outer join
Left outer join produces data from matching rows (for which
foreign key = primary key) from the participating tables and
data from non-matching rows from the left table. Right outer
join behaves in a similar way. The full outer join is the union
of left outer join and right outer join.
105
Outer join
Display name of employees and their immediate
supervisor without missing out employees who do
not have supervisor.
Select e.fname, e.lname, s.fname, s.lname
from employee e left outer join employee s
on e.super_ssn = s.ssn;
The key word outer, in such queries, is optional.
106
Outer join
Display name of all employees and their
dependents without leaving out employees who
did not register their dependent detail in the
company database.
Select fname, lname, dependent_name
from employee left outer join dependent
on essn = ssn;
107
Views
A view is a perspective of a database.
To create a view use
create view view_name as <query>;
To drop a view use
drop view view_name;
108
Views
Create view empdept as
select fname, lname, salary, dname from
employee, department where dno = dnumber;
109
Reference
 Fundamentals of Database Systems,
R. Elmasri & S.B. Navathe
Pearson education, 2011.
 Chapter 4 & 5 – Elmasri & Navathe,
Sixth edition

More Related Content

What's hot

Introduction to IoT (Basics of Networking & Emergence of IoT).pptx
Introduction to IoT (Basics of Networking & Emergence of IoT).pptxIntroduction to IoT (Basics of Networking & Emergence of IoT).pptx
Introduction to IoT (Basics of Networking & Emergence of IoT).pptx
taruian
 
NFV for beginners
NFV for beginnersNFV for beginners
NFV for beginners
Dave Neary
 
BinarySearchTree-bddicken
BinarySearchTree-bddickenBinarySearchTree-bddicken
BinarySearchTree-bddicken
Benjamin Dicken
 
Day 3 ENHANCED IGRP (EIGRP) AND OPEN SHORTEST PATH FIRST (OSPF)
Day 3 ENHANCED IGRP (EIGRP) AND OPEN SHORTEST PATH FIRST (OSPF)Day 3 ENHANCED IGRP (EIGRP) AND OPEN SHORTEST PATH FIRST (OSPF)
Day 3 ENHANCED IGRP (EIGRP) AND OPEN SHORTEST PATH FIRST (OSPF)
anilinvns
 
Codd's Rules for Relational Database Management Systems
Codd's Rules for Relational Database Management SystemsCodd's Rules for Relational Database Management Systems
Codd's Rules for Relational Database Management Systems
Rajeev Srivastava
 
Linked lists
Linked listsLinked lists
Linked lists
SARITHA REDDY
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - Graph
Madhu Bala
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In SqlAnurag
 
ENSA_Module_8.pptx
ENSA_Module_8.pptxENSA_Module_8.pptx
ENSA_Module_8.pptx
JoseLopez1854
 
Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | Edureka
Edureka!
 
Operators in java
Operators in javaOperators in java
Operators in java
yugandhar vadlamudi
 
VPLS Fundamental
VPLS FundamentalVPLS Fundamental
VPLS Fundamental
Reza Farahani
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
Masud Parvaze
 
08 subprograms
08 subprograms08 subprograms
08 subprograms
baran19901990
 
Chapter 15 : routing concepts
Chapter 15 : routing conceptsChapter 15 : routing concepts
Chapter 15 : routing concepts
teknetir
 
Information Centric Networking
Information Centric NetworkingInformation Centric Networking
Information Centric Networking
Shahneel Siddiqui
 
Dbms keys
Dbms keysDbms keys
Dbms keys
pyingkodi maran
 
Subroutines
SubroutinesSubroutines
Sql delete, truncate, drop statements
Sql delete, truncate, drop statementsSql delete, truncate, drop statements
Sql delete, truncate, drop statementsVivek Singh
 

What's hot (20)

Introduction to IoT (Basics of Networking & Emergence of IoT).pptx
Introduction to IoT (Basics of Networking & Emergence of IoT).pptxIntroduction to IoT (Basics of Networking & Emergence of IoT).pptx
Introduction to IoT (Basics of Networking & Emergence of IoT).pptx
 
NFV for beginners
NFV for beginnersNFV for beginners
NFV for beginners
 
BinarySearchTree-bddicken
BinarySearchTree-bddickenBinarySearchTree-bddicken
BinarySearchTree-bddicken
 
Day 3 ENHANCED IGRP (EIGRP) AND OPEN SHORTEST PATH FIRST (OSPF)
Day 3 ENHANCED IGRP (EIGRP) AND OPEN SHORTEST PATH FIRST (OSPF)Day 3 ENHANCED IGRP (EIGRP) AND OPEN SHORTEST PATH FIRST (OSPF)
Day 3 ENHANCED IGRP (EIGRP) AND OPEN SHORTEST PATH FIRST (OSPF)
 
Codd's Rules for Relational Database Management Systems
Codd's Rules for Relational Database Management SystemsCodd's Rules for Relational Database Management Systems
Codd's Rules for Relational Database Management Systems
 
Sql select
Sql select Sql select
Sql select
 
Linked lists
Linked listsLinked lists
Linked lists
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - Graph
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
ENSA_Module_8.pptx
ENSA_Module_8.pptxENSA_Module_8.pptx
ENSA_Module_8.pptx
 
Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | Edureka
 
Operators in java
Operators in javaOperators in java
Operators in java
 
VPLS Fundamental
VPLS FundamentalVPLS Fundamental
VPLS Fundamental
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
 
08 subprograms
08 subprograms08 subprograms
08 subprograms
 
Chapter 15 : routing concepts
Chapter 15 : routing conceptsChapter 15 : routing concepts
Chapter 15 : routing concepts
 
Information Centric Networking
Information Centric NetworkingInformation Centric Networking
Information Centric Networking
 
Dbms keys
Dbms keysDbms keys
Dbms keys
 
Subroutines
SubroutinesSubroutines
Subroutines
 
Sql delete, truncate, drop statements
Sql delete, truncate, drop statementsSql delete, truncate, drop statements
Sql delete, truncate, drop statements
 

Similar to ALL BASIC SQL SERVER QUERY

Sql server ___________session_15(data integrity)
Sql server  ___________session_15(data integrity)Sql server  ___________session_15(data integrity)
Sql server ___________session_15(data integrity)
Ehtisham Ali
 
Here is the company database--comments can be addedD.pdf
Here is the company database--comments can be addedD.pdfHere is the company database--comments can be addedD.pdf
Here is the company database--comments can be addedD.pdf
fckindswear
 
Here is the company database for the problem--commen.pdf
Here is the company database for the problem--commen.pdfHere is the company database for the problem--commen.pdf
Here is the company database for the problem--commen.pdf
fazilfootsteps
 
Chapter08
Chapter08Chapter08
Chapter08
sasa_eldoby
 
6 integrity and security
6 integrity and security6 integrity and security
6 integrity and securityDilip G R
 
Obtain better data accuracy using reference tables
Obtain better data accuracy using reference tablesObtain better data accuracy using reference tables
Obtain better data accuracy using reference tables
Kiran Venna
 
6_SQL.pdf
6_SQL.pdf6_SQL.pdf
6_SQL.pdf
LPhct2
 
CONSTRAINTS PPT.pptx
CONSTRAINTS PPT.pptxCONSTRAINTS PPT.pptx
CONSTRAINTS PPT.pptx
ThangaduraiA4
 
الوحدة التاسعة - قاعدة البيانات وادارتها
الوحدة التاسعة - قاعدة البيانات وادارتهاالوحدة التاسعة - قاعدة البيانات وادارتها
الوحدة التاسعة - قاعدة البيانات وادارتها
Amin Abu Hammad
 
DBMS.pptx
DBMS.pptxDBMS.pptx
DBMS.pptx
Geetha Kannan
 
SQL.pptx
SQL.pptxSQL.pptx
SQL.pptx
SAIFKHAN41507
 
Integrity constraint fundamentals of dbms.pdf
Integrity constraint fundamentals of dbms.pdfIntegrity constraint fundamentals of dbms.pdf
Integrity constraint fundamentals of dbms.pdf
Saikrishna492522
 
DOODB_LAB.pptx
DOODB_LAB.pptxDOODB_LAB.pptx
DOODB_LAB.pptx
FilestreamFilestream
 

Similar to ALL BASIC SQL SERVER QUERY (20)

Sql server ___________session_15(data integrity)
Sql server  ___________session_15(data integrity)Sql server  ___________session_15(data integrity)
Sql server ___________session_15(data integrity)
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
 
Here is the company database--comments can be addedD.pdf
Here is the company database--comments can be addedD.pdfHere is the company database--comments can be addedD.pdf
Here is the company database--comments can be addedD.pdf
 
Here is the company database for the problem--commen.pdf
Here is the company database for the problem--commen.pdfHere is the company database for the problem--commen.pdf
Here is the company database for the problem--commen.pdf
 
Data integrity
Data integrityData integrity
Data integrity
 
Chapter08
Chapter08Chapter08
Chapter08
 
6 integrity and security
6 integrity and security6 integrity and security
6 integrity and security
 
Obtain better data accuracy using reference tables
Obtain better data accuracy using reference tablesObtain better data accuracy using reference tables
Obtain better data accuracy using reference tables
 
Sql wksht-2
Sql wksht-2Sql wksht-2
Sql wksht-2
 
6_SQL.pdf
6_SQL.pdf6_SQL.pdf
6_SQL.pdf
 
Integrity and security
Integrity and securityIntegrity and security
Integrity and security
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
CONSTRAINTS PPT.pptx
CONSTRAINTS PPT.pptxCONSTRAINTS PPT.pptx
CONSTRAINTS PPT.pptx
 
الوحدة التاسعة - قاعدة البيانات وادارتها
الوحدة التاسعة - قاعدة البيانات وادارتهاالوحدة التاسعة - قاعدة البيانات وادارتها
الوحدة التاسعة - قاعدة البيانات وادارتها
 
DBMS.pptx
DBMS.pptxDBMS.pptx
DBMS.pptx
 
Les09
Les09Les09
Les09
 
SQL.pptx
SQL.pptxSQL.pptx
SQL.pptx
 
Integrity constraint fundamentals of dbms.pdf
Integrity constraint fundamentals of dbms.pdfIntegrity constraint fundamentals of dbms.pdf
Integrity constraint fundamentals of dbms.pdf
 
DOODB_LAB.pptx
DOODB_LAB.pptxDOODB_LAB.pptx
DOODB_LAB.pptx
 
Les08
Les08Les08
Les08
 

Recently uploaded

Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 

Recently uploaded (20)

Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 

ALL BASIC SQL SERVER QUERY

  • 1. 1 SQL (Structured Query Language) SQL is a database language. It is a comprehensive database language that facilitates data definition, data manipulation & view definition. SQL follows ANSI & ISO standard.
  • 2. 2 We will refer to this schema in our discussion on SQL. Company database schema
  • 3. 3
  • 9. 9 Defining foreign key on a table alter table employee add foreign key(dno) references department(dnumber); alter table employee add foreign key(super_ssn) references employee(ssn);
  • 10. 10 You may assign name to a constraint alter table employee add constraint empfk1 foreign key(super_ssn) references employee(ssn); alter table employee add constraint empfk2 foreign key(dno) references department(dnumber);
  • 11. 11 Defining primary key and secondary key on table alter table employee add primary key(ssn); alter table department add primary key(dnumber); alter table department add unique(dname); alter table works_on add primary key(essn, pno);
  • 12. 12 Assigning name to a constraint alter table employee add constraint emp_pk primary key(ssn); alter table department add constraint dept_pk primary key(dnumber); alter table works_on add constraint works_on_pk primary key(essn, pno); alter table department add constraint dept_sk unique(dname);
  • 13. 13 Removing constraint alter table employee drop constraint empfk1; (no quotes in constraint name)
  • 14. 14 Disabling & enabling constraint alter table employee disable constraint empfk2; alter table employee enable constraint empfk2;
  • 15. 15 Adding new column to a table alter table employee add email varchar2(20); alter table employee add email varchar2(20) not null; alter table employee add mobile char(10) not null;
  • 16. 16 Adding new columns to a table alter table employee add (email varchar2(20), mobile char(10)); alter table employee add (email varchar2(20) not null, mobile char(10));
  • 17. 17 Removing columns from a table alter table employee drop column minit; alter table employee drop (mobile, email);
  • 18. 18 Modifying column alter table employee modify address varchar2(40); alter table employee modify address varchar2(40) not null;
  • 19. 19 Modifying multiple columns alter table employee modify (email varchar2(24) not null, mobile char(13));
  • 20. 20 Making column value mandatory To make a column value mandatory qualify its definition with not null. Examples: alter table employee modify super_ssn not null; alter table employee modify dno not null;
  • 21. 21 Defining default value To assign a default value to a column you need to use the keyword default. Examples: alter table employee modify dno default 1; alter table employee modify super_ssn default ‘888445555’;
  • 22. 22 Defining default value & making column value mandatory Examples: alter table employee modify super_ssn default ‘888445555’ not null; alter table employee modify dno default 1 not null; If fname column of employee table is already declared as not null. To declare it as null use: alter table employee modify fname null;
  • 23. 23 Altering default value & Removing default value Altering default value alter table employee modify dno default 4; Removing default value alter table employee modify dno default null; New value of default
  • 24. 24 Declaring default in table definition create table employee ( Fname varchar2(15) not null, Minit char(1), Lname varchar2(15) not null, Ssn char(9) not null, Bdate date Address varchar2(30), Gender char(1), Salary number(10,2), Super_ssn char(9), Dno number(1) default 1 not null, constraint emppk primary key(ssn), constraint empfk1 foreign key(super_ssn) references employee(ssn), constraint empfk2 foreign key(dno) references department(dnumber) );
  • 25. 25 Declaring check constraint in table definition create table employee ( Fname varchar2(15) not null, Minit char(1), Lname varchar2(15) not null, Ssn char(9), not null, Bdate date Address varchar2(30), Gender char(1), Salary number(10,2), Super_ssn char(9), Dno number(1) default 1 not null, constraint emppk primary key(ssn), constraint empfk1 foreign key(super_ssn) references employee(ssn), constraint empfk2 foreign key(dno) references department(dnumber), check (gender = 'F' or gender = 'M'), check (salary > 50000));
  • 26. 26 Declaring check constraint in table definition create table department ( dnumber number(1) not null check (dnumber > 0 and dnumber < 6), … ); create table department ( dnumber number(1) not null check (dnumber in (1, 5, 4)), … );
  • 27. 27 Declaring check constraint in table definition create table dependent ( essn char(9) not null, dname varchar2(12) not null, gender char(1), relationship varchar2(8) check (relationship in (‘spouse’, ‘son’, ‘daughter’, ‘parent’)), …);
  • 28. 28 Assigning name to check constraint create table employee ( Fname varchar2(15) not null, Minit char(1), Lname varchar2(15) not null, Ssn char(9) not null, Bdate date, Address varchar2(30), Gender char(1), Salary number(10,2), Super_ssn char(9), Dno number(1) default 1 not null, constraint emppk primary key(ssn), constraint empfk1 foreign key(super_ssn) references employee(ssn), constraint empfk2 foreign key(dno) references department(dnumber), constraint gender_cons check(gender = 'F' or gender = 'M'), constraint salary_cons check(salary > 50000));
  • 29. 30 Adding check constraint to existing table alter table employee add check (gender = ‘F’ or gender = ‘M’); alter table employee add constraint emp_gender check (gender = ‘F’ or gender ‘M’); alter table employee add check (salary > 25000 and salary <= 140000); A check constraint allows you to restrict value of a column.
  • 30. 31 Changing table name alter table employee rename to employee1; alter table <old_table_name> rename to <new_table_name>
  • 31. 32 Changing column name alter table project rename column dnum to dno; alter table dependent rename column essn to ssn; alter table works_on rename column essn to ssn;
  • 32. 33 Remove a table drop table employee;
  • 33. 34 Data entry (insert statement) insert into employee values ( ‘Richard’, ‘K’, ‘Marini’, ‘653653653’, ’30-dec-1982’, ’98 Oak Forest, Katy, TX’, ‘M’, 37000, ‘888665555’, 4 ); insert into employee ( fname, mint, lname, ssn, bdate, address, gender, salary, super_ssn, dno) values ( ‘Richard’, ‘K’, ‘Marini’, ‘653653653’, ’30-dec-1982’, ’98 Oak Forest, Katy, TX’,‘M’, 37000, ‘888665555’, 4 ); Mentioning column name here is not mandatory.
  • 34. 35 Data entry (insert statement) insert into employee ( ssn, fname, mint, lname, bdate, address, gender, salary, super_ssn, dno) values (‘653653653’, ‘Richard’, ‘K’, ‘Marini’, ’30-dec-1982’, ’98 Oak Forest, Katy, TX’,‘M’, 37000, ‘888665555’, 4 ); Entering data into selective column insert into employee ( fname, lname, ssn, super_ssn, dno) values ( ‘Richard’, ‘Marini’, ‘653653653’, ‘888665555’, 4 );
  • 35. 36 Column that may be left out  null column may be left out.  column with default (but not declared as not null) may be left out.  not null column without default must be mentioned.
  • 36. 37 Failure of insert statement  Insert statement fails if one of the following constraints is violated  Domain constraint  Entity integrity constraint  Key constraint  Referential integrity constraint
  • 37. 38 Failure of insert statement Domain of a column is the set of all possible values that the column can assume. While entering data domain constraint is said to have been violated if an attempt is made to assign value to a column outside its domain. In this case the DBMS restricts the data entry and the insert statement fails. Entity integrity constraint (EIC) states that primary key value cannot be null. Any attempt to leave out the value in the primary key column (s) results in violation of EIC and in case of such violation DBMS restricts data entry and the insert statement fails.
  • 38. 39 Failure of insert statement Key constraint states that key value across rows of a table cannot have duplicate (e.g. you cannot enter duplicate values in the ssn column of department table). Any attempt to enter duplicate value in key (primary / secondary) is restricted by DBMS and data entry fails. Referential integrity constraint (RIC) states that a row can refer to an existing row only. RIC is specified using foreign key. Insert statement fails if RIC is violated.
  • 39. 40 Changing existing data (update statement) update employee set salary = 65000 where ssn = ‘888665555’; update employee set salary = salary + 5000 where dno = 5; update employee set dno = 5, salary = salary*1.2 where dno = 4; update employee set salary = null where ssn = ‘123456789’;
  • 40. 41 Update statement update employee set dno = default where ssn = ‘123456789’; update employee set salary = null, dno = default where ssn = ‘123456789’;
  • 41. 42 Update statement can update only one table An update statement can update only one table. One update statement cannot update multiple tables together. An update statement cannot update dnumber column of department and dno column of employee together. Syntax of update statement update <table_name> set <column_name> = <expression> [,<column_name = <expression>] [where <condition>]
  • 42. 43 Failure of update statement  Update statement fails if one of the following constraints is violated  Domain constraint  Entity integrity constraint  Key constraint  Referential integrity constraint
  • 43. Referential integrity constraint is violated whenever an attempt is made to delete a row from department table or update Dnumber column to any value other than 1, 5, 4.
  • 44. 45 Failure of update statement  To avoid violation of referential integrity constraint, when you define foreign key in the Employee table do one of the following.  alter table employee add foreign key(dno) references Department(dnumber) on update cascade  alter table employee add foreign key(dno) references Department(dnumber) on update set null  alter table employee add foreign key(dno) references Department(dnumber) on update set default
  • 45. Removing rows from table (delete statement) delete from employee where ssn = ‘888665555’; delete from employee where salary > 30000; delete from employee where salary > 30000 and dno = 4; delete from employee where salary between 30000 and 40000; delete from employee; One delete command can delete data from one table only. 46
  • 46. 47 Failure of delete statement  Delete statement fails if Referential integrity constraint is violated. To resolve this problem you do one of the following:  alter table Employee add foreign key(dno) references Department(dnumber) on delete cascade  alter table Employee add foreign key(dno) references Department(dnumber) on delete set null  alter table Employee add foreign key(dno) references Department(dnumber) on delete set default
  • 47. 48 You may combine actions on update with delete  alter table Employee add foreign key(dno) references Department(dnumber) on delete cascade on update cascade  And the likes
  • 48. 49 Select statement (Retrieving data from database) • Retrieves data from database • Can only read database, cannot modify it Examples of data retrieval  Reading balance in bank account  Viewing term end results  Viewing attendance status  Looking for availability of rail/flight ticket  Browsing through www.flipcart.com to find out the available books on database systems
  • 49. 50 Company database schema EMPLOYEE(Fname, Minit, Lname, Ssn, Bdate, Address, Gender, Salary, Super_ssn, Dno) DEPARTMENT(Dname, Dnumber, Mgr_ssn, Mgr_strat_date) PROJECT(Pname, Pnumber, Plocation, Dnum) DEPT_LOCATIONS(Dnumber, Dlocation) WORKS_ON(Essn, Pno, Hours) DEPENDENT(Essn, Dependent_name, Gender, Bdate, Relationship)
  • 50. 51 Select statement (Retrieving data) Retrieve all information of all projects. select * from project; Retrieve name of all projects and its location. select pname, plocation from project;
  • 51. 52 Select statement Find out the name of the employees, their address and salary. select fname, minit, lname, address, salary from employee;
  • 52. 53 Select statement (WHERE clause) Find out the last name & first name of the employees with salary higher than $40000. select lname, fname from employee where salary > 40000;
  • 53. 54 WHERE clause select lname, fname from employee where salary >= 30000 and salary <= 55000; select lname, fname from employee where salary between 30000 and 55000; <> or != Not equal to Find out the birth date and address of the employee (s) whose name is John B. Smith. Select bdate, address from employee where fname = ‘John’ and minit = ‘B’ and lname = ‘Smith’ Output of a query is displayed as a table.
  • 54. 55 Substring pattern matching using % (zero or more character) in WHERE clause Retrieve name of employees whose last name starts with an S. select fname, minit, lname from employee where lname like ‘S%’; (%  zero or more characters) Retrieve lname & fname of employees who live in Texas. select lname, fname from employee where address like ‘%TX%’;
  • 55. 56 Using _ (exactly one character) Retrieve first name and last name of employees whose first name has an o as the second character. select fname, lname from employee where fname like ‘_o%’; ( _  exactly one character) Retrieve the first name and last name of employees whose last name has an e as the fourth character. select fname, lname from employee where lname like ‘___e%’;
  • 56. 57 What if the string contains _ or % ? Find out first name and last name of employees with _ as one of the characters in their email address. select fname, lname from employee where email like ‘%_%’ escape ‘’;
  • 57. 58 What if the string contains _ or % ? Find out first name and last name of employees with % as one of the characters in their email address. select fname, lname from employee where email like ‘%%%’ escape ‘’; Any character that has not been used in the string may be used as escape character.
  • 58. 59 is null & is not null (Testing presence of data in a column) Tell me the name of the employee who do not have a supervisor. select fname, minit, lname from employee where super_ssn is null; Tell me the name of the employees who do not have email address. select fname, lname from employee where email is null;
  • 59. 60 is null & is not null Tell me the name of the employees who have email address but did not provide their mobile number. select fname, lname from employee where email is not null and mobile is null;
  • 60. 61 Eliminating duplicate rows from the output of a query Output of a select statement is a table. To eliminate duplicate rows use distinct clause. Show me the distinct salary values. select distinct salary from employee; Show me the supervisor`s ssn only. select distinct super_ssn from employee; Null is treated as different from any other values.
  • 61. 62 Arithmetic operators in query What would be the salary of the employees if they get a hike of 10%? select 1.1*salary from employee;
  • 62. 63 ORDER BY clause Sorts output of select statement. Default order ascending select fname, lname, salary from employee order by salary; select fname, lname from employee order by salary desc; select fname, lname, salary from employee order by fname, salary desc; select fname, lname from employee order by fname, lname, salary;
  • 63. 64 ORDER BY with WHERE clause select fname, lname, salary from employee where salary < 60000 order by salary desc;
  • 64. 65 Aggregate functions sum, avg, max, min, count are SQL aggregate functions Aggregate functions compute summary of data. sum (column header) computes total value in this column. You may also use distinct keyword before column header.
  • 65. Aggregate functions Similarly, avg, max, min computes the arithmetic mean, maximum and minimum respectively of a column. The count function computes number of values present in the column. In all these functions the column header can be preceded by keyword distinct. 66
  • 66. 67 Aggregate functions Sum and avg function can be applied on numeric data only, but count, max and min can be applied on numeric as well as alphanumeric data.
  • 67. 68 Aggregate functions Examples: select sum(salary) from employee; select avg(salary) from employee; select sum(salary), avg(salary), max(salary), min(salary), count(*) from employee; Find out the number of supervisors in the company.
  • 68. 69 Group by clause Group by clause is used when you want to apply aggregate function on groups of rows in a table. In these cases we need to partition the relation into non overlapping groups of rows. Each group (also called partition) will consist of the rows that have the same value of some column (s), called the grouping column (s). We can then apply the function to each such group independently to produce summary information about each group. If null value exists in the grouping column, then a separate group is created for all rows with a null value in the grouping column.
  • 69. 70 GROUP BY clause Tell me the average salary of each department and the number employees who work in the department.
  • 70. 71 How does GROUP BY work?
  • 71. 72 Using GROUP BY clause Tell me the number of projects each employee works on. Select count(pno) from works_on group by essn; Tell me the number of employees working in each project. Select count(essn) from works_on group by pno;
  • 72. 73 HAVING clause in select statement HAVING <condition> condition should be on an aggregate function and (or) grouping column. having avg(salary) > 30000; having salary > 30000; (incorrect) HAVING clause operates on summery data & grouping column (s).
  • 73. 74 HAVING with GROUP BY clause Tell me those departments that have average salary of employees higher than $40000; Select dno from employee group by dno having avg(salary) > 40000 Give me those project numbers that involve at least three employees. Select pno from works_on group by pno having count(essn) >= 3;
  • 74. 75 Format of select statement SELECT <list of columns, summary data> FROM <list of tables> WHERE <condition> GROUP BY <list of columns> HAVING <condition on summary data, grouping column> ORDER BY <list of columns, summary data>
  • 75. 76 Joining tables - Multiple tables in select statement Tell me the name of project & the name of controlling department.
  • 76. 77 Joining tables Consider two tables namely, PROJECT and DEPARTMENT. Now concatenate each row of PROJECT table with each row of DEPARTMENT table and by this process you get join of two tables. The output of this join is shown in the next slide, along with the query that produces this output.
  • 77. Output of select * from project, department; There are some rows that are invalid e.g. the second row which gives two different values of department number for the project ProductX, but a project is under the control of a single department. To avoid this, use join condition (Fkey = Pkey)
  • 78. 79 Joining tables - Multiple tables in select statement Retrieve the name of project and name of controlling department. select pname, dname from project , department where dnum = dnumber; Retrieve the name of employee and name of department he/she works. select fname, minit, lname, dname from employee, department where dno = dnumber; The above SQL statement may also be written as: select fname, minit, lname, dname from employee join department on dno = dnumber;
  • 79. 80 Joining tables - Multiple tables in select statement Find out first name, last name and address of all employees who work in administration department. select fname, lname, address from employee, department where dno = dnumber and dname = ‘Administration’; select fname, lname, address from employee join department on dno = dnumber and dname = ‘Administration’;
  • 80. 81 Join Retrieve name of project and name of controlling department select pname, dname from project, department where dnum = dnumber;
  • 81. 82 Join Tell me the first name, last name and address of employees who work in administration department select fname, lname, address from employee, department where dno = dnumber and dname = ‘Administration’;
  • 82. 83 Natural join If name of the foreign key is the same as that of primary key you may use natural join as illustrated in the following example. Find out name of department name and its location. Select dname, dlocation from department natural join dept_locations
  • 83. 84 Join Tell me the first name and last name of employees and the project number they are involved in. select fname, lname, pno from employee, works_on where essn = ssn; Tell me the first name and last name of employees and the name of the project (s) they are involved in. select fname, lname, pno from employee, works_on, project where essn = ssn and pno = pnumber;
  • 84. 85 Join For every project located in ‘Stafford’, list project number, controlling department number and the department manager’s last name. For the SQL query see the next slide.
  • 85. 86 Query select pnumber, dnum, lname from project, department, employee where dnum = dnumber and mgr_ssn = ssn and plocation = ‘Stafford’; select pnumber, dnum, lname from ((project join department on dnum = dnumber) join employee on mgr_ssn = ssn)) where plocation = ‘Stafford’; select pnumber, dnum, lname from project natural join department natural join employee where plocation = ‘Stafford’;
  • 86. 87 Self join For each employee, retrieve the employee’s first and the first name of his or her immediate supervisor. select e.fname, s.fname from employee e, employee s where e.super_ssn = s.ssn;
  • 87. 88 Set theoretic operations union, intersect, minus. You may combine the output of two or more queries using these set operations provided that the query outputs have the same schema. e.g. Find out name of employees who do not have dependent. (select fname, minit, lname from employee) minus (select fname, minit, lname from employee, dependent where essn = ssn);
  • 88. 89 Set theoretic operations Find out project number where Franklin Wong works either as a manager or as a worker. (Select pnumber from employee, department, project where mgr_ssn = ssn and dnum = dnumber and fname = ‘Franklin’ and lname = ‘Wong’) union (Select pno from employee, works_on where essn = ssn and fname = ‘Franklin’ and lname = ‘Wong’)
  • 89. 90 Union all, intersect all, minus all Union, intersect and minus eliminates duplicates (if any) before displaying the results of the query. If you need to retain duplicates then use union all, intersect all and minus all.
  • 90. 91 Nested queries  If there is a query inside another query then the SQL statement is called a nested query.  You may have any number of levels of nesting.  The general look of nested query is  Outer query (inner query);  Outer query (inner query1 (inner query2)); In the following nested query is illustrated with examples.
  • 91. 92 Nested queries Find out name of the department where John Smith works. select dname from department where dnumber = (select dno from employee where fname = ‘John’ and lname = ‘Smith’)
  • 92. 93 Nested queries  Retrieve the department name where last name of persons working in the department starts with an S. select dname from department where dnumber in (select dno from employee where lname like ‘S%’ );  Find out the name of the employee who draws the highest salary. select fname, minit, lname from employee where salary = (select max(salary) from employee)
  • 93. 94 Nested queries Retrieve the ssn of employees who work on the same project as Smith does. select distinct essn from works_on where pno in (select pno from works_on where essn = (select ssn from employee where lname =‘Smith’));
  • 94. 95 Uncorrelated & Correlated nested query When an inner query does not access the columns of the table used in outer query then the nested query is called uncorrelated nested query. But when an inner query accesses the columns of the table used in outer query then the nested query is called correlated nested query. Nested queries that you have seen so far are uncorrelated nested query.
  • 95. 96 Correlated nested query Retrieve the name of employees whose dependent has the same name as the last name of the employee. select fname, lname from employee where ssn in (select essn from dependent where dependent_name = lname);
  • 96. 97 Correlated nested query Retrieve the last name of employees who has a dependent with the same gender as that of the employee. select e.lname from employee e where e.ssn in (select essn from dependent where e.gender = gender);
  • 97. 98 Correlated nested query Retrieve the names of all employees who have two or more dependents. select lname, fname from employee where (select count(*) from dependent where essn = ssn) >= 2; N.B. The outer query is colored.
  • 98. 99 exists & not exists function exists and not exists functions are used in relation to nested query. Usage: (outer query) where exists (inner query); (outer query) where not exists (inner query);
  • 99. 100 exists & not exists function not exists (inner query) returns true if inner query does not return result, otherwise it returns false. exists (inner query) returns true if inner query returns one or more rows, otherwise it returns false.
  • 100. 101 not exists function - example Retrieve the name of employees who do not have dependent. select fname, lname from employee where not exists (select * from dependent where ssn = essn);
  • 101. 102 exists function - example Retrieve the name of employees who have at least one dependent. select fname, lname from employee where exists (select * from dependent where ssn = essn);
  • 102. 103 Correlated vs. uncorrelated nested queries In case of correlated nested query, the inner is executed once for every row of the table in the outer query whereas, in case of uncorrelated nested query, the inner query is executed only once, and the output of the inner query is used to evaluate outer query. How many times does the inner query execute in correlated nested query? How many times does the inner query execute in uncorrelated nested query?
  • 103. 104 Outer join • Left outer join • Right outer join • Full outer join Left outer join produces data from matching rows (for which foreign key = primary key) from the participating tables and data from non-matching rows from the left table. Right outer join behaves in a similar way. The full outer join is the union of left outer join and right outer join.
  • 104. 105 Outer join Display name of employees and their immediate supervisor without missing out employees who do not have supervisor. Select e.fname, e.lname, s.fname, s.lname from employee e left outer join employee s on e.super_ssn = s.ssn; The key word outer, in such queries, is optional.
  • 105. 106 Outer join Display name of all employees and their dependents without leaving out employees who did not register their dependent detail in the company database. Select fname, lname, dependent_name from employee left outer join dependent on essn = ssn;
  • 106. 107 Views A view is a perspective of a database. To create a view use create view view_name as <query>; To drop a view use drop view view_name;
  • 107. 108 Views Create view empdept as select fname, lname, salary, dname from employee, department where dno = dnumber;
  • 108. 109 Reference  Fundamentals of Database Systems, R. Elmasri & S.B. Navathe Pearson education, 2011.  Chapter 4 & 5 – Elmasri & Navathe, Sixth edition