SlideShare una empresa de Scribd logo
1 de 54
1 | P a g e
Submitted To:- Submitted By:-
Sir Arun Kumar Uttam Singh Chaudhary
(17EMBIT055)
2 | P a g e
Table of Contents
S.no Experiment Page no.
1 Database design using E-R model of
university
4
2 Database design using E-R model
National Hockey league
5-8
3 Introductionto PostGres SQL and its
installation.
9-17
4 Implementation of Data Definition
language (DML), Commands with
Examples
i. Create Database
ii. Select Database
iii. Delete Database
iv. Create Table
v. Delete Table
vi. Insertion Data into table, Etc.
18-23
5 Implement type of Constraintswith
Examples
(a) Primary key, (b) Foreign Key,
(c) Check, (d) Unique (e) Null
(f) Not null, (g) Default
24-28
6 Implementation on Data
Manipulation (DML) (Introductionto
29-32
3 | P a g e
SQL)
a. Select clause
b. From clause
c. Where clause
7 implementation on Data
Manipulation (DML)
a. Aggregation functions (Min,
Max, Sum, Avg, count)
b. Group by clause
c. Having
d. Rename operation (as)
33-36
8 Implementation on Data
Manipulation (DML), Set Operations
a. Union Operation
b. Intersect Operation
c. Except Operation
37-39
9 Implementation of Nested Queries 40-45
10 Create a Company Database and
Write SQL retrieval queries with
example.
46-54
4 | P a g e
Experiment:-1
Aim:-Design a ER diagram for the University
database
Fig :1
It describe different entities having relation with each other.
5 | P a g e
Experiment:-2
Aim:-Design a clean and clear ER diagram for the NHL
Database.
Fig:-2
It describes National hockey league database with different
entities having set of attributes with relationship among them.
6 | P a g e
Definitions:
1. Entity:- An entity can be any real world object that has an
independent existence.
E.g.:- person, place, object etc.
2. Attributes:- Attributes can be described as the properties of
entities.
Types of attributes:-
 Simple:- Attributes which can’t be broken into
smaller subparts.
E.g.:- Student Id.
Composite:- Attributes which can be broken down
into smaller parts.
E.g.:- Student Name.
 Single valued:-Attributes having only one value.
E.g.:- Student Age.
Multi-valued:- Attributes having more thanone value.
E.g.:-Student Mobile Number
 Stored:-Attribute which is already present as an
attribute for an entity.
7 | P a g e
E.g.;- Student college duration can be calculated using date of
joining. Here Date of joining is stored attribute.
Derived:- Attribute which is derived from stored attributes it
was not present as an attribute for an entity.
E.g.:- Student college duration is derived attribute.
 Null:-Attributes having null values.
E.g.:- Student Mobile Number may or may not have
null value.
3. Specialization:- It is a process of creating subclasses out of
given entity types.
4. Generalization:- It is a process in which two or more entity
types are taken and grouped under a common subclass. It
is a reverse process of specialization.
5. Relationship:- This shows relations between different
entities and hold together various component of ER model.
6. Keys:- Keys are the attributes used to distinguish one entity
from another in entity set.
8 | P a g e
TYPES OF KEYS:-
 Super key:- It is a set of key having one or more
attribute that can uniquely identify entity in a entity
set.
 Candidate Key:- Least combination of attributes that
can uniquely identify an entity set. It could be subset
of super key.
 Primary Key:- It is the candidate key which is most
appropriate key for the table. It is decided by the
administrator.
 Foreign Key:- It is generally a primary key that serve
as a field to another field in the same database.
 Simple Key:- It is a key having single attribute.
 Composite key:-It is a key which is not simple key but
having more than one attribute.
 Compound Key:- It is key which is not composite key.
 Alternate Key:-It is term used for candidate key
