LMS-DBMS Lab Manual
LMS-DBMS Lab Manual
List of Experiments
S. No. Name of the Experiment
1
Introduction to SQL & MySQL and Database Design
3 INSERT
UPDATE
DELETE
Implementation of Constraints
PRIMARY KEY
FOREIGN KEY
UNIQUE
4
NULL
NOT NULL
DEFAULT
CHECK
Implementation of different types of function
NUMBER FUNCTION
5 AGGREGATE FUNCTION
STRING FUNCTION
DATE FUNCTION
Implementation of different types of operators .
ARITHMETIC OPERATORS
LOGICAL OPERATORS
6
COMPARISON OPERATORS
SPECIAL OPERATORS
SET OPERATORS
Implementation of different types of Joins.
INNER JOIN
7 OUTER JOIN
NATURAL JOIN
SELF JOIN
Implementation of GROUP BY, HAVING, ORDER BY
8 clause(s).
Exp : 1
Clauses, which are in some cases optional, constituent components of statements and
queries.
Expressions, which can produce either scalar values or tables consisting of columns
and rows of data.
Statements which may have a persistent effect on schemas and data, or which may
control transactions, program flow, connections, sessions, or diagnostics.
SQL statements also include the semicolon (";") statement terminator. Though not
required on every platform, it is defined as a standard part of the SQL grammar.
Insignificant white space is generally ignored in SQL statements and queries, making
it
easier to format SQL code for readability.
MySQL
MySQL is the widely used open source database. MySQL is the backend database of most of
the websites. As a Free Software(Free as in freedom), MySQL can be downloaded and used
by the developer for free.MySQL is robust and it provides excellent performance due to
usage of MyISAM. MySQL occupies very less disk space.MySQL can be easily installed in
all major operating systems like Microsoft Windows, Linux, UNIX. MySQL is best suited for
small and medium applications.
Before creating any tables, MySQL requires you to create a database by executing the
CREATE DATABASE command. To create a database called SaleCo you would type the
following:
A specific database has to be chosen to work upon. Databases objects created under one
database will not be available in the other. To choose a particular database use the below
command.
In order to view the tables created under a specifc databases use the show table command.
Database Design :
A database model is a type of data model that determines the logical structure of
adatabase and fundamentally determines in which manner data can be stored, organized and
manipulated. The most popular example of a database model is the relational model, which
uses a table-based format.
Logical database design is the process of deciding how to arrange the attributes of the
entities in a given business environment into database structures, such as the tables of a
relational database. The goal of logical database design is to create well structured tables that
properly reflect the company's business environment. The tables will be able to store data
about the company's entities in a non-redundant manner and foreign keys will be placed in
the tables so that all the relationships among the entities will be supported.
Consider the Insurance Database given below. The primary keys are underlined and the
datatypes are specified.
Sample ER diagram
CAR
NAME OW
NS
ADDRESS
PERSON
DRIVER_I
mak
es
ACCIDENT
The Prescriptions-R-X chain of pharmacies has offered to give you a Free lifetime supply of
medicines if you design its database. Given the rising cost of health care, you agree.
Here's the information that you gather:
Patients are identified by an SSN, and their names, addresses, and ages must be
recorded.
Doctors are identified by an SSN. For each doctor, the name, specialty, and years of
experience must be recorded.
Each pharmaceutical company is identified by name and has a phone number. For
each drug, the trade name and formula must be recorded.
Each drug is sold by a given pharmaceutical company, and the trade name identifies a
drug uniquely from among the products of that company. If a pharmaceutical
company is deleted, you need not keep track of its products any longer.
Each pharmacy has a name, address, and phone number.
Every patient has a primary physician. Every doctor has at least one patient.
Each pharmacy sells several drugs and has a price for each. A drug could be sold at
several pharmacies, and the price could vary from one pharmacy to another.
Doctors prescribe drugs for patients. A doctor could prescribe one or more drugs for
several patients, and a patient could obtain prescriptions from several doctors.
Each prescription has a date and a quantity associated with it. You can assume that if
a doctor prescribes the same drug for the same patient more than once, only the last
such prescription needs to be stored.
Pharmaceutical companies have long-term contracts with pharmacies. A
pharmaceutical company can contract with several pharmacies, and a pharmacy can
contract with several pharmaceutical companies. For each contract, you have to store
a start date, an end date, and the text of the contract.
Pharmacies appoint a supervisor for each contract. There must always be a supervisor
for each contract, but the contract supervisor can change over the lifetime of the
contract.
Draw an ER diagram that captures the above information. Identify any constraints that
are not captured by the ER diagram.
Experiment:2 ER Model to Relational Model Date: 17.8.2021
b. Translate the ER model you have drawn in Experiment1 to a corresponding relational model.
Keep all your assumptions and make the translation.
Experiment : 3 DDL COMMANDS
The Data Definition Language (DDL) is used to create and destroy databases and database
objects. It simply deals with descriptions of the database schema and is used to create and
modify the structure of database objects in database..
Let's take a look at the structure and usage of four basic DDL commands:
1. CREATE
2. ALTER
3. DROP
4. RENAME
5. TRUNCATE
1. CREATE:
Syntax:
CREATE TABLE <relation_name/table_name > (field_1 data_type(size),field_2
data_type(size), .. . );
Example:
SQL> CREATE TABLE Student (sno int, sname CHAR (10), class CHAR (5));
2. ALTER:
Syntax:
ALTER TABLE relation_name ADD (new field_1 data_type(size), new field_2
data_type(size),..);
Example:
SQL>ALTER TABLE std ADD (Address CHAR(10));
(b)ALTER TABLE...MODIFY...:
This is used to change the width as well as data type of fields of existing relations.
Syntax:
Example:
SQL>ALTER TABLE student MODIFY(sname VARCHAR(10),class
VARCHAR(5));
c) ALTER TABLE..DROP...:
This is used to remove any field of existing relations.
Syntax:
ALTER TABLE relation_name DROP COLUMN (field_name);
Example:
SQL>ALTER TABLE student DROP column (sname);
d)ALTER TABLE..RENAME...:
This is used to change the name of fields in existing relations.
Syntax:
ALTER TABLE relation_name RENAME COLUMN (OLD field_name) to (NEW
field_name);
Example:
SQL>ALTER TABLE student RENAME COLUMN sname to stu_name;
3. DROP TABLE:
This is used to delete the structure of a relation. It permanently deletes the records in the table.
Syntax:
DROP TABLE relation_name;
Example:
SQL>DROP TABLE std;
4. RENAME:
It is used to modify the name of the existing database object.
Syntax:
RENAME TABLE old_relation_name TO new_relation_name;
Example:
5.TRUNCATE:
Syntax :
TRUNCATE TABLE relation_name;
Example:
mysql> TRUNCATE TABLE student;
LAB Exercise:
1. INSERT table
2. UPDATE table
3. DELETE table
4. SELECT
1. INSERT
This is used to add records into a relation. These are three type of INSERT INTO queries
which are as,
Example:
SQL>INSERT INTO student VALUES (1,’Ravi’,’M.Tech’,’Palakol’),
(2,’Mohan’,’M.Tech’,'Trichy'), (4,’Rio’,’MBA’,'Lucknow');
Syntax:
INSERT INTO relation_name_1 SELECT Field_1,field_2,field_n FROM relation_name_2
WHERE field_x=data;
Example:
SQL>INSERT INTO std SELECT sno,sname FROM student WHERE name = ‘Ramu‘;
Example:
SQL>UPDATE student SET sname = ‘kumar’ WHERE sno=1;
3. DELETE-FROM: This is used to delete all the records of a relation but it will retain the
structure of that relation.
Syntax:
SQL>DELETE FROM relation_name;
Example:
SQL>DELETE FROM std;
Syntax:
SQL>DELETE FROM relation_name WHERE condition;
Example:
4. SELECT - To Retrieve data from one or more tables.To display all fields for all records.
Syntax :
SELECT * FROM relation_name;
Example :
SQL> select * from dept;
SELECT - FROM -WHERE: This query is used to display a selected set of fields for a
selected set of records of a relation.
Syntax:
SELECT a set of fields FROM relation_name WHERE condition;
Example:
SQL> select * FROM dept WHERE deptno<=20;
Constraints are used to specify rules for the data in a table. If there is any violation between
the constraint and the data action, the action is aborted by the constraint. It can be specified
when the table is created (using CREATE TABLE statement) or after the table is created
(using ALTER TABLE statement).
1. NOT NULL:
When a column is defined as NOTNULL, then that column becomes a mandatory column. It
implies that a value must be entered into the column if the record is to be accepted for storage
in the table.
Syntax:
CREATE TABLE Table_Name (column_name data_type (size) NOT NULL, );
Example:
CREATE TABLE student (sno NUMBER(3)NOT NULL, name CHAR(10));
2. UNIQUE:
The purpose of a unique key is to ensure that information in the column(s) is unique i.e. a
value entered in column(s) defined in the unique constraint must not be repeated across the
column(s). A table may have many unique keys.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) UNIQUE, ….);
Example:
CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10));
3. CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the
constraint, each row in the table must make the condition either TRUE or unknown (due to a
null).
Syntax:
CREATE TABLE Table_Name(column_name data_type(size)
CHECK(logical expression), ….);
Example:
CREATE TABLE student (sno NUMBER (3), name CHAR(10),class
CHAR(5),CHECK(class IN(‘CSE’,’CAD’,’VLSI’));
4. PRIMARY KEY:
A field which is used to identify a record uniquely. A column or combination of columns can
be created as primary key, which can be used as a reference from other tables. A table
contains primary key is known as Master Table.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) PRIMARY KEY, ….);
Example:
CREATE TABLE faculty (fcode NUMBER(3) PRIMARY KEY, fname CHAR(10));
5. FOREIGN KEY:
It is a table level constraint. We cannot add this at column level. To reference any primary
key column from other table this constraint can be used. The table in which the foreign key is
defined is called a detail table. The table that defines the primary key and is referenced by
the foreign key is called the master table.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) FOREIGN
KEY(column_name) REFERENCES table_name);
Example:
CREATE TABLE subject (scode NUMBER (3) PRIMARY KEY, subname
CHAR(10),fcode NUMBER(3), FOREIGN KEY(fcode) REFERENCE faculty );
Syntax:
ALTER TABLE Table_Name ADD PRIMARY KEY (column_name);
Example:
ALTER TABLE student ADD PRIMARY KEY (sno);
(Or)
Syntax:
ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY
KEY(colname)
Example:
ALTER TABLE student ADD CONSTRAINT SN PRIMARY KEY(SNO)
Example:
ALTER TABLE student DROP PRIMARY KEY;
(or)
Syntax:
ALTER TABLE student DROP CONSTRAINT constraint_name;
Example:
ALTER TABLE student DROP CONSTRAINT SN;
6. DEFAULT :
The DEFAULT constraint is used to insert a default value into a column. The default value
will be added to all new records, if no other value is specified.
Syntax:
CREATE TABLE Table_Name(col_name1,col_name2,col_name3 DEFAULT ‘<value>’);
Example:
CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10),address
VARCHAR(20) DEFAULT ‘Aurangabad’);
Allow NULL for all columns except ename and job. (Either in Create command or
Alter Command)
2. Add constraints to check, while entering the empno value (i.e) empno > 100.
3. Define the field DEPTNO as unique.
4. Create a primary key constraint for the table(EMPNO).
5. Create a default constraint and provide a salary value of "1000" if salary is not provided.
Name Type
---------- ----------------------
DEPTNO NUMBER (6)
DNAME VARCHAR2 (20)
LOC VARCHAR2 (10)
create a referential integrity constraint between Employee and Department table.
7.Display the Employee information along with department details
8. Display the Employee details who works in CSE department and salary less than 10000.
9. Delete the Employee details who works in Hyderabad.
1. NUMBER FUNCTIONS:
ii. Power(m,n): POWER() function returns the value of a number raised to another,
where both of the numbers are passed as arguments.
v. Truncate(m,n): The TRUNC () function returns date value truncated to the unit
specified by the format.
vi. Sqrt(m,n): returns the square root of a given value in the argument.
2. AGGREGATE FUNCTIONS:
In addition to simply retrieving data, we often want to perform some computation or
summarization. SQL allows the use of arithmetic expressions. We now consider a powerful
class of constructs for computing aggregate values such as MIN and SUM.
i. Count():
COUNT following by a column name returns the count of tuple in that column. If DISTINCT
keyword is used then it will return only the count of unique tuple in the column. Otherwise, it
will return count of all the tuples (including duplicates) count (*) indicates all the tuples of
the column.
Syntax:
COUNT (Column name)
Example:
SELECT COUNT (Sal) FROM emp;
ii. SUM(): SUM followed by a column name returns the sum of all the values in that
column.
Syntax:
SUM (Column name)
Example:
SELECT SUM (Sal) From emp;
iii. AVG(): AVG followed by a column name returns the average value of that column
values.
Syntax:
AVG (n1, n2...)
Example:
Select AVG (10, 15, 30) FROM DUAL;
iv. MAX():
MAX followed by a column name returns the maximum value of that column.
Syntax:
MAX (Column name)
Example:
SELECT MAX (Sal) FROM emp;
SQL> select deptno, max (sal) from emp group by deptno having max(sal)<3000;
DEPTNO MAX(SAL)
----- --------
30 2850
v. MIN(): MIN followed by column name returns the minimum value of that column.
Syntax:
MIN (Column name)
Example:
SELECT MIN (Sal) FROM emp;
v. replace (char,search ): Finds the given character in a string and replaces with another
character.
select substr(‘ABCDEFGHIJ’,3,4);
CDEF
ix. Instr: The INSTR functions search string for substring. The function returns an integer
indicating the position of the character in string that is the first character of this
occurrence.
select instr('CORPORATE FLOOR','OR',3,2);
4. DATE FUNCTIONS:
i. SYSDATE() /CURDATE():
select sysdate();
2-DEC-08
ii. DATE_ADD()
iii. DATE_SUB()
iv. DATE_FORMAT()
v. DATE()
vi. DATEDIFF()
vii. DAY()