Database and SQL Lab
Database and SQL Lab
for
3159
By
SITTTR
Kalamassery
GENERAL INSTRUCTIONS
Rough record and Fair record are needed to record the experiments conducted in the laboratory.
Rough records are needed to be certified immediately on completion of the experiment. Fair records
are due at the beginning of the next lab period. Fair records must be submitted as neat, legible, and
complete.
In the fair record, the index page should be filled properly by writing the corresponding experiment
number, experiment name , date on which it was done and the page number.
1. Title: The title of the experiment should be written in the page in capital letters.
2. In the left top margin, experiment number and date should be written.
6. Procedure: steps for doing the experiment and recording the readings should be briefly
described(flow chart/programs in the case of computer/processor related experiments)
7. Results: The results of the experiment must be summarized in writing and should be fulfilling
the aim.
iii) Relevant calculations should be shown. If repetitive calculations are needed, only show a sample
calculation and summarize the others in a table.
4. Graphs : Graphs can used to present data in a form that show the results obtained, as one or
more of the parameters are varied. A graph has the advantage of presenting large
1. Always wear tight shirt/lab coat , pants and shoes inside workshops.
2. REMOVE ALL METAL JEWELLERY since rings, wrist watches or bands, necklaces, etc. make
excellent electrodes in the event of accidental contact with electric power sources.
3. DO NOT MAKE CIRCUIT CHANGES without turning off the power.
4. Make sure that equipment working on electrical power are grounded properly.
5. Avoid standing on metal surfaces or wet concrete. Keep your shoes dry.
6. Never handle electrical equipment with wet skin.
7. Hot soldering irons should be rested in its holder. Never leave a hot iron unattended.
8. Avoid use of loose clothing and hair near machines and avoid running around inside lab .
DO: 1. SET MULTIRANGE METERS to highest range before connecting to an unknown source.
2. INFORM YOUR INSTRUCTOR about faulty equipment so that it can be sent for repair.
DO NOT: 1. Do not MOVE EQUIPMENT around the room except under the supervision of an
instructor.
1 Introduction to MYSQL 3
5 Views 14
6 Procedures 15
7 Cursors 16
8 Triggers 17
9 Normalization 18
10 Checking Normalization 19
Introduction to MYSQL
AIM:
To study about Mysql database
OBJECTIVES
THEORY
MySQL, is one of the most popular Open Source SQL database management systems.
MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses.
MySQL is developed, marketed, and supported by MySQL AB, which is a Swedish
company.
MySQL is becoming so popular because of many good reasons:
MySQL is released under an open-source license. So you have nothing to pay to use
it.
MySQL is a very powerful program in its own right. It handles a large subset of the
functionality of the most expensive and powerful database packages.
MySQL works on many operating systems and with many languages including PHP,
PERL, C, C++, JAVA, etc.
MySQL works very quickly and works well even with large data sets.
MySQL is very friendly to PHP, the most appreciated language for web development.
MySQL is customizable.
RESULT
OBJECTIVES
THEORY
Database Queries:
Before creating any tables, MySQL requires you to create a database by executing the
CREATE DATABASE command.
Create a database
CREATE DATABASE <database name>
Delete a database
DROP DATABASE <database name>
Select the database
USE <database name>
List all databases
SHOW databases;
Rename a database
ALTER DATABASE <database name> RENAME <new database name>
Constraints:
Primary key A PRIMARY KEY constraint for a table enforces the table to accept
unique data for a specific column and this constraint create a unique index for
accessing the table faster
UNIQUE The UNIQUE constraint in Mysql does not allow to insert a duplicate
value in a column.
NOT NULL In Mysql NOT NULL constraint allows to specify that a column can
not contain any NULL value.
FOREIGN KEY A FOREIGN KEY in mysql creates a link between two tables by
one specific column of both table. The specified column in one table must be a
PRIMARY KEY and referred by the column of another table known as FOREIGN
KEY.
CHECK The CHECK constraint determines whether the value is valid or not from
a logical expression.
DEFAULT While inserting data into a table, if no value is supplied to a column,
then the column gets the value set as DEFAULT
PROCEDURE
(i) CREATE DATABASE command
RESULT:
OUTPUT
Problems
1. Consider the database for a college and design an ER diagram. Write the query for the
following.
Register (sid,cid,sem )
Teaching (f_id,cid,sem)
Hostel(hid,hname,seats,)
(ii) Include the necessary constraints NOT NULL, DEFAULT, CHECK, and PRIMARY KEY,
UNIQUE.
2. Consider the database for a banking enterprise. Write the queries for the below
questions.
Table Attributes
customer cid,cname,loc,sex,dob
Bank_brn bcode,bloc,bsate
Deposit Dacno,dtype,ddate,damt
Loan Lacno,ltype,ldate,lamt
Accounts_in Bcode,cid
depositor cid,dacno
borrower cid,lacno
AIM:
Consider the database for an organisation. Write the queries for the following
(i) Add 5 rows in the employee and dept tables
(ii) Display all the records from the above tables
(iii) Display the empno and name of all the employees from department no2
(iv) Display empno,name,designation,dept no and salary in the descending order of
salary
(v) Display the empno and name of all employees whose salary is between 2000 and
5000
(vi) Display all designations without duplicate values.
(vii) Display the dept name and total salary of employees of each department.
(viii) Change the salary of employees to 25000 whose designation is ‘Typist’
(ix) Change the mobile no of employee named ‘john’
(x) Delete all employees whose salaries are equal to Rs.7000
(xi) Select the department that has total salary paid for its employees more than 25000
OBJECTIVES
To understand how to insert, update and delete data from within a table.
To learn how to retrieve data from a table using the SELECT statement.
THEORY
1. INSERT
INSERT INTO tablename VALUES (value1, value2, ..., valuen).
2. UPDATE
UPDATE <table> SET <field1> = <value1> AND <field2> = <value2> WHERE <conditions>
3. DELETE
DELETE FROM <table> WHERE <condition>
4. SELECT
a) Retrieve from all columns
SELECT * FROM <table>
b) Retrieve from selected columns
SELECT <column 1>, <column 2> FROM <table>
c) Retrieve unique values
SELECT DISTINCT <column name> FROM <table>
d) Retrieve data satisfying a given condition
SELECT <columns> FROM <tables> WHERE <condition>
PROCEDURE
RESULT
The DML commands are executed successfully.
OUTPUT
Problems
1. Consider the database for a college. Write the query for the following.
(ii) List the details of students in the ascending order of date of birth
(vi) Display the total number of faculties in each department with salary greater than
25000
(vi) List the deposit schemes provided by the bank to the customers
AIM:
Consider the database for the organization and Write the queries for the following
(i) display the empno, name, and salaries for employees whose average salary is higher
than the average salary of the organization
(ii) Display the details of employees whose salary is equal to the minimum salary of
organisation.
(iii) Display all the employees whose designation is same as that of ‘Arun’
(iv) display the empno and name of employees who earn more than any
Employee in dept 1.
(v) Display the empno,name , departments that the departments are same in both the
emp and dept
(vi) Display the employee details by implementing left inner join
(vii) Display employee details by implementing a right outer join
OBJECTIVES
THEORY
NESTED QUERIES:
A sub query is a query within a query. These sub queries can reside in the WHERE clause,
the FROM clause, or the SELECT clause. The first query in the SQL statement is known as
the outer query. The query inside the SQL statement is known as the inner query. The inner
query is executed first. The output of an inner query is used as the input for the outer query.
The entire SQL statement is sometimes referred to as a nested query.
JOINS:
MySQL JOINS are used to retrieve data from multiple tables. A MySQL JOIN is performed
whenever two or more tables are joined in a SQL statement.
There are different types of MySQL joins:
Syntax
SELECT columns
From table1
Inner join table2
On table1.column=table2.column;
Syntax
SELECT columns
From table1
left join table2
On table1.column=table2.column;
Syntax
Syntax
SELECT columns
From table1
Right join table2
On table1.column=table2.column;
RESULT:
The nested queries and joins are executed successfully.
Programs
1. Consider the database for a banking enterprise. Write the queries for the below
questions.
(i) List the deposit account number and amount in which the deposit scheme
having maximum deposit is opened
(ii) List the account number and amount of that savings bank deposit scheme in
which minimum amount is deposited.
(v) List the customers having same name but different account numbers.
(vi) List the customer name that is having maximum deposit account in bank
(vii) List the customer who has borrowed highest amount of home loan
2. Consider the database for a college. Write the queries for the below questions.
(i) List out the ID, Name and Date of Birth of students registered for a specific
course.
(ii) List out the ID, Name and Date of Birth of students registered for a specific
course, staying in a specific Hostel.
(iii) List the names of faculties who teach for a specific course.
(iv) Display the student details by implementing left inner join
(v) Display the student details by implementing a right outer join
(i) Create a view emp from employee such that it contains only emp_no and
emp_name and department.
(ii) Create a view dept from department with only dept_no and location.
(iii) Create a view that contains the details of employees who are managers only.
(iv) drop the views.
OBJECTIVES
THEORY
A view is the tailored presentation of data contained in one or more table and can also be said
as restricted view to the data in the tables. A view is a “virtual table” or a “stored query”
which takes the output of a query and treats it as a table. The table upon which a view is
created is called as base table. A view is a logical table based on a table or another view. A
view contains no data of its own but is like a window through which data from tables can be
viewed or changed. The tables on which a view is based are called base tables. The view is
stored as a SELECT statement in the data dictionary.
Advantages of a view:
a. Additional level of table security.
b. Hides data complexity.
c. Simplifies the usage by combining multiple tables into a single table
Syntax:
PROCEDURE
Result
Thus the views are created successfully
Problems
1. Create and drop views on student table
EXPERIMENT NO:6
PROCEDURE
AIM:
Write a procedure which increases the salary of an employee. It accepts an employee number
and salary increase amount. It uses the employee number to find the current salary from the
EMPLOYEE table and update the salary.
OBJECTIVES
PROCEDURE:
In MySQL, a procedure is a stored program that you can pass parameters into. It does not
return a value like a function does.
Syntax
Create procedure procedure name (parameter data type, parameter data type...)
Begin
Declaration section
Executable _section
End;
Procedure name
The name to assign to this procedure in MySQL.
Parameter
Declaration section
The place in the procedure where you declare local variables.
Executable section
The place in the procedure where you enter the code for the procedure.
PROCEDURE:
OUTPUT
RESULT:
The procedures are executed successfully.
Problems
1. Write a procedure which accept the account number of a customer and retrieve the
balance.
2. Write a procedure which accepts the student number and displays the department in
which he belongs to.
EXPERIMENT NO: 7
CURSOR
AIM
Write a cursor to display the list of employees who are working as managers.
To implement cursor
THEORY
A cursor is a SELECT statement that is defined within the declaration section of your stored
program in MySQL.
1. Declare a cursor
Declare cursor name cursor for select statement;
2. Open the cursor.
Open cursor name;
3. Fetch cursor
The purpose of using a cursor, in most cases, is to retrieve the rows from your cursor
so that some type of operation can be performed on the data.
PROCEDURE
To be written by the student
OUTPUT
The cursor is executed successfully.
RESULT
PROGRAMS
1. Create a cursor to modify the salary of ‘Professors’ belonging to all departments by 150%.
2. Consider the college database. Retrieve all students who have registered for a specific
course and store their details into another table using cursors.
3. Consider the bank database .Retrieve all customers who have loan at a particular
branch using cursor.
EXPERIMENT NO: 8
TRIGGER
AIM
Write a Trigger for employee table it will store the updated salary into another table
SALARY while updating salary.
OBJECTIVES
To understand triggers in Mysql
PROCEDURE
(i) Create the employee table
(ii) Insert values
(iii)Write the after update trigger
(iv) Update the salary in employee table
(v) Display the SALARY table
RESULT:
Problems
1. Write an update trigger on Account table. The system should keep track of the records
that are being updated.
2. Write a before delete trigger on student table.
Experiment No: 9
CONCEPTS OF NORMALIZATION
AIM: Checking Normalization of a database table (First Normal form)
We can easily verify that this table satisfies the definition of 1NF: viz., it has no duplicated
rows; each cell is single-valued (i.e., there are no repeating groups or arrays); and all the
entries in a given column are of the same kind. In this table we can see that the key, SSN,
functionally determines the other attributes; i.e.,FirstName, LastName, and Major. .
Experiment No: 10
An excercise to check whether the given database table is normalized or not. If yes find out
the status of normalization and reasoning.
Objective:
Design/Theory
Create a database table in SQL with a few no of rows and columns.Analyze
the table and determine to which normal form it beongs to according to the rules and
regulations of each normal forms.
Procedure:
Consider a book database table as given below.
Author Author Book Title Subject Collection or Building
Last First Library
Name Name
Berdahl Robert The Politics of the History PCL General Perry-
Prussian Nobility Stacks Castañeda
Library
Yudof Mark Child Abuse and Legal Law Library Townes Hall
Neglect Procedur
es
Harmon Glynn Human Memory and Cognitiv PCL General Perry-
Knowledge e Stacks Castañeda
Psycholo Library
gy
Graves Robert The Golden Fleece Greek Classics Waggener
Literatur Library Hall
e
Miksa Francis Charles Ammi Library Library and Perry-
Cutter Biograph Information Castañeda
y Science Library
Collection
Hunter David Music Publishing Music Fine Arts Fine Arts
and Collecting Literatur Library Building
e
Graves Robert English and Scottish Folksong PCL General Perry-
Ballads Stacks Castañeda
Library
By examining the table, we can infer that books dealing with history, cognitive
psychology, and folksong are assigned to the PCL General Stacks collection; that books
dealing with legal procedures are assigned to the Law Library; that books dealing with Greek
literature are assigned to the Classics Library; that books dealing with library biography are
Moreover, we can infer that the PCL General Stacks collection and the LISC are both
housed in the Perry-Castañeda Library (PCL) building; that the Classics Library is housed in
Waggener Hall; and that the Law Library and Fine Arts Library are housed, respectively, in
Townes Hall and the Fine Arts Building.
Thus we can see that a transitive dependency exists in the above table : any book that
deals with history, cognitive psychology, or library biography will be physically housed in
the PCL building (unless it is temporarily checked out to a borrower); any book dealing with
legal procedures will be housed in Townes Hall; and so on. In short, if we know what subject
a book deals with, we also know not only what library or collection it will be assigned to but
also what building it is physically housed in.
A problem with transitive dependency is that, there is duplicated information: from three
different rows we can see that the PCL General Stacks are in the PCL building. For another
thing, we have possible deletion anomalies: if the Yudof book were lost and its row removed
from table, we would lose the information that books on legal procedures are assigned to the
Law Library and also the information the Law Library is in Townes Hall. As a third problem,
we have possible insertion anomalies: if we wanted to add a chemistry book to the table, we
would find that the above table nowhere contains the fact that the Chemistry Library is in
Robert A.Welch Hall. As a fourth problem, we have the chance of making errors in updating:
a careless data-entry clerk might add a book to the LISC but mistakenly enter Townes Hall in
the building column.
To solve this problem decompose the above table into three different tables as follows
Table A
Table B
Table C
Subject Collection or Library
Table D
Collection or Library Building
Problem Statement:
A program which connects to an online book database table and select the tuple and display
it.
Objective:
To understand the connectivity to a database table using java. In java database is accessed
through java database connectivity(JDBC).
Design/Theory:
The four main components required for implementation of JDBC are application,
driver manager, data source specific drivers and corresponding data sources. The application
program establishes/terminates connection with data. Driver manager will load JDBC drivers
and pass JDBC function calls from the application to the driver.The data source processes
commands from the driver and return the results.
1. Drivers for the database are loaded by using Class.for Name.
2. The getConnection() function of DriverManager class of JDBC is used to create the
connection object. The URL specifies the machine name(db.onlinebook.edu)
Experiment No:12
DATABASE CONNECTIVITY
AIM:
To create a PHP-Mysql Program to enter data into Mysql
Problem Statement:
A php program that connects to a database table and insert values into the table.
Objective:
To understand the connectivity to a database table using php and how to insert new values
into that table.
Requirements:
Design/Theory:
EXPERIMENT NO: 13
DATABASE CONNECTIVITY
AIM
Create a php program that allows to enter the employee details into a database.
To create an application program that process a query which returns the grade result of a
student after processing the marks table.
OBJECTIVES
To understand PHP mysql database connectivity.
To study the concept of connecting database using an application program (PHP) and process
results after manipulating the database table
Requirements:
PROCEDURE
Create a database in Mysql. Create a 'marks' table with fields regno, name, batch, mark1,
mark2 and mark3. Write a function which finds the total marks and if the total marks is
greater than 225 then the result is categorized as “Distinction”, if the total marks is less than
225 , the result is “firstclass”, it the total marks is less than 180, the result is “second class”, if
the total marks is less than 150 the result is “passed”. If the marks in any one of the subject is
less than 40 the result is “Failed”.
php code:
$user_name = "root";
$password = "";
$server = "localhost";
$database = "mysql";
$regno = $_POST['regno'];
//$regno = 1;
if (!$db_handle)
{
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
$db_found = mysql_select_db($database);
if ($db_found)
{
//echo "Database found";
$SQL = "SELECT * FROM marks WHERE regno = '".$regno."'";
$result_set = mysql_query($SQL);
$record = mysql_fetch_array($result_set);
echo "<BR>MARKLIST";
echo "<BR>Reg No..:".$record['regno'];
echo "<BR>Name....:".$record['name'];
echo "<BR>Group...:".$record['batch'];
echo "<BR>Mark1...:".$record['mark1'];
echo "<BR>Mark2...:".$record['mark2'];
echo "<BR>Mark3...:".$record['mark3'];
echo "<BR>Result..:".
compute_result($record['mark1'],$record['mark2'],$record['mark3']);
Html code:
<html>
<body>
OUTPUT
RESULT