which is chosen after choosing a primary key by
database designer.
9 | P a g e
Experiment 3
Aim: Introduction to PostGreSQL and its installation.
SQL is also called SE-QU-EL. It has got some historical
significance - the initial name of SQL
was Simple English Query Language.
You will be using PostgreSQL as the relational database
management system. PostgreSQL is very light-weight,
and it is free as well.
What is PostgreSQL?
PostgreSQL is a powerful, open source object-relational
database system that uses and extends the SQL language
combined with many features that safely store and scale
the most complicated data workloads.
PostgrSQL has earned a strong reputation for its proven
architecture, reliability, data integrity, robust feature set,
extensibility, and the dedication of the open source
community behind the software to consistently deliver
performing and innovative solutions.
10 | P a g e
PostgreSQL runs on all major operating systems, has
been ACID-compliant since 2001, and has powerful add-
ons such as the popular PostGRES geospatial database
extender. It is no surprise that PostgreSQL has become
the open source relational database of choice for many
people and organizations .
Install PostgreSQL step by step
Start Installing PostgreSQL
Specify installation folder, choose your own or keep the
default folder suggested by PostgreSQL installer.
11 | P a g e
Enterthe password for the database super user and service
account.
Enter the port for PostgreSQL. Make sure that no other
applications are using this port. Leave it as default if you
are unsure.
12 | P a g e
Choose the default locale used by the database.
13 | P a g e
You’ve completed providing information for the
PostgreSQL installer. Click the Next button to install
PostgreSQL
14 | P a g e
The installation may take few minutes to complete.
15 | P a g e
Click the Finish button to complete the PostgreSQL
installation.
Verify the Installation
There are several ways to verify the installation. You can
try to connect to the PostgreSQL database server from
any client application e.g., psql and pgAdmin.
The quick way to verify the installation is through
the pgAdmin application.
16 | P a g e
First, click on pgAdmin III to launch it. The pgAdmin III
GUI will display.
Second, double-click PostgreSQL 9.5 on the object
browser. It will ask you for the admin password. Just
enter the password you’ve used in the installation step.
17 | P a g e
Third, if everything is fine, the pgAdmin will display all
the objects that belong to the server.
Congratulation!you’ve successfully installed PostgreSQL
database server on your local system.
18 | P a g e
Experiment:-4
Aim:-Implementation of Data Definition language
(DML), Commands with Examples
i. Create Database
ii. Select Database
iii. Delete Database
iv. Create Table
v. Delete Table
vi. Insertion Data into table, Etc.
DDL- Data Definition Language (DDL) statements are
used to define the database structure or schema.
DDL uses different statements :
CREATE - to create objects in the database
ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all records from a table, including
all spaces allocated for the records are removed
19 | P a g e
COMMENT - add comments to the data dictionary
RENAME - rename an object
CREATE TABLE
Syntax: Create table tablename( fieldname1
datatype(),fieldname2 datatype()...);
ALTER TABLE
1. ADD
2.MODIFY
ADD
Syntax:alter table table name ADD (fieldname
datatype()...);
modify
syntax: Alter table table name modify (fieldname
datatype()...);
DESCRIBE TABLE
Syntax: DESCRIBE TABLE NAME;
DROP TABLE
Syntax: DROP Table name;
20 | P a g e
COMMENT - add comments to the data dictionary
RENAME - rename a table
Synatax: rename table table name to new table name
Examples : In this example we creates a table and insert
the values.
21 | P a g e
Example : In the following figure shows the alter a table .
For Example : In this figure shows the describe
command.
22 | P a g e
DML- Data Manipulation Language (DML) statements
are used for managing data within schema objects DML
deals with data manipulation, and therefore includes most
common SQL statements such SELECT, INSERT, etc.
DML allows to add / modify / delete data itself.
DML is used to manipulate with the existing data in the
database objects (insert, select, update, delete).
DML Commands:
1.INSERT
2.SELECT
3.UPDATE
4.DELETE
*INSERT:
Syntax: INSERT INTO Table name values();
*SELECT:
Syntax: Select*from <table name>
*UPDATE:
Syntax: Update<table name> set to(calculation);
*DELETE:
Syntax: Delete form<table name>
23 | P a g e
Example : In the below figure shows the update and
delete command on the given table.
24 | P a g e
Experiment :-5
Aim:-Implement type of constraints with examples
(a) Primary key
(b) Foreign key
(c) Check
(d) Unique
(e) Null
(f) Not null
(g) Default
Primary Keys:
Primary key uniquely identifies each record in a table. It
must have unique values and cannot contain nulls. In the
below example the ROLL_NO field is marked as primary
key, that means the ROLL_NO field cannot have
duplicate and null values.
25 | P a g e
CREATE TABLE STUDENT(
ROLL_NO INT NOT NULL,
STU_NAME VARCHAR (35) NOT NULL UNIQUE,
STU_AGE INT NOT NULL,
STU_ADDRESS VARCHAR (35) UNIQUE,
PRIMARY KEY (ROLL_NO)
);
Foreign keys: are the columns of a tablethat points to the
primary key of another table. They act as a cross-
reference between tables.
This constraint is used for specifying range of values for a
particular column of a table. When this constraint is being
set on a column, it ensures that the specified column must
have the value falling in the specified range.
CREATE TABLE STUDENT(
ROLL_NO INT NOT NULL CHECK(ROLL_NO
>1000) ,
STU_NAME VARCHAR (35) NOT NULL,
26 | P a g e
STU_AGE INT NOT NULL,
EXAM_FEE INT DEFAULT 10000,
STU_ADDRESS VARCHAR (35) ,
PRIMARY KEY (ROLL_NO)
);
In the above example we have set the check constraint on
ROLL_NO column of STUDENT table. Now, the
ROLL_NO field must have the value greater than 1000.
UNIQUE Constraint:enforces a column or set of columns
to have unique values. If a column has a unique
constraint, it means that particular column cannot have
duplicate values in a table.
CREATE TABLE STUDENT(
ROLL_NO INT NOT NULL,
STU_NAME VARCHAR (35) NOT NULL UNIQUE,
STU_AGE INT NOT NULL,
STU_ADDRESS VARCHAR (35) UNIQUE,
PRIMARY KEY (ROLL_NO)
27 | P a g e
);
NOT NULL: constraint makes sure that a column does
not hold NULL value. When we don’t provide value for a
particular column while inserting a record into a table, it
takes NULL value by default. By specifying NULL
constraint, we can be sure that a particular column(s)
cannot have NULL values.
Example:
CREATE TABLE STUDENT(
ROLL_NO INT NOT NULL,
STU_NAME VARCHAR (35) NOT NULL,
STU_AGE INT NOT NULL,
STU_ADDRESS VARCHAR (235),
PRIMARY KEY (ROLL_NO)
);
28 | P a g e
The DEFAULT: constraint provides a default value to a
column when there is no value provided while inserting a
record into a table.
Example:-
CREATE TABLE STUDENT(
ROLL_NO INT NOT NULL,
STU_NAME VARCHAR (35) NOT NULL,
STU_AGE INT NOT NULL,
EXAM_FEE INT DEFAULT 10000,
STU_ADDRESS VARCHAR (35) ,
PRIMARY KEY (ROLL_NO)
);
29 | P a g e
Experiment:-6.
Aim:-Explain Data ManipulationLanguage(DML)
with examples in DBMS.
Data manipulation language (DML) can be defined as a
set of syntax elements that are used to manage the data in
the database. The commands of DML are not auto
committed and modification made by them are not
permanent to the database. It is a computer programming
language that is used to perform select, insert delete and
updatedata in a database.Theuser requests are assisted by
data manipulation language. This language is responsible
for all forms of data modification in a database.
Types of Data Manipulation Languages.
1.Procedural programming
In this type the user will specify what data is required
and how to get it.
2 Declarative programming
Here, the user will only specify what data is required
30 | P a g e
Commands
The DML section of SQL consists of following a set of
commands.
 Select/From/Where
 Insertinto/values
 Update/set/where
 Delete/from/where
The database programmers and users are allowed by this
basic to enter the data and information into the database
and then retrieve it by the use of several numbers of filter
option.
 Select/from/where
 Select
It is one of the basic query commands available in SQL
and works in the same way as the projection operation of
relational algebra. The attributes are selected by this
command on the basis of the condition defined by the
where clause.
 From
A relation name is taken by this clause as an argument
from where attributed are to be projected or selected.
31 | P a g e
 Where
The predictions or conditions that should match for
qualifying the attributed to be projected are defined by
this clause.
For example
Select author_name
From book-set
Where age>40
The name of the authors will be yield by the command
from the relation book set whose age is greater than 40.
e.g.
SQL> select*from student
32 | P a g e
OUTPUT:-
ROLL NO. NAME MARKS ADDR
101 ABC 75 LINK ROAD
102 XYZ 80 JM ROAD
103 PQR 87 N7
SQL>select *from student where marks=80
ROLL NO. NAME MARKS ADDR
102 XYZ 80 JM ROAD
33 | P a g e
Experiment:7
Aim:- Implementationof Aggregate Functions
These functions operate on the multiset of values of a
column of a relation, and return a value
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values
Q.1 Find the avg salary of employee from employee table
Ans:- Select avg(salary)
From employee
Q.2 Find the no. of employee who worksin dept-no.2
Ans:- Select count(*)
From employee
Where dept-no.2
34 | P a g e
Q.3 Find the no. of cities where dept present
Ans:-Select count(distinct(city))
From department
Q.4 Give the age of oldest employee
Ans:-Select max(age)
From employee
Q.5 Find the mini. Age of employee whose salary is
greater than 50K
Ans:- Select min(age)
From employee
Where salary>50K
Q.6 Find the total salary of all employees
Ans:- Select sum(salary)
From employee
35 | P a g e
Aggregate Functions –Group By
Find the average salary of instructors in each department
 select dept_name, avg(salary) as avg_salary
from instructor
group by dept_name;
Attributes in select clause outside of aggregate functions
must appear in group bylist
/* erroneous query */
select dept_name, ID, avg(salary)
from instructor
group by dept_name;
Aggregate Functions –Having Clause
Find the names and average salaries of all departments
whose average salary is greater than 42000
36 | P a g e
 select dept_name, avg(salary)
from instructor
group by dept_name
having avg(salary) > 42000;
Note: predicates in the havingclause are applied after the
formation of groups whereas predicates in the where
clause are applied before forming groups
RENAME OPERATOR:-
Employee(employee_name,e_id,age,salary)
Q. Find the name of employee whose salary is greater
than 20K
Select employee_name as name
From employee
Where salary>20K
37 | P a g e
Experiment:-8
Aim:-Implementation of Set operations on Data
manipulation language
Set Operations:-
Find courses that ran in Fall 2009 or in Spring 2010
(selectcourse_idfrom section where sem= ‘Fall’ and year
= 2009)
 Union
(selectcourse_idfrom section where sem= ‘Spring’ and
year = 2010)
Find courses that ran in Fall 2009 but not in Spring 2010
(selectcourse_idfrom section where sem= ‘Fall’ and year
= 2009)
 Intersect
(selectcourse_idfrom section where sem= ‘Spring’ and
year = 2010)
38 | P a g e
Find courses that ran in Fall 2009 and in Spring 2010
(selectcourse_idfrom section where sem= ‘Fall’ and year
= 2009)
 Except
(selectcourse_idfrom section where sem= ‘Spring’ and
year = 2010)
1.Find the salaries of all instructors that are less than the
largest salary
select distinct T.salary
from instructor as T, instructor as S
where T.salary< S.salary
2.Find all the salaries of all instructors
select distinct salary
from instructor
39 | P a g e
3.Find the largest salary of all instructors
(select“second query” )
Except
(select“first query”)
Set operations union, intersect, and except
Each of the above operations automatically eliminates
duplicates
To retain all duplicates use the corresponding multiset
versions union all, intersect alland except all.
Suppose a tuple occurs mtimes in rand n times in s, then,
it occurs:
m + n times in r union all s
min(m,n)times in rintersect all s
max(0, m –n)times in rexcept all s
40 | P a g e
EXPERIMENT-9
Aim:-IMPLEMENTATION OF NESTED QUERIES
In nested queries, a query is written inside a query. The
result of inner query is used in execution of outer query.
We will use STUDENT, COURSE,
STUDENT_COURSEtablesfor understandingnested
queries.
STUDENT
S_ID S_NAME S_ADDRESS S_PHONE S_AGE
S1 RAM DELHI 9455123451 18
S2 RAMESH GURGAON 9652431543 18
S3 SUJIT ROHTAK 9156253131 20
S4 SURESH DELHI 9156768971 18
41 | P a g e
COURSE
C_ID C_NAME
C1 DSA
C2 Programming
C3 DBMS
STUDENT_COURSE
S_ID C_ID
S1 C1
S1 C3
S2 C1
S3 C2
S4 C2
S4 C3
42 | P a g e
There are mainly two types of nested queries:
 Independent Nested Queries: In independent nested
queries, query execution starts from innermost query
to outermost queries. The execution of inner query is
independent of outer query, but the result of inner
query is used in execution of outer query. Various
operators like IN, NOT IN, ANY, ALL etc are used in
writing independent nested queries.
IN: If we want to find out S_ID who are enrolled
in C_NAME ‘DSA’ or ‘DBMS’, we can write it with
the help of independent nested query and IN operator.
From COURSE table, we can find
out C_ID for C_NAME ‘DSA’ or DBMS’ and we can
use these C_IDs for finding S_IDs
from STUDENT_COURSE TABLE.
STEP1: Finding C_ID for C_NAME =’DSA’or
‘DBMS’
Select C_ID from COURSE where C_NAME = ‘DSA’
or C_NAME = ‘DBMS’
43 | P a g e
STEP 2: Using C_ID of step 1 for finding S_ID
Select S_ID from STUDENT_COURSEwhere C_ID IN
(SELECT C_ID from COURSE where C_NAME =
‘DSA’ or C_NAME=’DBMS’);
STEP 3: Using C_ID of step 1 for finding S_ID
Select S_ID from STUDENT_COURSEwhere C_ID IN
(SELECT C_ID from COURSE where C_NAME =
‘DSA’ or C_NAME=’DBMS’);
The inner query will return a set with members C1 and C3
and outer query will return those S_IDs for
which C_ID is equal to any member of set (C1 and C3 in
this case). So, it will return S1, S2 and S4.
Note: If we want to find out names of STUDENTs
who have either enrolledin ‘DSA’ or ‘DBMS’, it can
be done as:
44 | P a g e
Select S_NAME from STUDENT where S_ID IN
(Select S_ID from STUDENT_COURSE
where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA
’ or C_NAME=’DBMS’));
NOT IN: If we want to find out S_IDs
of STUDENTs who have neither enrolled in ‘DSA’
nor in ‘DBMS’, it can be done as:
Select S_ID from STUDENT where S_ID NOT IN
(Select S_ID from STUDENT_COURSE
where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’
DSA’ or C_NAME=’DBMS’));
The innermost query will return a set with members C1
and C3. Second inner query will return those S_IDs for
which C_ID is equal to any member of set (C1 and C3 in
this case) which are S1, S2 and S4. The outermost query
will return those S_IDs where S_ID is not a member of
set (S1, S2 and S4). So it will return S3.
45 | P a g e
 Co-related Nested Queries: In co-related nested
queries, the output of inner query dependson the row
which is being currentlyexecuted in outer query. e.g.;
If we want to find out S_NAME of STUDENTswho
are enrolled in C_ID ‘C1’, it can be done with the
help of co-related nested query as:
Select S_NAME from STUDENT S where EXISTS
( select * from STUDENT_COURSE SC where
S.S_ID=SC.S_ID and SC.C_ID=’C1’).
For each row of STUDENT S, it will find the rows
from
STUDENT_COURSE
where S.S_ID = SC.S_ID and SC.C_ID=’C1’.
If for a S_ID from STUDENT S, atleast a row exists
in STUDENT_COURSE SC with C_ID=’C1’, then
inner query will return true and
corresponding S_ID will be returned as output.
46 | P a g e
Experiment:-10
Aim:-Create a company database and Write SQL
Retrieval Queries with example
CREATE TABLE employee (
emp_idINT PRIMARY KEY,
first_nameVARCHAR(40),
last_nameVARCHAR(40),
birth_dayDATE,
sexVARCHAR(1),
salaryINT,
super_idINT,
branch_idINT
);
CREATE TABLE branch (
branch_idINT PRIMARY KEY,
branch_nameVARCHAR(40),
mgr_idINT,
mgr_start_dateDATE,
47 | P a g e
FOREIGN KEY(mgr_id) REFERENCES
employee(emp_id) ONDELETESETNULL
);
ALTERTABLE employee
ADD FOREIGN KEY(branch_id)
REFERENCESbranch(branch_id)
ONDELETESETNULL;
ALTERTABLE employee
ADD FOREIGN KEY(super_id)
REFERENCESemployee(emp_id)
ONDELETESETNULL;
CREATETABLEclient (
client_idINT PRIMARY KEY,
client_nameVARCHAR(40),
branch_idINT,
48 | P a g e
FOREIGN KEY(branch_id) REFERENCES
branch(branch_id) ONDELETESETNULL
);
CREATETABLEworks_with (
emp_idINT,
client_idINT,
total_salesINT,
PRIMARY KEY(emp_id, client_id),
FOREIGN KEY(emp_id) REFERENCES
employee(emp_id) ONDELETECASCADE,
FOREIGN KEY(client_id)
REFERENCESclient(client_id) ONDELETECASCADE
);
CREATETABLEbranch_supplier(
branch_idINT,
supplier_nameVARCHAR(40),
supply_typeVARCHAR(40),
49 | P a g e
PRIMARY KEY(branch_id,supplier_name),
FOREIGN KEY(branch_id) REFERENCES
branch(branch_id) ONDELETECASCADE
);
-- -------------------------------------------------------------------
----------
Corporate
INSERTINTO employee VALUES(100, 'David',
'Wallace', '1967-11-17', 'M', 250000, NULL, NULL);
INSERTINTO branch VALUES(1, 'Corporate', 100,
'2006-02-09');
UPDATE employee
SETbranch_id = 1
WHEREemp_id = 100;
50 | P a g e
INSERTINTO employee VALUES(101, 'Jan', 'Levinson',
'1961-05-11', 'F', 110000, 100, 1);
-- Scranton
INSERTINTO employee VALUES(102, 'Michael', 'Scott',
'1964-03-15', 'M', 75000, 100, NULL);
INSERTINTO branch VALUES(2, 'Scranton', 102, '1992-
04-06');
UPDATE employee
SETbranch_id = 2
WHEREemp_id = 102;
INSERTINTO employee VALUES(103, 'Angela',
'Martin', '1971-06-25', 'F', 63000, 102, 2);
INSERTINTO employee VALUES(104, 'Kelly', 'Kapoor',
'1980-02-05', 'F', 55000, 102, 2);
51 | P a g e
INSERTINTO employee VALUES(105, 'Stanley',
'Hudson', '1958-02-19', 'M', 69000, 102, 2);
-- Stamford
INSERTINTO employee VALUES(106, 'Josh', 'Porter',
'1969-09-05', 'M', 78000, 100, NULL);
INSERTINTO branch VALUES(3, 'Stamford', 106,
'1998-02-13');
UPDATE employee
SETbranch_id = 3
WHEREemp_id = 106;
INSERTINTO employee VALUES(107, 'Andy',
'Bernard', '1973-07-22', 'M', 65000, 106, 3);
INSERTINTO employee VALUES(108, 'Jim', 'Halpert',
'1978-10-01', 'M', 71000, 106, 3);
52 | P a g e
-- BRANCH SUPPLIER
INSERTINTObranch_supplierVALUES(2, 'Hammer
Mill', 'Paper');
INSERTINTObranch_supplierVALUES(2, 'Uni-ball',
'Writing Utensils');
INSERTINTObranch_supplierVALUES(3, 'Patriot
Paper', 'Paper');
INSERTINTObranch_supplierVALUES(2, 'J.T. Forms &
Labels', 'Custom Forms');
INSERTINTObranch_supplierVALUES(3, 'Uni-ball',
'Writing Utensils');
INSERTINTObranch_supplierVALUES(3, 'Hammer
Mill', 'Paper');
INSERTINTObranch_supplierVALUES(3, 'Stamford
Lables', 'Custom Forms');
53 | P a g e
-- CLIENT
INSERTINTOclientVALUES(400, 'Dunmore
Highschool', 2);
INSERTINTOclientVALUES(401, 'Lackawana Country',
2);
INSERTINTOclientVALUES(402, 'FedEx', 3);
INSERTINTOclientVALUES(403, 'John Daly Law,
LLC', 3);
INSERTINTOclientVALUES(404, 'Scranton
Whitepages', 2);
INSERTINTOclientVALUES(405, 'Times Newspaper',
3);
INSERTINTOclientVALUES(406, 'FedEx', 2);
54 | P a g e
-- WORKS_WITH
INSERTINTOworks_withVALUES(105, 400, 55000);
INSERTINTOworks_withVALUES(102, 401, 267000);
INSERTINTOworks_withVALUES(108, 402, 22500);
INSERTINTOworks_withVALUES(107, 403, 5000);
INSERTINTOworks_withVALUES(108, 403, 12000);
INSERTINTOworks_withVALUES(105, 404, 33000);
INSERTINTOworks_withVALUES(107, 405, 26000);
INSERTINTOworks_withVALUES(102, 406, 15000);
INSERTINTOworks_withVALUES(105, 406, 130000);

Más contenido relacionado

La actualidad más candente

class and objects
class and objectsclass and objects
class and objects
Payel Guria
 
Conversion from infix to prefix using stack
Conversion from infix to prefix using stackConversion from infix to prefix using stack
Conversion from infix to prefix using stack
Haqnawaz Ch
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
Tareq Hasan
 
ER DIAGRAM TO RELATIONAL SCHEMA MAPPING
ER DIAGRAM TO RELATIONAL SCHEMA MAPPING ER DIAGRAM TO RELATIONAL SCHEMA MAPPING
ER DIAGRAM TO RELATIONAL SCHEMA MAPPING
ARADHYAYANA
 

La actualidad más candente (20)

class and objects
class and objectsclass and objects
class and objects
 
Functional dependency
Functional dependencyFunctional dependency
Functional dependency
 
Data structures
Data structuresData structures
Data structures
 
Data structures using c
Data structures using cData structures using c
Data structures using c
 
Packages - PL/SQL
Packages - PL/SQLPackages - PL/SQL
Packages - PL/SQL
 
Relational algebra ppt
Relational algebra pptRelational algebra ppt
Relational algebra ppt
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File
 
Sql operators & functions 3
Sql operators & functions 3Sql operators & functions 3
Sql operators & functions 3
 
single linked list
single linked listsingle linked list
single linked list
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
Linked list
Linked listLinked list
Linked list
 
Conversion from infix to prefix using stack
Conversion from infix to prefix using stackConversion from infix to prefix using stack
Conversion from infix to prefix using stack
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Advanced Database Management Systems Project Report
Advanced Database Management Systems Project ReportAdvanced Database Management Systems Project Report
Advanced Database Management Systems Project Report
 
ER DIAGRAM TO RELATIONAL SCHEMA MAPPING
ER DIAGRAM TO RELATIONAL SCHEMA MAPPING ER DIAGRAM TO RELATIONAL SCHEMA MAPPING
ER DIAGRAM TO RELATIONAL SCHEMA MAPPING
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
 

Similar a DataBase Management System Lab File

PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12
Andrew Dunstan
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core Module
Katie Gulley
 

Similar a DataBase Management System Lab File (20)

PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core Module
 
Postgres в основе вашего дата-центра, Bruce Momjian (EnterpriseDB)
Postgres в основе вашего дата-центра, Bruce Momjian (EnterpriseDB)Postgres в основе вашего дата-центра, Bruce Momjian (EnterpriseDB)
Postgres в основе вашего дата-центра, Bruce Momjian (EnterpriseDB)
 
R programming for data science
R programming for data scienceR programming for data science
R programming for data science
 
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdfDBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
 
Making Postgres Central in Your Data Center
Making Postgres Central in Your Data CenterMaking Postgres Central in Your Data Center
Making Postgres Central in Your Data Center
 
Data Exploration in R.pptx
Data Exploration in R.pptxData Exploration in R.pptx
Data Exploration in R.pptx
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
SQLMAP Tool Usage - A Heads Up
SQLMAP Tool Usage - A  Heads UpSQLMAP Tool Usage - A  Heads Up
SQLMAP Tool Usage - A Heads Up
 
PL/SQL New and Advanced Features for Extreme Performance
PL/SQL New and Advanced Features for Extreme PerformancePL/SQL New and Advanced Features for Extreme Performance
PL/SQL New and Advanced Features for Extreme Performance
 
Complete+dbt+Bootcamp+slides-plus examples
Complete+dbt+Bootcamp+slides-plus examplesComplete+dbt+Bootcamp+slides-plus examples
Complete+dbt+Bootcamp+slides-plus examples
 
Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...
Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...
Engineering Student MuleSoft Meetup#6 - Basic Understanding of DataWeave With...
 
Boost Your Neo4j with User-Defined Procedures
Boost Your Neo4j with User-Defined ProceduresBoost Your Neo4j with User-Defined Procedures
Boost Your Neo4j with User-Defined Procedures
 
Pig latin
Pig latinPig latin
Pig latin
 
PPT on Data Science Using Python
PPT on Data Science Using PythonPPT on Data Science Using Python
PPT on Data Science Using Python
 
Getting Started with PostGIS geographic database - Lasma Sietinsone, EDINA
Getting Started with PostGIS geographic database - Lasma Sietinsone, EDINAGetting Started with PostGIS geographic database - Lasma Sietinsone, EDINA
Getting Started with PostGIS geographic database - Lasma Sietinsone, EDINA
 
Getting started with PostGIS geographic database
Getting started with PostGIS geographic databaseGetting started with PostGIS geographic database
Getting started with PostGIS geographic database
 
SQL Server 2008 Performance Enhancements
SQL Server 2008 Performance EnhancementsSQL Server 2008 Performance Enhancements
SQL Server 2008 Performance Enhancements
 
Tactical data engineering
Tactical data engineeringTactical data engineering
Tactical data engineering
 

Más de Uttam Singh Chaudhary

Más de Uttam Singh Chaudhary (6)

Big Data Analytics Lab File
Big Data Analytics Lab FileBig Data Analytics Lab File
Big Data Analytics Lab File
 
5 Pen PC Technology
5 Pen PC Technology5 Pen PC Technology
5 Pen PC Technology
 
Data Communication and Networking(DCACN)
Data Communication and Networking(DCACN)Data Communication and Networking(DCACN)
Data Communication and Networking(DCACN)
 
Traffic woes in India
Traffic woes in IndiaTraffic woes in India
Traffic woes in India
 
Software Requirement Specification Of Hotel Management System
Software Requirement Specification Of Hotel Management SystemSoftware Requirement Specification Of Hotel Management System
Software Requirement Specification Of Hotel Management System
 
Network Topologies
Network TopologiesNetwork Topologies
Network Topologies
 

Último

Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 

Último (20)

Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 

DataBase Management System Lab File

  • 1. 1 | P a g e Submitted To:- Submitted By:- Sir Arun Kumar Uttam Singh Chaudhary (17EMBIT055)
  • 2. 2 | P a g e Table of Contents S.no Experiment Page no. 1 Database design using E-R model of university 4 2 Database design using E-R model National Hockey league 5-8 3 Introductionto PostGres SQL and its installation. 9-17 4 Implementation of Data Definition language (DML), Commands with Examples i. Create Database ii. Select Database iii. Delete Database iv. Create Table v. Delete Table vi. Insertion Data into table, Etc. 18-23 5 Implement type of Constraintswith Examples (a) Primary key, (b) Foreign Key, (c) Check, (d) Unique (e) Null (f) Not null, (g) Default 24-28 6 Implementation on Data Manipulation (DML) (Introductionto 29-32
  • 3. 3 | P a g e SQL) a. Select clause b. From clause c. Where clause 7 implementation on Data Manipulation (DML) a. Aggregation functions (Min, Max, Sum, Avg, count) b. Group by clause c. Having d. Rename operation (as) 33-36 8 Implementation on Data Manipulation (DML), Set Operations a. Union Operation b. Intersect Operation c. Except Operation 37-39 9 Implementation of Nested Queries 40-45 10 Create a Company Database and Write SQL retrieval queries with example. 46-54
  • 4. 4 | P a g e Experiment:-1 Aim:-Design a ER diagram for the University database Fig :1 It describe different entities having relation with each other.
  • 5. 5 | P a g e Experiment:-2 Aim:-Design a clean and clear ER diagram for the NHL Database. Fig:-2 It describes National hockey league database with different entities having set of attributes with relationship among them.
  • 6. 6 | P a g e Definitions: 1. Entity:- An entity can be any real world object that has an independent existence. E.g.:- person, place, object etc. 2. Attributes:- Attributes can be described as the properties of entities. Types of attributes:-  Simple:- Attributes which can’t be broken into smaller subparts. E.g.:- Student Id. Composite:- Attributes which can be broken down into smaller parts. E.g.:- Student Name.  Single valued:-Attributes having only one value. E.g.:- Student Age. Multi-valued:- Attributes having more thanone value. E.g.:-Student Mobile Number  Stored:-Attribute which is already present as an attribute for an entity.
  • 7. 7 | P a g e E.g.;- Student college duration can be calculated using date of joining. Here Date of joining is stored attribute. Derived:- Attribute which is derived from stored attributes it was not present as an attribute for an entity. E.g.:- Student college duration is derived attribute.  Null:-Attributes having null values. E.g.:- Student Mobile Number may or may not have null value. 3. Specialization:- It is a process of creating subclasses out of given entity types. 4. Generalization:- It is a process in which two or more entity types are taken and grouped under a common subclass. It is a reverse process of specialization. 5. Relationship:- This shows relations between different entities and hold together various component of ER model. 6. Keys:- Keys are the attributes used to distinguish one entity from another in entity set.
  • 8. 8 | P a g e TYPES OF KEYS:-  Super key:- It is a set of key having one or more attribute that can uniquely identify entity in a entity set.  Candidate Key:- Least combination of attributes that can uniquely identify an entity set. It could be subset of super key.  Primary Key:- It is the candidate key which is most appropriate key for the table. It is decided by the administrator.  Foreign Key:- It is generally a primary key that serve as a field to another field in the same database.  Simple Key:- It is a key having single attribute.  Composite key:-It is a key which is not simple key but having more than one attribute.  Compound Key:- It is key which is not composite key.  Alternate Key:-It is term used for candidate key which is chosen after choosing a primary key by database designer.
  • 9. 9 | P a g e Experiment 3 Aim: Introduction to PostGreSQL and its installation. SQL is also called SE-QU-EL. It has got some historical significance - the initial name of SQL was Simple English Query Language. You will be using PostgreSQL as the relational database management system. PostgreSQL is very light-weight, and it is free as well. What is PostgreSQL? PostgreSQL is a powerful, open source object-relational database system that uses and extends the SQL language combined with many features that safely store and scale the most complicated data workloads. PostgrSQL has earned a strong reputation for its proven architecture, reliability, data integrity, robust feature set, extensibility, and the dedication of the open source community behind the software to consistently deliver performing and innovative solutions.
  • 10. 10 | P a g e PostgreSQL runs on all major operating systems, has been ACID-compliant since 2001, and has powerful add- ons such as the popular PostGRES geospatial database extender. It is no surprise that PostgreSQL has become the open source relational database of choice for many people and organizations . Install PostgreSQL step by step Start Installing PostgreSQL Specify installation folder, choose your own or keep the default folder suggested by PostgreSQL installer.
  • 11. 11 | P a g e Enterthe password for the database super user and service account. Enter the port for PostgreSQL. Make sure that no other applications are using this port. Leave it as default if you are unsure.
  • 12. 12 | P a g e Choose the default locale used by the database.
  • 13. 13 | P a g e You’ve completed providing information for the PostgreSQL installer. Click the Next button to install PostgreSQL
  • 14. 14 | P a g e The installation may take few minutes to complete.
  • 15. 15 | P a g e Click the Finish button to complete the PostgreSQL installation. Verify the Installation There are several ways to verify the installation. You can try to connect to the PostgreSQL database server from any client application e.g., psql and pgAdmin. The quick way to verify the installation is through the pgAdmin application.
  • 16. 16 | P a g e First, click on pgAdmin III to launch it. The pgAdmin III GUI will display. Second, double-click PostgreSQL 9.5 on the object browser. It will ask you for the admin password. Just enter the password you’ve used in the installation step.
  • 17. 17 | P a g e Third, if everything is fine, the pgAdmin will display all the objects that belong to the server. Congratulation!you’ve successfully installed PostgreSQL database server on your local system.
  • 18. 18 | P a g e Experiment:-4 Aim:-Implementation of Data Definition language (DML), Commands with Examples i. Create Database ii. Select Database iii. Delete Database iv. Create Table v. Delete Table vi. Insertion Data into table, Etc. DDL- Data Definition Language (DDL) statements are used to define the database structure or schema. DDL uses different statements : CREATE - to create objects in the database ALTER - alters the structure of the database DROP - delete objects from the database TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
  • 19. 19 | P a g e COMMENT - add comments to the data dictionary RENAME - rename an object CREATE TABLE Syntax: Create table tablename( fieldname1 datatype(),fieldname2 datatype()...); ALTER TABLE 1. ADD 2.MODIFY ADD Syntax:alter table table name ADD (fieldname datatype()...); modify syntax: Alter table table name modify (fieldname datatype()...); DESCRIBE TABLE Syntax: DESCRIBE TABLE NAME; DROP TABLE Syntax: DROP Table name;
  • 20. 20 | P a g e COMMENT - add comments to the data dictionary RENAME - rename a table Synatax: rename table table name to new table name Examples : In this example we creates a table and insert the values.
  • 21. 21 | P a g e Example : In the following figure shows the alter a table . For Example : In this figure shows the describe command.
  • 22. 22 | P a g e DML- Data Manipulation Language (DML) statements are used for managing data within schema objects DML deals with data manipulation, and therefore includes most common SQL statements such SELECT, INSERT, etc. DML allows to add / modify / delete data itself. DML is used to manipulate with the existing data in the database objects (insert, select, update, delete). DML Commands: 1.INSERT 2.SELECT 3.UPDATE 4.DELETE *INSERT: Syntax: INSERT INTO Table name values(); *SELECT: Syntax: Select*from <table name> *UPDATE: Syntax: Update<table name> set to(calculation); *DELETE: Syntax: Delete form<table name>
  • 23. 23 | P a g e Example : In the below figure shows the update and delete command on the given table.
  • 24. 24 | P a g e Experiment :-5 Aim:-Implement type of constraints with examples (a) Primary key (b) Foreign key (c) Check (d) Unique (e) Null (f) Not null (g) Default Primary Keys: Primary key uniquely identifies each record in a table. It must have unique values and cannot contain nulls. In the below example the ROLL_NO field is marked as primary key, that means the ROLL_NO field cannot have duplicate and null values.
  • 25. 25 | P a g e CREATE TABLE STUDENT( ROLL_NO INT NOT NULL, STU_NAME VARCHAR (35) NOT NULL UNIQUE, STU_AGE INT NOT NULL, STU_ADDRESS VARCHAR (35) UNIQUE, PRIMARY KEY (ROLL_NO) ); Foreign keys: are the columns of a tablethat points to the primary key of another table. They act as a cross- reference between tables. This constraint is used for specifying range of values for a particular column of a table. When this constraint is being set on a column, it ensures that the specified column must have the value falling in the specified range. CREATE TABLE STUDENT( ROLL_NO INT NOT NULL CHECK(ROLL_NO >1000) , STU_NAME VARCHAR (35) NOT NULL,
  • 26. 26 | P a g e STU_AGE INT NOT NULL, EXAM_FEE INT DEFAULT 10000, STU_ADDRESS VARCHAR (35) , PRIMARY KEY (ROLL_NO) ); In the above example we have set the check constraint on ROLL_NO column of STUDENT table. Now, the ROLL_NO field must have the value greater than 1000. UNIQUE Constraint:enforces a column or set of columns to have unique values. If a column has a unique constraint, it means that particular column cannot have duplicate values in a table. CREATE TABLE STUDENT( ROLL_NO INT NOT NULL, STU_NAME VARCHAR (35) NOT NULL UNIQUE, STU_AGE INT NOT NULL, STU_ADDRESS VARCHAR (35) UNIQUE, PRIMARY KEY (ROLL_NO)
  • 27. 27 | P a g e ); NOT NULL: constraint makes sure that a column does not hold NULL value. When we don’t provide value for a particular column while inserting a record into a table, it takes NULL value by default. By specifying NULL constraint, we can be sure that a particular column(s) cannot have NULL values. Example: CREATE TABLE STUDENT( ROLL_NO INT NOT NULL, STU_NAME VARCHAR (35) NOT NULL, STU_AGE INT NOT NULL, STU_ADDRESS VARCHAR (235), PRIMARY KEY (ROLL_NO) );
  • 28. 28 | P a g e The DEFAULT: constraint provides a default value to a column when there is no value provided while inserting a record into a table. Example:- CREATE TABLE STUDENT( ROLL_NO INT NOT NULL, STU_NAME VARCHAR (35) NOT NULL, STU_AGE INT NOT NULL, EXAM_FEE INT DEFAULT 10000, STU_ADDRESS VARCHAR (35) , PRIMARY KEY (ROLL_NO) );
  • 29. 29 | P a g e Experiment:-6. Aim:-Explain Data ManipulationLanguage(DML) with examples in DBMS. Data manipulation language (DML) can be defined as a set of syntax elements that are used to manage the data in the database. The commands of DML are not auto committed and modification made by them are not permanent to the database. It is a computer programming language that is used to perform select, insert delete and updatedata in a database.Theuser requests are assisted by data manipulation language. This language is responsible for all forms of data modification in a database. Types of Data Manipulation Languages. 1.Procedural programming In this type the user will specify what data is required and how to get it. 2 Declarative programming Here, the user will only specify what data is required
  • 30. 30 | P a g e Commands The DML section of SQL consists of following a set of commands.  Select/From/Where  Insertinto/values  Update/set/where  Delete/from/where The database programmers and users are allowed by this basic to enter the data and information into the database and then retrieve it by the use of several numbers of filter option.  Select/from/where  Select It is one of the basic query commands available in SQL and works in the same way as the projection operation of relational algebra. The attributes are selected by this command on the basis of the condition defined by the where clause.  From A relation name is taken by this clause as an argument from where attributed are to be projected or selected.
  • 31. 31 | P a g e  Where The predictions or conditions that should match for qualifying the attributed to be projected are defined by this clause. For example Select author_name From book-set Where age>40 The name of the authors will be yield by the command from the relation book set whose age is greater than 40. e.g. SQL> select*from student
  • 32. 32 | P a g e OUTPUT:- ROLL NO. NAME MARKS ADDR 101 ABC 75 LINK ROAD 102 XYZ 80 JM ROAD 103 PQR 87 N7 SQL>select *from student where marks=80 ROLL NO. NAME MARKS ADDR 102 XYZ 80 JM ROAD
  • 33. 33 | P a g e Experiment:7 Aim:- Implementationof Aggregate Functions These functions operate on the multiset of values of a column of a relation, and return a value avg: average value min: minimum value max: maximum value sum: sum of values count: number of values Q.1 Find the avg salary of employee from employee table Ans:- Select avg(salary) From employee Q.2 Find the no. of employee who worksin dept-no.2 Ans:- Select count(*) From employee Where dept-no.2
  • 34. 34 | P a g e Q.3 Find the no. of cities where dept present Ans:-Select count(distinct(city)) From department Q.4 Give the age of oldest employee Ans:-Select max(age) From employee Q.5 Find the mini. Age of employee whose salary is greater than 50K Ans:- Select min(age) From employee Where salary>50K Q.6 Find the total salary of all employees Ans:- Select sum(salary) From employee
  • 35. 35 | P a g e Aggregate Functions –Group By Find the average salary of instructors in each department  select dept_name, avg(salary) as avg_salary from instructor group by dept_name; Attributes in select clause outside of aggregate functions must appear in group bylist /* erroneous query */ select dept_name, ID, avg(salary) from instructor group by dept_name; Aggregate Functions –Having Clause Find the names and average salaries of all departments whose average salary is greater than 42000
  • 36. 36 | P a g e  select dept_name, avg(salary) from instructor group by dept_name having avg(salary) > 42000; Note: predicates in the havingclause are applied after the formation of groups whereas predicates in the where clause are applied before forming groups RENAME OPERATOR:- Employee(employee_name,e_id,age,salary) Q. Find the name of employee whose salary is greater than 20K Select employee_name as name From employee Where salary>20K
  • 37. 37 | P a g e Experiment:-8 Aim:-Implementation of Set operations on Data manipulation language Set Operations:- Find courses that ran in Fall 2009 or in Spring 2010 (selectcourse_idfrom section where sem= ‘Fall’ and year = 2009)  Union (selectcourse_idfrom section where sem= ‘Spring’ and year = 2010) Find courses that ran in Fall 2009 but not in Spring 2010 (selectcourse_idfrom section where sem= ‘Fall’ and year = 2009)  Intersect (selectcourse_idfrom section where sem= ‘Spring’ and year = 2010)
  • 38. 38 | P a g e Find courses that ran in Fall 2009 and in Spring 2010 (selectcourse_idfrom section where sem= ‘Fall’ and year = 2009)  Except (selectcourse_idfrom section where sem= ‘Spring’ and year = 2010) 1.Find the salaries of all instructors that are less than the largest salary select distinct T.salary from instructor as T, instructor as S where T.salary< S.salary 2.Find all the salaries of all instructors select distinct salary from instructor
  • 39. 39 | P a g e 3.Find the largest salary of all instructors (select“second query” ) Except (select“first query”) Set operations union, intersect, and except Each of the above operations automatically eliminates duplicates To retain all duplicates use the corresponding multiset versions union all, intersect alland except all. Suppose a tuple occurs mtimes in rand n times in s, then, it occurs: m + n times in r union all s min(m,n)times in rintersect all s max(0, m –n)times in rexcept all s
  • 40. 40 | P a g e EXPERIMENT-9 Aim:-IMPLEMENTATION OF NESTED QUERIES In nested queries, a query is written inside a query. The result of inner query is used in execution of outer query. We will use STUDENT, COURSE, STUDENT_COURSEtablesfor understandingnested queries. STUDENT S_ID S_NAME S_ADDRESS S_PHONE S_AGE S1 RAM DELHI 9455123451 18 S2 RAMESH GURGAON 9652431543 18 S3 SUJIT ROHTAK 9156253131 20 S4 SURESH DELHI 9156768971 18
  • 41. 41 | P a g e COURSE C_ID C_NAME C1 DSA C2 Programming C3 DBMS STUDENT_COURSE S_ID C_ID S1 C1 S1 C3 S2 C1 S3 C2 S4 C2 S4 C3
  • 42. 42 | P a g e There are mainly two types of nested queries:  Independent Nested Queries: In independent nested queries, query execution starts from innermost query to outermost queries. The execution of inner query is independent of outer query, but the result of inner query is used in execution of outer query. Various operators like IN, NOT IN, ANY, ALL etc are used in writing independent nested queries. IN: If we want to find out S_ID who are enrolled in C_NAME ‘DSA’ or ‘DBMS’, we can write it with the help of independent nested query and IN operator. From COURSE table, we can find out C_ID for C_NAME ‘DSA’ or DBMS’ and we can use these C_IDs for finding S_IDs from STUDENT_COURSE TABLE. STEP1: Finding C_ID for C_NAME =’DSA’or ‘DBMS’ Select C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME = ‘DBMS’
  • 43. 43 | P a g e STEP 2: Using C_ID of step 1 for finding S_ID Select S_ID from STUDENT_COURSEwhere C_ID IN (SELECT C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME=’DBMS’); STEP 3: Using C_ID of step 1 for finding S_ID Select S_ID from STUDENT_COURSEwhere C_ID IN (SELECT C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME=’DBMS’); The inner query will return a set with members C1 and C3 and outer query will return those S_IDs for which C_ID is equal to any member of set (C1 and C3 in this case). So, it will return S1, S2 and S4. Note: If we want to find out names of STUDENTs who have either enrolledin ‘DSA’ or ‘DBMS’, it can be done as:
  • 44. 44 | P a g e Select S_NAME from STUDENT where S_ID IN (Select S_ID from STUDENT_COURSE where C_ID IN (SELECT C_ID from COURSE where C_NAME=’DSA ’ or C_NAME=’DBMS’)); NOT IN: If we want to find out S_IDs of STUDENTs who have neither enrolled in ‘DSA’ nor in ‘DBMS’, it can be done as: Select S_ID from STUDENT where S_ID NOT IN (Select S_ID from STUDENT_COURSE where C_ID IN (SELECT C_ID from COURSE where C_NAME=’ DSA’ or C_NAME=’DBMS’)); The innermost query will return a set with members C1 and C3. Second inner query will return those S_IDs for which C_ID is equal to any member of set (C1 and C3 in this case) which are S1, S2 and S4. The outermost query will return those S_IDs where S_ID is not a member of set (S1, S2 and S4). So it will return S3.
  • 45. 45 | P a g e  Co-related Nested Queries: In co-related nested queries, the output of inner query dependson the row which is being currentlyexecuted in outer query. e.g.; If we want to find out S_NAME of STUDENTswho are enrolled in C_ID ‘C1’, it can be done with the help of co-related nested query as: Select S_NAME from STUDENT S where EXISTS ( select * from STUDENT_COURSE SC where S.S_ID=SC.S_ID and SC.C_ID=’C1’). For each row of STUDENT S, it will find the rows from STUDENT_COURSE where S.S_ID = SC.S_ID and SC.C_ID=’C1’. If for a S_ID from STUDENT S, atleast a row exists in STUDENT_COURSE SC with C_ID=’C1’, then inner query will return true and corresponding S_ID will be returned as output.
  • 46. 46 | P a g e Experiment:-10 Aim:-Create a company database and Write SQL Retrieval Queries with example CREATE TABLE employee ( emp_idINT PRIMARY KEY, first_nameVARCHAR(40), last_nameVARCHAR(40), birth_dayDATE, sexVARCHAR(1), salaryINT, super_idINT, branch_idINT ); CREATE TABLE branch ( branch_idINT PRIMARY KEY, branch_nameVARCHAR(40), mgr_idINT, mgr_start_dateDATE,
  • 47. 47 | P a g e FOREIGN KEY(mgr_id) REFERENCES employee(emp_id) ONDELETESETNULL ); ALTERTABLE employee ADD FOREIGN KEY(branch_id) REFERENCESbranch(branch_id) ONDELETESETNULL; ALTERTABLE employee ADD FOREIGN KEY(super_id) REFERENCESemployee(emp_id) ONDELETESETNULL; CREATETABLEclient ( client_idINT PRIMARY KEY, client_nameVARCHAR(40), branch_idINT,
  • 48. 48 | P a g e FOREIGN KEY(branch_id) REFERENCES branch(branch_id) ONDELETESETNULL ); CREATETABLEworks_with ( emp_idINT, client_idINT, total_salesINT, PRIMARY KEY(emp_id, client_id), FOREIGN KEY(emp_id) REFERENCES employee(emp_id) ONDELETECASCADE, FOREIGN KEY(client_id) REFERENCESclient(client_id) ONDELETECASCADE ); CREATETABLEbranch_supplier( branch_idINT, supplier_nameVARCHAR(40), supply_typeVARCHAR(40),
  • 49. 49 | P a g e PRIMARY KEY(branch_id,supplier_name), FOREIGN KEY(branch_id) REFERENCES branch(branch_id) ONDELETECASCADE ); -- ------------------------------------------------------------------- ---------- Corporate INSERTINTO employee VALUES(100, 'David', 'Wallace', '1967-11-17', 'M', 250000, NULL, NULL); INSERTINTO branch VALUES(1, 'Corporate', 100, '2006-02-09'); UPDATE employee SETbranch_id = 1 WHEREemp_id = 100;
  • 50. 50 | P a g e INSERTINTO employee VALUES(101, 'Jan', 'Levinson', '1961-05-11', 'F', 110000, 100, 1); -- Scranton INSERTINTO employee VALUES(102, 'Michael', 'Scott', '1964-03-15', 'M', 75000, 100, NULL); INSERTINTO branch VALUES(2, 'Scranton', 102, '1992- 04-06'); UPDATE employee SETbranch_id = 2 WHEREemp_id = 102; INSERTINTO employee VALUES(103, 'Angela', 'Martin', '1971-06-25', 'F', 63000, 102, 2); INSERTINTO employee VALUES(104, 'Kelly', 'Kapoor', '1980-02-05', 'F', 55000, 102, 2);
  • 51. 51 | P a g e INSERTINTO employee VALUES(105, 'Stanley', 'Hudson', '1958-02-19', 'M', 69000, 102, 2); -- Stamford INSERTINTO employee VALUES(106, 'Josh', 'Porter', '1969-09-05', 'M', 78000, 100, NULL); INSERTINTO branch VALUES(3, 'Stamford', 106, '1998-02-13'); UPDATE employee SETbranch_id = 3 WHEREemp_id = 106; INSERTINTO employee VALUES(107, 'Andy', 'Bernard', '1973-07-22', 'M', 65000, 106, 3); INSERTINTO employee VALUES(108, 'Jim', 'Halpert', '1978-10-01', 'M', 71000, 106, 3);
  • 52. 52 | P a g e -- BRANCH SUPPLIER INSERTINTObranch_supplierVALUES(2, 'Hammer Mill', 'Paper'); INSERTINTObranch_supplierVALUES(2, 'Uni-ball', 'Writing Utensils'); INSERTINTObranch_supplierVALUES(3, 'Patriot Paper', 'Paper'); INSERTINTObranch_supplierVALUES(2, 'J.T. Forms & Labels', 'Custom Forms'); INSERTINTObranch_supplierVALUES(3, 'Uni-ball', 'Writing Utensils'); INSERTINTObranch_supplierVALUES(3, 'Hammer Mill', 'Paper'); INSERTINTObranch_supplierVALUES(3, 'Stamford Lables', 'Custom Forms');
  • 53. 53 | P a g e -- CLIENT INSERTINTOclientVALUES(400, 'Dunmore Highschool', 2); INSERTINTOclientVALUES(401, 'Lackawana Country', 2); INSERTINTOclientVALUES(402, 'FedEx', 3); INSERTINTOclientVALUES(403, 'John Daly Law, LLC', 3); INSERTINTOclientVALUES(404, 'Scranton Whitepages', 2); INSERTINTOclientVALUES(405, 'Times Newspaper', 3); INSERTINTOclientVALUES(406, 'FedEx', 2);
  • 54. 54 | P a g e -- WORKS_WITH INSERTINTOworks_withVALUES(105, 400, 55000); INSERTINTOworks_withVALUES(102, 401, 267000); INSERTINTOworks_withVALUES(108, 402, 22500); INSERTINTOworks_withVALUES(107, 403, 5000); INSERTINTOworks_withVALUES(108, 403, 12000); INSERTINTOworks_withVALUES(105, 404, 33000); INSERTINTOworks_withVALUES(107, 405, 26000); INSERTINTOworks_withVALUES(102, 406, 15000); INSERTINTOworks_withVALUES(105, 406, 130000);