DBMS Lab Manual
DBMS Lab Manual
DBMS Lab Manual
LABORATORY MANUAL
SEMESTER: V
Objectives
To provide quality education and groom top-notch professionals, entrepreneurs and
leaders for different fields of engineering, technology and management.
To open a Training-R & D-Design-Consultancy cell in each department, gradually
introduce doctoral and postdoctoral programs, encourage basic & applied research in
areas of social relevance, and develop the institute as a center of excellence.
To develop academic, professional and financial alliances with the industry as well as
the academia at national and transnational levels.
To develop academic, professional and financial alliances with the industry as well as
the academia at national and transnational levels.
To cultivate strong community relationships and involve the students and the staff in
local community service.
To constantly enhance the value of the educational inputs with the participation of
students, faculty, parents and industry.
Vision
Development of academically excellent, culturally vibrant, socially responsible and
globally competent human resources.
Mission
To keep pace with advancements in knowledge and make the students competitive and
capable at the global level.
To create an environment for the students to acquire the right physical, intellectual,
emotional and moral foundations and shine as torch bearers of tomorrow's society.
To strive to attain ever-higher benchmarks of educational excellence.
Department of Computer Science & Engineering
Vision of the Department
Motivate students to put their thoughts and ideas adoptable by industry or to pursue
higher studies leading to research.
PO2. Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first principles
of mathematics, natural sciences, and engineering sciences.
PO5. Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
PO6. The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
PO12. Life-long learning: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of technological
change.
2. PSO2: Apply knowledge in the field of computer networks for building network and
internet based applications.
Program Educational Objectives (PEOs):
CREDITS – 02
Course objectives: This course will enable students to
Foundation knowledge in database concepts, technology and practice to groom students
into well-informed database applicationdevelopers.
Strong practice in SQL programming through a variety of databaseproblems.
Develop database applications using front-end tools and back-endDBMS.
Lab Experiments:
Part A: SQL Programming
Experiment distribution
o For laboratories having only one part: Students are allowed to pick one
experiment from the lot with equalopportunity.
o For laboratories having PART A and PART B: Students are allowed to
pick one experiment from PART A and one experiment from PART B,
with equalopportunity.
Change of experiment is allowed only once and marks allotted for procedure to be made
zero of the changed part only.
MarksDistribution(Courseedtochangeinaccoradancewithuniversityregulations)
INTRODUCTION
INTRODUCTION TO DATABASE
What is Database?
A database is a separate application that stores a collection of data. Each database has one or
more distinct APIs for creating, accessing, managing, searching, and replicating the data it holds.
now a days we use relational database management systems (RDBMS) to store and manager
huge volume of data.
RDBMS Terminology:
Table: A table is a matrix with data. A table in a database looks like a simple spreadsheet.
Column: One column (data element) contains data of one and the same kind, for example the column
postcode. or phone numbers
Row: A row (= tuple, entry or record) is a group of related data, for example the data of one
subscription.
Primary Key: A primary key is unique. A key value can not occur twice in one table. With a key you
can find at most one row.
Foreign Key: A foreign key is the linking pin between two tables.
Compound Key: A compound key (composite key) is a key that consists of multiple columns, because
one column is not sufficiently unique.
Referential Integrity: Referential Integrity makes sure that a foreign key value always points to an
existing row
DDL or Data Definition Language actually consists of the SQL commands that can be used to
to create and modify the structure of database objects in a database. These database objects include
views, schemas, tables, indexes, etc.
Some examples:
CREATE - to create objects in the database
ALTER - alters the structure of the database
DROP - delete objects from the database
DML is Data Manipulation Language statements: which areused to interact with a database by deleting,
inserting, retrieving, or updating data in the database.
Some examples:
SELECT - retrieve data from the a database
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
DCL is Data Control Language statements: which includes commands such as GRANT and REVOKE
which mainly deals with the rights, permissions and other controls of the database system.
Some examples:
GRANT-gives user’s access privileges to database.
REVOKE-withdraw user’s access privileges given by using the GRANT command.
TCL is Transaction Control Language which deals with a transaction within a database.
Some examples:
COMMIT - save work done
SAVEPOINT - identify a point in a transaction to which you can later roll back
ROLLBACK - restore database to original since the last COMMIT
SET TRANSACTION - Change transaction options like what rollback segment to use.
SQL Data Types
Each column in a database table is required to have a name and a data type.
An SQL developer must decide what type of data that will be stored inside each column when
creating a table. The data type is a guideline for SQL to understand what type of data is expected
inside of each column, and it also identifies how SQL will interact with the stored data.
MySQL uses many different data types broken into three categories
Numeric
Date and Time
String Type
DATA TYPES
NUMERIC:
INT − A normal-sized integer that can be signed or unsigned. If signed, the allowable range is
from -2147483648 to 2147483647. If unsigned, the allowable range is from 0 to 4294967295.
You can specify a width of up to 11 digits.
TINYINT − A very small integer that can be signed or unsigned. If signed, the allowable range is
from -128 to 127. If unsigned, the allowable range is from 0 to 255. You can specify a width of
up to 4 digits.
SMALLINT − A small integer that can be signed or unsigned. If signed, the allowable range is
from -32768 to 32767. If unsigned, the allowable range is from 0 to 65535. You can specify a
width of up to 5 digits.
MEDIUMINT − A medium-sized integer that can be signed or unsigned. If signed, the allowable
range is from -8388608 to 8388607. If unsigned, the allowable range is from 0 to 16777215. You
can specify a width of up to 9 digits.
BIGINT − A large integer that can be signed or unsigned. If signed, the allowable range is from -
9223372036854775808 to 9223372036854775807. If unsigned, the allowable range is from 0 to
18446744073709551615. You can specify a width of up to 20 digits.
FLOAT (M, D) − A floating-point number that cannot be unsigned. You can define the display
length (M) and the number of decimals (D). This is not required and will default to 10, 2, where 2
is the number of decimals and 10 is the total number of digits (including decimals). Decimal
precision can go to 24 places for a FLOAT.
DOUBLE (M, D) − A double precision floating-point number that cannot be unsigned. You can
define the display length (M) and the number of decimals (D). This is not required and will
default to 16, 4, where 4 is the number of decimals. Decimal precision can go to 53 places for a
DOUBLE. REAL is a synonym for DOUBLE.
DATE − A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example,
December 30th, 1973 would be stored as 1973-12-30.
TIMESTAMP − A timestamp between midnight, January 1 st, 1970 and sometime in 2037. This
looks like the previous DATETIME format, only without the hyphens between numbers; 3:30 in
the afternoon on December 30th, 1973 would be stored as 19731230153000
(YYYYMMDDHHMMSS).
YEAR (M) − Stores a year in a 2-digit or a 4-digit format. If the length is specified as 2 (for
example YEAR (2)), YEAR can be between 1970 to 2069 (70 to 69). If the length is specified as
4, then YEAR can be 1901 to 2155. The default length is 4.
STRING TYPES
This list describes the common string data types in MySQL.
CHAR (M) − A fixed-length string between 1 and 255 characters in length (for example CHAR
(5)), right-padded with spaces to the specified length when stored. Defining a length is not
required, but the default is 1.
VARCHAR (M) − A variable-length string between 1 and 255 characters in length. For
example, VARCHAR (25). You must define a length when creating a VARCHAR field.
BLOB or TEXT − A field with a maximum length of 65535 characters. BLOBs are "Binary
Large Objects" and are used to store large amounts of binary data, such as images or other types
of files. Fields defined as TEXT also hold large amounts of data. The difference between the two
is that the sorts and comparisons on the stored data are case sensitive on BLOBs and are not case
sensitive in TEXT fields. You do not specify a length with BLOB or TEXT.
CREATE TABLE
Specifies a new base relation by giving it a name, and specifying each of its attributes and
their data types
Syntax of CREATE Command:
CREATE TABLE<table name>
(<AttributeA1><Data TypeD1> [<Constraints>],
<Attribute A2><Data Type D2> [<Constraints>],
…….
<Attribute An><Data Type Dn> [<Constraints>],
[<integrity-constraint1>, <integrity-constraint k> ] );
Specifying the unique, primary key attributes, secondary keys, and referential integrity constraints
EXAMPLE OF CREATING TABLE
CREATE TABLE ORDERS
(
ORDER_ID INT (6) PRIMARY KEY,
ORDER_DATE DATE
);
Add a column
Drop a column
Change a column name
Change the data type for a column
add and drop various constraints on an existing table.including primarykey and foreignkey
For example,say the column is currently named JOB, but you decide that DESIGNATION is a
more appropriate title. The column is located on the table entitled ORDERS.
DELETING COLUMN
To delete a column in a table, use the following syntax:
RENAMING A TABLE
To rename a table, use the following syntax:
DROP TABLE
It is very easy to drop an existing MySQL table, but you need to be very careful while deleting
any existing table because the data lost will not be recovered after deleting a table.
if we wish to simply get rid of the data but not the table itself? For this, we can use the
TRUNCATE "table_name"
So, if we wanted to truncate the table called customer that we created in MYSQL , we simply
type,
Example:TRUNCATE customer
CONSTRAINTS:
Common types of constraints include the following:
Primary Key:-
A primary key is used to uniquely identify each row in a table. It can either be part of the
actual record itself, or it can be an artificial field (one that has nothing to do with the
actual record).
A primary key can consist of one or more fields on a table. When multiple fields are used
as a primary key, they are called a composite key.
Primary keys can be specified either when the table is created (using CREATE TABLE)
or by changing the existing table structure (using ALTER TABLE).
Below are examples for specifying a primary key when creating a table:
Example :
CREATE TABLE ORDERS (ORDER_ID INT (6) PRIMARY KEY,ORDER_DATE DATE);
Note: - Before using the ALTER TABLE command to add a primary key, you'll need to make sure
that the field is defined as 'NOT NULL' -- in other words, NULL cannot be an accepted value for
that field.and column values must be unique
To drop a PRIMARY KEY constraint in Table ORDERS, use the following MYSQL:syntax
FOREIGN KEY
A foreign key is a field (or fields) that points to the primary key of another table.
The purpose of the foreign key is to ensure referential integrity of the data. In other
words, only values that are supposed to appear in the database are permitted
For example, say we have two tables, a CUSTOMER table that includes all customer
data, and an ORDERS table that includes all customer orders. The constraint here is that
all orders must be associated with a customer that is already in the CUSTOMER table.
In this case, we will place a foreign key on the ORDERS table and have it relate to the
primary key of the CUSTOMER table. This way, we can ensure that all orders in the
ORDERS table are related to a customer in the CUSTOMER table. .In other words, the
ORDERS table cannot contain information on a customer that is not in the CUSTOMER
table.
Table ORDERS
column name characteristic
Order_ID Primary Key
Order_Date Date
Customer_SID Foreign Key
Amount Decimal(10,2)
In the below example, the Customer_SID column in the ORDERS table is a foreign keypointing
to the SID column which is primary key in the CUSTOMER table.
Below we show examples of how to specify the foreign key when creating the ORDERS table:
CREATE TABLE ORDERS
(
Order_ID int,
Order_Date date,
Customer_SID int,
Amount double,
Primary Key (Order_ID),
Foreign Key (Customer_SID) references CUSTOMER(SID)
);
NOT NULL Constraint:-By default, a column can hold NULL. If you don’t want to allow or
store NULL value in a column, you will want to place a constraint on this column specifying that
NULL is now not an allowable value.
DEFAULT Constraint:- The DEFAULT constraint provides a default value to a column when
the INSERT INTO statement does not provide a specific value.
UNIQUE Constraint:-The UNIQUE constraint ensures that all values in a column are distinct.
CHECK Constraint:-The CHECK constraint ensures that all values in a column satisfy certain
conditions. Once defined, the database will only insert a new row or update an existing row if the
new value satisfies the CHECK constraint. The CHECK constraint is used to ensure data quality
Query 10: Retrieve the names of all employees who do not have supervisors.
Q10: SELECT FNAME, LNAME FROM EMPLOYEE
WHERE SUPERSSN IS NULL
Note: If a join condition is specified, tuples with NULL values for the join attributes are not
included in the result
Dept. of CSE, ATMECE, Mysore Page 16
DBMS Laboratory with mini Project 21CSL55
AGGREGATE FUNCTIONS
Include COUNT, SUM, MAX, MIN, and AVG
Query 11: Find the maximum salary, the minimum salary, and the average salary among all
employees.
Q11: SELECT MAX (SALARY), MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE
Note: Some SQL implementations may not allow more than one function in the SELECT-clause
Query 12: Find the maximum salary, the minimum salary, and the average salary among
employees who work for the 'Research' department.
Q12: SELECT MAX (SALARY), MIN(SALARY), AVG(SALARY) FROM
EMPLOYEE, DEPARTMENT WHERE DNO=DNUMBER ANDDNAME='Research'
Queries 13 and 14: Retrieve the total number of employees in the company (Q13), and the number
of employees in the 'Research' department (Q14).
Q13: SELECT COUNT (*) FROM EMPLOYEE
Q14: SELECT COUNT (*) FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME='Research’
GROUPING
In many cases, we want to apply the aggregate functions to subgroups of tuples in a relation
Each subgroup of tuples consists of the set of tuples that have the same value for the
groupingattribute(s)
The function is applied to each subgroupindependently
SQL has a GROUP BY-clause for specifying the grouping attributes, which must also
appear in theSELECT-clause
Query 15: For each department, retrieve the department number, the number of employees
in the department, and their averagesalary.
Q15: SELECT DNO, COUNT (*), AVG (SALARY)
FROM EMPLOYEE GROUP BY DNO
In Q15, the EMPLOYEE tuples are divided into groups. Each group having the same value
for the grouping attributeDNO
The COUNT and AVG functions are applied to each such group of tuplesseparately
The SELECT-clause includes only the grouping attribute and the functions to be applied on
each group oftuples
Query 19: Retrieve all employees who were born during the 1950s.
Here, '5' must be the 8th character of the string (according to our format for date), so the BDATE
valueis' 5_', with each underscore as a place holder for a single arbitrarycharacter.
Q19: SELECT FNAME, LNAME
FROM EMPLOYEE WHERE BDATELIKE' 5_’
Note: The LIKE operator allows us to get around the fact that each value is considered atomic and
indivisible. Hence, in SQL, character string attribute values are not atomic
Dept. of CSE, ATMECE, Mysore Page 18
DBMS Laboratory with mini Project 21CSL55
ARITHMETIC OPERATIONS
The standard arithmetic operators '+', '-'. '*', and '/' (for addition, subtraction, multiplication, and
division, respectively) can be applied to numeric values in an SQL query result
Query 20: Show the effect of giving all employees who work on the 'ProductX' project a 10%
raise.
Q20: SELECT FNAME, LNAME, 1.1*SALARY
FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE SSN=ESSN
AND PNO=PNUMBER AND PNAME='ProductX’
ORDER BY
The ORDER BY clause is used to sort the tuples in a query result based on the values of some
attribute(s)
Query 21: Retrieve a list of employees and the projects each works in, ordered by the
employee's department, and within each department ordered alphabetically by employee
lastname.
Q21: SELECT DNAME, LNAME, FNAME, PNAME
FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT
WHERE DNUMBER=DNO
AND SSN=ESSN
AND PNO=PNUMBER ORDER
BY DNAME, LNAME
The default order is in ascending order of values. We can specify the keyword DESC if we want a
descending order; the keyword ASC can be used to explicitly specify ascending order, even though it is
thedefault
Ex: ORDER BY DNAME DESC, LNAME ASC, FNAME ASC
MORE EXAMPLE QUERIES:
Query 22: Retrieve the names of all employees who have two or more dependents.
Q22: SELECT LNAME, FNAME FROM
EMPLOYEE WHERE (SELECT COUNT (*) FROM DEPENDENT WHERE
SSN=ESSN) ≥ 2);
Query 23: List the names of managers who have least one dependent.
Q23: SELECT FNAME, LNAME
FROM EMPLOYEE
Example: Insert a tuple for a new EMPLOYEE for whom we only know the FNAME, LNAME, and
SSN attributes.
INSERT INTO EMPLOYEE (FNAME, LNAME, SSN)VALUES ('Richard', 'Marini',
'653298653')
Important Note: Only the constraints specified in the DDL commands are automatically enforced by
the DBMS when updates are applied to the database. Another variation of INSERT allows insertion of
multiple tuples resulting from a query into a relation
Example: Suppose we want to create a temporary table that has the name, number of employees, and
total salaries for each department. A table DEPTS_INFO is created first, and is loaded with the
summary information retrieved from the database by the query.
CREATE TABLE DEPTS_INFO(DEPT_NAME VARCHAR (10),NO_OF_EMPS INT,
TOTAL_SAL INT);
INSERT INTO DEPTS_INFO (DEPT_NAME, NO_OF_EMPS, TOTAL_SAL)
SELECT DNAME, COUNT (*), SUM (SALARY) FROM DEPARTMENT, EMPLOYEE
WHERE DNUMBER=DNO GROUP BY DNAME ;
Note: The DEPTS_INFO table may not be up-to-date if we change the tuples in either the
DEPARTMENT or the EMPLOYEE relations after issuing the above. We have to create a view
(see later) to keep such a table up to date.
DELETE
Removes tuples from a relation. Includes a WHERE-clause to select the tuples to bedeleted
Referential integrity should beenforced
So to handle these problems, we should analyze and decompose the relations with redundant data into
smaller, simpler, and well-structured relations that are satisfy desirable properties. Normalization is a
process of decomposing the relations into relations with fewer attributes.
What is Normalization?
Normalization is the process of organizing the data in the database.
Normalization is used to minimize the redundancy from a relation or set of relations. It is also
used to eliminate undesirable characteristics like Insertion, Update, and Deletion Anomalies.
Normalization divides the larger table into smaller and links them using relationships.
The normal form is used to reduce redundancy from the database table.
Advantages of Normalization
Normalization helps to minimize data redundancy.
Greater overall database organization.
Data consistency within the database.
Much more flexible database design.
Enforces the concept of relational integrity.
Disadvantages of Normalization
You cannot start building the database before knowing what the user needs.
It is very time-consuming and difficult to normalize relations of a higher degree.
Careless decomposition may lead to a bad database design, leading to serious problems.
Normal Forms
There are four types of normal forms that are usually used in relational databases as you can see in
the following figure:
NORMAL FORMS
2. 2NF: A relation is in 2NF if it is in 1NF and all non-key attributes are fully functional
dependent on the candidate key.
4. BCNF: A relation is in BCNF if it is in 3NF and for every Functional Dependency, LHS is the
super key.
To understand the above-mentioned normal forms, we first need to have an understanding of the
functional dependencies.
Functional dependency is a relationship that exists between two sets of attributes of a relational table
where one set of attributes can determine the value of the other set of attributes. It is denoted by X ->
Y, where X is called a determinant and Y is called dependent.
There are various levels of normalizations. Let’s go through them one by one:
Let’s take an example of a relational table <EmployeeDetail> that contains the details of the
employees of the company.
<EmployeeDetail>
Here, the Employee Phone Number is a multi-valued attribute. So, this relation is not in 1NF.
To convert this table into 1NF, we make new rows with each Employee Phone Number as a new row
as shown below
<EmployeeDetail>
For a relational table to be in second normal form, it must satisfy the following rules:
The table must be in first normal form.
It must not contain any partial dependency, i.e., all non-prime attributes are fully functionally
dependent on the primary key.
If a partial dependency exists, we can divide the table to remove the partially dependent attributes and
move them to some other table where they fit in well.
<EmployeeProjectDetail>
In the above table, the prime attributes of the table are Employee Code and Project ID. We have partial
dependencies in this table because Employee Name can be determined by Employee Code and Project
Name can be determined by Project ID. Thus, the above relational table violates the rule of 2NF.
The prime attributes are those which are part of one or more candidate keys.
To remove partial dependencies from this table and normalize it into second normal form, we can
decompose the <EmployeeProjectDetail> table into the following three tables:
<EmployeeDetail>
<EmployeeProject>
The relations in 2NF are clearly less redundant than relations in 1NF. However, the decomposed
relations may still suffer from one or more anomalies due to the transitive dependency. We will
remove the transitive dependencies in the Third Normal Formalization
<EmployeeDetail>
<EmployeeLocation>
Thus, we’ve converted the <EmployeeDetail> table into 3NF by decomposing it into
<EmployeeDetail> and <EmployeeLocation> tables as they are in 2NF and they don’t have any
transitive dependency.
The 2NF and 3NF impose some extra conditions on dependencies on candidate keys and remove
redundancy caused by that. However, there may still exist some dependencies that cause redundancy
in the database. These redundancies are removed by a more strict normal form known as BCNF.
A superkey is a set of one or more attributes that can uniquely identify a row in a database table.Let us
<EmployeeProjectLead>
The above table satisfies all the normal forms till 3NF, but it violates the rules of BCNF because the
candidate key of the above table is {Employee Code, Project ID}.
For the non-trivial functional dependency, Project Leader -> Project ID, Project ID is a prime attribute
but Project Leader is a non-prime attribute. This is not allowed in BCNF.
To convert the given table into BCNF, we decompose it into three tables:
<EmployeeProject>
Thus, we’ve converted the <EmployeeProjectLead> table into BCNF by decomposing it into
<EmployeeProject> and <ProjectLead> tables.
The ACID properties are meant for the transaction that goes through a different group of tasks, and
there we come to see the role of the ACID properties.
In this section, we will learn and understand about the ACID properties. We will learn what these
properties stand for and what does each property is used for. We will also understand the ACID
properties with the help of some examples.
ACID Properties
The expansion of the term ACID defines for:
ACID PROPERTIES
1)Atomicity: The term atomicity defines that the data remains atomic. It means if any operation is
performed on the data, either it should be performed or executed completely or should not be executed
at all. It further means that the operation should not break in between or execute partially. In the case
of executing operations on the transaction, the operation should be completely executed and not
partially.
Example: If Yogesh has account A having $30 in his account from which he wishes to send $10 to
Vinay's account, which is B. In account B, a sum of $ 100 is already present. When $10 will be
transferred to account B, the sum will become $110. Now, there will be two operations that will take
place. One is the amount of $10 that Yogesh wants to transfer will be debited from his account A, and
the same amount will get credited to account B, i.e., into Vinay's account. Now, what happens - the
first operation of debit executes successfully, but the credit operation, however, fails. Thus, in Yogesh
account A, the value becomes $20, and to that of Vinay's account, it remains $ 100 as it was
previously present.
In the above diagram, it can be seen that after crediting $10, the amount is still $100 in account B. So,
it is not an atomic transaction.
The below diagram shows that both debit and credit operations are done successfully. Thus the
transaction is atomic.
Thus, when the amount loses atomicity, then in the bank systems, this becomes a huge issue, and so
the atomicity is the main focus in the bank systems.
Example:
In the above figure, there are three accounts, A, B, and C, where A is making a transaction T one by
one to both B & C. There are two operations that take place, i.e., Debit and Credit. Account A firstly
debits $50 to account B, and the amount in account A is read $300 by B before the transaction. After
the successful transaction T, the available amount in B becomes $150. Now, A debits $20 to account
C, and that time, the value read by C is $250 (that is correct as a debit of $50 has been successfully
done to B). The debit and credit operation from account A to C has been done successfully. We can
see that the transaction is done successfully, and the value is also read correctly. Thus, the data is
consistent. In case the value read by B and C is $300, which means that data is inconsistent because
when the debit operation executes, it will not be consistent.
4)Isolation: The term 'isolation' means separation. In DBMS, Isolation is the property of a database
where no data should affect the other one and may occur concurrently. In short, the operation on one
database should begin when the operation on the first database gets complete. It means if two
operations are being performed on two different databases, they may not affect the value of one
another. In the case of transactions, when two or more transactions occur simultaneously, the
consistency should remain maintained. Any changes that occur in any particular transaction will not be
seen by other transactions until the change is not committed in the memory.
4) Durability: Durability ensures the permanency of something. In DBMS, the term durability ensures
that the data after the successful execution of the operation becomes permanent in the database. The
durability of the data should be so perfect that even if the system fails or leads to a crash, the database
still survives. However, if gets lost, it becomes the responsibility of the recovery manager for ensuring
the durability of the database. For committing the values, the COMMIT command must be used every
time we make changes.
Therefore, the ACID property of DBMS plays a vital role in maintaining the consistency and
availability of data in the database.
Thus, it was a precise introduction of ACID properties in DBMS. We have discussed these properties
in the transaction section also.
Arithmetic operators
Comparison operators
Logical operators
Operators used to negate conditions
1.Arithmetic Operators
In MySQL, arithmetic operators are used to perform the arithmetic operations as described below.
SELECT 17 * 5;
Output
85
SELECT 49 / 7;
Output
7.0000
SELECT 21 % 5;
Output
1
2.Comparison Operators
The comparison operators in MySql are used to compare values between operands and
return true or false according to the condition specified in the statement.
3. Logical Operators
The logical operators used in MySQL are shown below.
Operator Description
BETWEEN It is used to search within a set of values, by the minimum value and maximum
value provided.
It is used to search for the presence of a row in a table which satisfies a certain
EXISTS
condition specified in the query.
It is used to combine multiple conditions in a statement by using the WHERE
OR
clause.
It allows the existence of multiple conditions in an SQL statement’s WHERE
AND
clause.
It reverses the meaning of the logical operator with which it is used. (Examples:
NOT
NOT EXISTS, NOT BETWEEN, NOT IN, etc.)
ANY It compares a value to any value in the list according to the condition specified.
LIKE It uses wildcard operators to compare a value to similar values.
IS NULL It compares a value with a NULL value.
UNIQUE It searches for every row of a specified table for uniqueness (no duplicates).
Let us take an example of CUSTOMERtable as shown below to understand how to use the comparison
operators as stated above while performing MySQL queries.
Pre-RequisiteData:
CUSTOMERTABLE
Let us use the different comparison operators to query the CUSTOMER table as shown below.
Queries:
Q1.Writeaquerytofindthesalaryofapersonwhereageis less than or equal to 26and salary greater
than or equal 25000fromCustomer table
SELECT *FROMCUSTOMER WHERE AGE <=26ANDSALARY>=25000;
Output:
Q2. Write a query to find the salary of a person where age is less than or equal to 26 or salary
greater than or equal to 33000 from customer table.
SELECT *FROMCUSTOMER WHERE AGE <=26orSALARY>=33000;
Output:
Q3.Write a query to find the name of customer whose name start with n(using pattern
matching)
Q4.Write a query to find the name of customer ending with th(using pattern matching)
SELECT * FROMCUSTOMER WHERE NAME LIKE '%th';
Output:
Q5. Write a query to find the customer details using “IN” operator where age can be 25 and 27.
SELECT*FROMCUSTOMER WHEREAGEIN (25,27);
Output:
Q7. Write a query to find the customer details where age is not null
Syntax:
The following are the syntax to use aggregate functions in MySQL:
Count():
Count(*): Returns total number of records .
Count(salary): Return number of Non Null values over the column salary.
Count(Distinct Salary): Return number of distinct Non Null values over the column salary
Sum():
sum(salary): Sum all Non Null values of Column salary
sum(Distinct salary): Sum of all distinct Non-Null values
Avg():
Avg(salary) = Sum(salary) / count(salary) = 310/5
Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary)
Q1. Write a query to find the average salary of employees in customer table
SELECT AVG(salary) FROM CUSTOMER;
Output:
Q4. Write a query to find the minimum salary of employees in customer table
SELECT MIN(salary) FROM CUSTOMER;
Output:
Q5. Write a query to find the sum of salary of all employees in customer table
SELECT SUM (salary)FROM CUSTOMER;
GROUP BY Clause
The MYSQL GROUP BY Clause is used to collect data from multiple records and group the
result by one or more column. It is generally used in a SELECT statement.
You can also use some aggregate functions like COUNT, SUM, MIN, MAX, AVG etc. on the
grouped column.
Pre-RequisiteData:
employeesTABLE
We can also use the count() function with the GROUP BY clause that returns the count of the
element in each group. For example, the following statement returns the number of employee
staying in each city:
MySQLsum()FunctionwithHAVINGandORDERBYClause
Letussee anotherclausethatuses ORDERBY andHavingclausewith thesum()unction.Execute the
following statement that gives the sum of salary who has at least two city and sum of salary should be
greaten or equal to 100000 annd sortsthem basedonthesalary
In Above Ouput ,salary can sorted in descending order by salary using order by clause
Select city,sum(salary) from employee group by city having sum(salary)>=100000
Order by sum(salary) desc;
MOVIE_ID MOVIE_NAME
1000 SHOLAY
1001 ITTEFAQ
1002 TEESRI MANZIL
1003 JEWEL THIEF
1004 CARAVAN
1005 GUMNAAM
INNER JOIN CONSISTING OF WHERE CONDITION AND ACTOR NAME FIELDS ARE
HAVING NULL VALUE
SELECT MOVIE_NAME, ACTOR_NAME,ACTOR_ID FROM MOVIES M INNER JOIN
ACTORS A ON M.MOVIE_ID=A.MOVIE_ID WHERE ACTOR_NAME='NULL';
Executing the above script in MySQL workbench gives us the following results.
OUTER-JOIN
A full outer join, or full join, which is not supported by the popular MySQL database management
system, However, can customized selection of un-matched rows e.g, selecting unmatched row from
first table or second table by sub-types: LEFT OUTER JOIN and RIGHT OUTER JOIN.
It can detect records having no match in joined table. It retuns NULL values for records of joined
table if no match is found.
LEFT JOIN
The LEFT JOIN retuns all the rows from the table on the left even if no matching rows have been
found in the table on the right. Where no matches have been found in the table on the right, NULL
is returned.
Select * FROM Table1 A LEFT OUTER JOIN Table2 B On A.<PrimaryKey>=B.<ForeignKey>;
SELECT MOVIE_NAME, ACTOR_NAME,ACTOR_ID FROM MOVIES M LEFT
OUTER JOIN ACTORS A ON M.MOVIE_ID=A.MOVIE_ID;
RIGHT JOIN
RIGHT JOIN is obviously the opposite of LEFT JOIN. The RIGHT JOIN retuns all the columns
from the table on the right even if no matching rows have been found in the table on the left.
Where no matches have been found in the table on the left, NULL is returned.
Select * FROM Table1 A RIGHT OUTER JOIN Table2 B on A.<PrimaryKey>=B.<ForeignKey>;
SELECT MOVIE_NAME, ACTOR_NAME,ACTOR_ID FROM MOVIES M RIGHT
OUTER JOIN ACTORS A ON M.MOVIE_ID=A.MOVIE_ID;
Executing the above script in MySQL workbench gives the following results.
Syntax:
There is not any general syntax for Subqueries. However, Subqueries are seen to be used most
frequently with SELECT statement as shown below:
SELECT column_name FROM table_name WHERE column_name expression operator
( SELECT COLUMN_NAME from TABLE_NAME WHERE ... );
Below is sample table StudentDetails and StudentSection we have created to demonstrate
working of subquesry
Query2: To update name from StudentDetails table whose rollno is same as that in
StudentSection table and having name as Nitin by Using subquery
UPDATE StudentDetails SET NAME=’Nitin Jain’
WHERE ROLL_NO IN(SELECT ROLL_NOFROM StudentSection where NAME=’Nitin’);
JOINs are faster than a subquery and it is very rare that the opposite.
In JOINs the RDBMS calculates an execution plan, that can predict, what data should be
loaded and how much it will take to processed and as a result this process save some times,
unlike the subquery there is no pre-process calculation and run all the queries and load all their
data to do the processing.
A JOIN is checked conditions first and then put it into table and displays; where as a subquery
take separate temp table internally and checking condition.
When joins are using, there should be connection between two or more than two tables and
each table has a relation with other while subquery means query inside another query, has no
need to relation, it works on columns and conditions
Let's now look at the basic syntax used to create a view in MySQL.
CREATE VIEW `view_name` AS SELECT statement;
WHERE
"CREATE VIEW “view_name" tells MySQL server to create a view object in the
database
"AS SELECT statement" is the SQL statements to be packed in the views. It can be a
SELECT statement can contain data from one table or multiple tables.
Tables_in_naveen
VW_BOOKDETAILS
VW_ORDERS
VW_BOOK1
VW_BOOK2
Example2-Simple View
CREATE VIEW VW_PUBLICATION AS SELECT PUB_YEAR FROM BOOK;
DROPING VIEWS
The DROP command can be used to delete a view from the database that is no longer required.
The basic syntax to drop a view is as follows.
DROP VIEW VIEWNAME;
DROP VIEW V_PUBLICATION;
You may want to use views primarily for following 3 reasons
Ultimately , you will use your SQL knowledge , to create applications , which will use a
database for datarequirements. It's recommended that you use VIEWS of the original table
structure in your application instead of using the tables themselves. This ensures that when you
refactor your DB, your legacy code will see the orignal schema via the view without breaking
the application.
VIEWS increase re-usability. You will not have to create complex queries involving joins
repeatedly. All the complexity is converted into a single line of query use VIEWS. Such
condensed code will be easier to integrate in your application. This will eliminates chances of
typos and your code will be more readable.
VIEWS help in data security. You can use views to show only authorized information to
users and hidesensitive data like credit card numbers, pass
You can also pass parameters to a stored procedure, so that the stored procedure can act based on
the parameter value(s) that is passed.
A procedure can return one or more than one value through parameters or may not return at all.
The procedure can be used in SQL queries.
Creating a procedure
Syntax
CREATE PROCEDURE procedure_name
(
parameter datatype ,
parameter datatype
)
BEGIN
Declaration_section
Executable_section
END;
Parameter
procedure_name: name of the stored procedure.
Parameter: number of parameters. It can be one or more than one.
declaration_section: all variables are declared.
executable_section: code is written here.
A variable is a named data object whose value can change during the stored procedure execution.
We typically use the variables in stored procedures to hold the immediate results. These variables
are local to the stored procedure. You must declare a variable before using it.
DELIMITER //
CREATE PROCEDURE sp_name
(
p_1 INT
)
BEGIN
...code goes here...
END //
DELIMITER ;
The main body of the stored procedure goes in between the BEGIN and END keywords. These
keywords are used for writing compound statements. A compound statement can contain multiple
statements, and these can be nested if required. Therefore, you can nest BEGIN and END blocks.
In most cases, you will also need to surround the CREATE PROCEDURE statement
with DELIMITER commands and change END; to END //. Like this:
About the DELIMITER Command
The first command is DELIMITER // , which is not related to the stored procedure syntax.
The DELIMITER statement changes the standard delimiter which is a semicolon ( ; ) to another.
In this case, the delimiter is changed from the semicolon( ; ) to double-slashes(//) We need to
change delimiter from ; to //.Because we want to pass the stored procedure to the server as a whole
rather than letting mysql tool interpret each statement at a time.
Following the END keyword, we use the delimiter // to indicate the end of the stored procedure.
The last command ( DELIMITER; )changes the delimiter back to the semicolon (;).
How to Execute a Stored Procedure
Call sp_procedure_name();
Writing the first MySQL stored procedure
Here we are creating sample table named employee
Example
We are going to develop a simple stored procedure named SP_getEmployee to help you get
familiar with the syntax. The SP_getEmployee() stored procedure selects all employee information
from the employee table.:
DELIMITER $$
DROP PROCEDURE IF EXISTS SP_getEmployee $$
CREATE PROCEDURE SP_getEmployee()
BEGIN
SELECT * FROM employee;
END$$
Execute the stored procedure above as follows:
call SP_getEmployee();
IN – is the default mode. When you define an IN parameter in a stored procedure, the calling
program has to pass an argument to the stored procedure. In addition, the value of an IN parameter
is protected. It means that even the value of the IN parameter is changed inside the stored
procedure, its original value is retained after the stored procedure ends. In other words, the stored
procedure only works on the copy of the IN parameter.
OUT – the value of an OUT parameter can be changed inside the stored procedure and its new
value is passed back to the calling program. Notice that the stored procedure cannot access the
initial value of the OUT parameter when it starts.
INOUT – an INOUT parameter is a combination of IN and OUT parameters. It means that the
calling program may pass the argument, and the stored procedure can modify
the INOUT parameter, and pass the new value back to the calling program.
The following example shows a simple stored procedure that uses an INOUT parameter and an IN
parameter. The user will supply 'M' or 'F' through IN parameter to count a number of male or female
gender from STUDENT table. The INOUT parameter (countgender) will return the result to a user.
Here is the code and output of the procedure
DELIMITER $$
DROP PROCEDURE IF EXISTS sp_ studentcountgender $$
create procedure sp_studentcountgender
(
IN studentgender char(1),
OUT countgender int
)
begin
select COUNT(GENDER) INTO countgender FROM STUDENT WHERE
GENDER=studentgender;
END$$
DELIMITER ;
This an example of updating information into table employee through stored procedure
// UPDATE STORED PROCEDURE
DELIMITER $$
DROP PROCEDURE IF EXISTS sp_UpdatetEmployee $$
CREATE PROCEDURE sp_UpdatetEmployee
(
IN emp_id INT(10),
IN Name VARCHAR(255),
IN Designation VARCHAR(255),
IN Salary float(10,2)
)
BEGIN
UPDATE EMPLOYEE SET Name= Name, Designation= Designation, Salary= Salary WHERE
employee_id = emp_id ;
END$$
Previously we had written separate stored procedure for inserting and updating information in
employee table.now we can write single stored procedure which includes both Inserting and
updating information in employee table.
This an example of both Inserting and updating information into table employee through single
stored procedure
// INSERT AND UPDATE STORED PROCEDURE
DELIMITER $$
DROP PROCEDURE IF EXISTS SP_InsertUpdateemployee $$
SP_InsertUpdateemployee
Variables scope
A variable has its own scope that defines its lifetime. If you declare a variable inside a stored
procedure, it will be out of scope when the END statement of stored procedure reaches.
If you declare a variable inside BEGIN END block, it will be out of scope if the END is reached.
You can declare two or more variables with the same name in different scopes because a variable is
only effective in its own scope. However, declaring variables with the same name in different
scopes is not good programming practice.
A variable whose name begins with the @ sign is a session variable. It is available and accessible
until the session ends.
Declare a Variable:
DECLARE var_name [, var_name] ... type [DEFAULT value]
To provide a default value for a variable, include a DEFAULT clause. The value can be specified
as an expression; it need not be constant. If the DEFAULT clause is missing, the initial value is
NULL.
Faster Query Execution : Since stored procedures are Parsed, Compiled at once, and the
executable is cached in the Database. Therefore if same query is repeated multiple times then
Database directly executes the executable and hence Time is saved in Parse,Compile etc.
Secure: MySQL stored procedures are secure because the database administrator can grant
appropriate permissions to applications that access stored procedures in the database without
giving any permissions on the underlying database table
It is difficult to debug stored procedures. Only a few database management systems allow you to
debug stored procedures. Unfortunately, MySQL does not provide facilities for debugging stored
procedures.
Memory usage increased: If we use many stored procedures, the memory usage of every
connection that is using those stored procedures will increase substantially.
A trigger is a set of SQL Statements that are run automatically when a specified change operation
(SQL INSERT, UPDATE, or DELETE statement) is performed on a specified table.
A SQL trigger is a special type of stored procedure. It is special because it is not called directly
like a stored procedure. The main difference between a trigger and a stored procedure is that a
trigger is called automatically when a data modification event is made against a table whereas a
stored procedure must be called explicitly.
A trigger can be defined to be invoked either before or after the data is changed by INSERT,
UPDATE or DELETE statement
Triggers are useful for tasks such as enforcing business rules, validating input data, and keeping an
audit trail.A trigger can be set to activate either before or after the trigger event.For example, you
can have a trigger activate before each row that is inserted into a table or after each row that is
updated
It is important to understand the SQL trigger’s advantages and disadvantages so that you can use it
appropriately. In the following sections, we will discuss the advantages and disadvantages of using
SQL triggers.
SQL triggers only can provide an extended validation and they cannot replace all the validations.
Some simple validations have to be done in the application layer. For example, you can validate
user’s inputs in the client side by using JavaScript or on the server side using server-side scripting
languages such as JSP, PHP, ASP.NET, Perl.
SQL triggers are invoked and executed invisible from the client applications, therefore, it is
difficult to figure out what happens in the database layer.
SQL triggers may increase the overhead of the database server.
Trigger_name is the name of the trigger which must be put after CREATE TRIGGER statement.
The naming convention for trigger_name can be like [trigger time]_[table name]_[trigger event]. For
example, before_student_update or after_student_insert can be a name of the trigger.
Trigger_time is the time of trigger activation and it can be BEFORE or AFTER. We must have to
specify the activation time while defining a trigger. We must to use BEFORE if we want to process
action prior to the change made on the table and AFTER if we want to process action post to the
change made on the table.
Trigger_event can be INSERT, UPDATE or DELETE. This event causes the trigger to be invoked.
A trigger only can be invoked by one event. To define a trigger that is invoked by multiple events,
we have to define multiple triggers, one for each event.
Table_name is the name of the table. Actually, a trigger is always associated with a specific table.
Without a table, a trigger would not exist hence we have to specify the table name after the ‘ON’
keyword.
BEGIN…END is the block in which we will define the logic for the trigger.
Syntax:
Parameter:
trigger_name: name of the trigger to be created.
AFTER UPDATE: It points the trigger update query is executed.
table_name: name of the table in which a trigger is created.
Syntax:
Parameter:
trigger_name: name of the trigger to be created.
AFTER/BEFORE DELETE: It points the trigger after/before delete query is executed.
table_name: name of the table in which a trigger is created.
AUDIT TRACKING
Above we have two scripts for creating two table Employee_Details and Employee_Details_Audit.
Both tables have same no of column names,same column name and same date type.In second
table,Employee_Details_Audit keeps track of what kind of operations are perdormed on table
Employee_Details and any insert ,update and delete operation value are stored in
Employee_Details_Audit
TRIGGER EXAMPLE 1
EXAMPLE OF CREATING AFTER INSERT TRIGGER FOR AUDIT PURPOSE
TRIGGER EXAMPLE 2
TRIGGER EXAMPLE 2
TRIGGER EXAMPLE 3
Write a Trigger To Calculate the FinalIA (average of best two test marks) and update the
correspondingtable for all students By Using Trigger.
DELIMITER $$
DROP trigger IF EXISTS trg_insertbefore_IAMARKS $$
CREATE TRIGGER trg_insertbefore_IAMARKS
BEFORE INSERT ON IAMARKS
FOR EACH ROW
BEGIN
SETNEW.FINALIA=GREATEST(NEW.TEST1+NEW.TEST2,NEW.TEST2+NEW.TEST3,
NEW.TEST1+NEW.TEST3)/2;
END$$
Below is insert script for Student Info and marks into table IAMARKS
Please note that we are inserting 0 marks into table IAMARKS containing columnnameFINALIA.
Above ,we have written trigger name before_IAMARKS_insert on IAMARKS table which
automatically calculates FINALIA by using Greatest function and inserts intovalues into
FINALIA column of table IAMARKS while trying to insert record on IAMARKS
TRIGGER EXAMPLE 5
DELIMITER $$
DROP trigger IF EXISTS increment_Salary_Employee $$
CREATE TRIGGER increment_Salary_Employee
BEFORE insert ON employee
FOR EACH ROW
IF NEW.Salary>20000 and NEW.Salary<40000
THEN
SET NEW.salary=NEW.salary*1.1;
ELSEIF NEW.Salary>=40000 and NEW.Salary<90000
THEN
SET NEW.Salary=NEW.Salary*1.2;
END IF;
END$$
Dept. of CSE, ATMECE, Mysore Page 82
DBMS Laboratory with mini Project 21CSL55
Above trigger increment_Salary_Employee is written on table employee.this trigger checks salary of
employee table during insertion if salary is greater than 20000 and salary is lesser than 40000,it
automatically increments salary by 10%.if salary is greater than or equal to 40000 and salary is lesser
than 90000,salary is automatically incremented by 20%
Here is snapshot of output of trigger increment_Salary_Employee fired on Employee table when any
records is inserted into table Employee
TRIGGER EXAMPLE 6
DELIMITER $$
DROP trigger IF EXISTS trg_insertbefore_trimupper $$
CREATE TRIGGER trg_insertbefore_trimupper
BEFORE INSERT ON employee
FOR EACH ROW
BEGIN
SET NEW.Name = UPPER(NEW.Name);
SET NEW.Designation = UPPER(NEW.Designation);
END IF;
END$$
Below is screen shot for creating simple table people which has 2 columns age and name
Above trigger beforeinsert _agecheck is created on table people which checks age being inserted into
Table people if age is less than 0 or negative values ,it automatically insert age valeue has 0.if we are
trying to insert into table people suppose age value is greater than 100,then automatically inserts 60 as
default value in age column of people table.
Above trigger beforeupdate_agecheck is created on table people which checks age being updated into
Table people if age is less than 0 or negative values ,it automatically updates age valeue has 0. suppose
if we are trying to update age value is greater than 100,then automatically updates 60 in age column of
people table.
In this syntax:
First, specify the name of the trigger that you want to drop after the DROP TRIGGER keywords.
Second, specify the name of the schema to which the trigger belongs. If you skip the schema
name, the statement will drop the trigger in the current database.
Third, use IF EXISTS option to conditionally drops the trigger if the trigger exists. The IF
EXISTS clause is optional.
Program Objectives:
This course will enable students to
Foundation knowledge in database concepts, technology and practice to groomstudents
into well-informed database applicationdevelopers.
Strong practice in SQL programming through a variety of databaseproblems.
Develop database applications using front-end tools and back-endDBMS.
DESC BOOK
DESC BOOK_AUTHORS;
DESC PUBLISHER;
DESC BOOK_COPIES
DESC CARD;
DESC LIBRARY_PROGRAMME;
AUTHOR_NAME BOOK_ID
NAVATHE 1
NAVATHE 2
ULLMAN 3
CHARLES 4
GALVIN 5
CARD NO
101
102
103
104
105
NO_
BOOK_ TITLE PUBLISHER_ AUTHOR_ OF_COPIES PROGRAMME
ID NAME NAME _ID
NAVATHE 10 10
1 DBMS MCGRAW-HILL
NAVATHE 5 11
1 DBMS MCGRAW-HILL
NAVATHE 2 12
2 ADBMS MCGRAW-HILL
NAVATHE 5 13
2 ADBMS MCGRAW-HILL
ULLMAN 7 14
3 CD PEARSON
CHARLES 1 11
4 ALGORITHMS MIT
GALVIN 3 10
5 OS PEARSON
2. Get the particulars of borrowers who have borrowed more than 3 books, but from Jan
2017 to Jun2017.
SELECT CARD_NO FROM BOOK_LENDING WHERE DATE_OUT
BETWEEN '2017-01-01'AND '2017-07-01' GROUP BY CARD_NO
HAVING COUNT(*)>3;
4. Partition the BOOK table based on year of publication. Demonstrate its working with a
simple query.
5. Create a view of all books and its number of copies that are currently available in the
Library.
CREATE VIEW VW_BOOKS AS SELECT B.BOOK_ID, B.TITLE, C.NO_OF_COPIES
FROM BOOK B, BOOK_COPIES C, LIBRARY_PROGRAMME L WHERE
B.BOOK_ID=C.BOOK_ID AND C.PROGRAMME_ID=L.PROGRAMME_ID;
Program Outcomes:
The students are able to
Create, Update and query on thedatabase.
Demonstrate the working of different concepts ofDBMS
Implement, analyze and evaluate the project developed for anapplication.
Program Objectives:
This course will enable students to
Foundation knowledge in database concepts, technology and practice to groomstudents
into well-informed database applicationdevelopers.
Strong practice in SQL programming through a variety of databaseproblems.
Develop database applications using front-end tools and back-endDBMS.
Solution:
Entity-Relationship Diagram
Table Creation
DESC SALESMAN;
DESC CUSTOMER;
DESC ORDERS;
Insertion of Value
2. Find the name and numbers of all salesmen who had more than onecustomer.
SELECT SALESMAN_ID,NAME
FROM SALESMAN A
WHERE 1 <(SELECT COUNT(*) FROM CUSTOMER
WHERE SALESMAN_ID=A.SALESMAN_ID)
OR
SELECT S.SALESMAN_ID,NAME, FROM CUSTOMER
C,SALESMAN S WHERE
S.SALESMAN_ID=C.SALESMAN_ID GROUP BY
C.SALESMAN_ID HAVING COUNT(*)>1
3. List all salesmen and indicate those who have and don’t have customers in their cities
(Use UNIONoperation.)
5. Demonstrate the DELETE operation by removing salesman with id 1000. All his orders
must also be deleted.
Use ON DELETE CASCADE at the end of foreign key definitions while creating child table
orders and then execute the following:
Program Outcomes:
The students are able to
Create, Update and query on thedatabase.
Demonstrate the working of different concepts ofDBMS
Implement, analyze and evaluate the project developed for anapplication.
Program Objectives:
This course will enable students to
Foundation knowledge in database concepts, technology and practice to groom students
into well-informed database applicationdevelopers.
Strong practice in SQL programming through a variety of databaseproblems.
Develop database applications using front-end tools and back-endDBMS.
Solution:
Entity-Relationship Diagram
Schema Diagram
Table Creation
CREATE TABLE ACTOR (
ACT_ID INT (5) PRIMARY KEY,
ACT_NAME VARCHAR (20),
ACT_GENDER CHAR (1));
Table Descriptions
DESC ACTOR;
DESC DIRECTOR;
DESC MOVIES;
DESC MOVIES_CAST;
MOV_ID REV_STARS
501 4
502 2
503 5
504 4
505 3
506 2
507 2
508 4
2. Find the movie names where one or more actors acted in two or more movies.
SELECT MOV_TITLE FROM MOVIES M,MOVIES_CAST MV
WHERE M.MOV_ID=MV.MOV_ID AND ACT_ID IN(SELECT ACT_ID FROM
MOVIES_CAST GROUP BY ACT_ID HAVING COUNT(ACT_ID)>1) GROUP BY
MOV_TITLE HAVING COUNT(*)>1;
3. List all actors who acted in a movie before 2000 and also in a movie after 2015 (use JOIN
operation).
SELECT ACT_NAME, MOV_TITLE, MOV_YEAR FROM ACTOR A JOIN
MOVIE_CAST C ON A.ACT_ID=C.ACT_ID INNER JOIN MOVIES M
ON C.MOV_ID=M.MOV_ID WHERE M.MOV_YEAR NOT BETWEEN 2000 AND 2015;
Program Outcomes:
The students are able to
Create, Update and query on thedatabase.
Demonstrate the working of different concepts ofDBMS
Implement, analyze and evaluate the project developed for anapplication.
Solution:
Entity - Relationship Diagram
Schema Diagram
Table Creation
CREATE TABLE STUDENT (
USN VARCHAR (10) PRIMARY KEY,
SNAME VARCHAR (25),
ADDRESS VARCHAR (25),
PHONE BIGINT (10),
GENDER CHAR (1));
Table Descriptions
DESC STUDENT;
DESC SEMSEC;
DESC CLASS;
DESC IAMARKS;
SELECT * FROM
SELECT S.*, SS.SEM, SS.SEC FROM STUDENT S, SEMSEC SS, CLASS C WHERE
S.USN = C.USN AND SS.SSID = C.SSID AND SS.SEM = 4 AND SS.SEC=’C’
2. Compute the total number of male and female students in each semester and ineach section.
SELECT SS.SEM, SS.SEC, S.GENDER, COUNT (S.GENDER) AS COUNT FROM
STUDENT S, SEMSEC SS, CLASS C
WHERES.USN = C.USN AND SS.SSID =C.SSID
GROUP BY SS.SEM, SS.SEC,S.GENDER ORDER BY SEM;
Note: Before execution above SQL statement, IAMARKS table contents are:
UPDATE IAMARKS
SET FINALIA=GREATEST(TEST1+TEST2,TEST2+TEST3,TEST1+TEST3)/2;
SELECT S.USN,S.SNAME,S.ADDRESS,S.PHONE,S.GENDER,
(CASE
WHEN IA.FINALIA BETWEEN 17 AND 20 THEN 'OUTSTANDING'
WHEN IA.FINALIA BETWEEN 12 AND 16 THEN 'AVERAGE'
ELSE 'WEAK'
END) AS CAT
FROM STUDENT S, SEMSEC SS, IAMARKS IA, SUBJECT SUB WHERE S.USN = IA.USN
AND SS.SSID = IA.SSID AND SUB.SUBCODE = IA.SUBCODE AND SUB.SEM = 8;
Program Outcomes:
The students are able to
Create, Update and query on thedatabase.
Demonstrate the working of different concepts ofDBMS
Implement, analyze and evaluate the project developed for anapplication.
Program Objectives:
This course will enable students to
Foundation knowledge in database concepts, technology and practice to groomstudents
into well-informed database applicationdevelopers.
Strong practice in SQL programming through a variety of databaseproblems.
Develop database applications using front-end tools and back-endDBMS.
Solution:
Entity-Relationship Diagram
Schema Diagram
Table Creation
NOTE: Once DEPARTMENT and EMPLOYEE tables are created we must alter department
table to add foreign constraint MGRSSN using sql command
Table Descriptions
DESC EMPLOYEE;
DESC DEPARTMENT;
DESC DLOCATION;
DESC PROJECT;
DESC PROJECT
DESC WORKS_ON;
Note: update entries of employee table to fill missing fields SUPERSSN and DNO
Queries:
1. Make a list of all project numbers for projects that involve an employee whose last
name is ‘Scott’, either as a worker or as a manager of the department that controls the
project.
(SELECT DISTINCT P.PNO FROM PROJECT P, DEPARTMENT D, EMPLOYEE E
WHERE E.DNO=D.DNO AND D.MGRSSN=E.SSN AND E.LNAME=’SCOTT’)
UNION
(SELECT DISTINCT P1.PNO FROM PROJECT P1, WORKS_ON W, EMPLOYEE E1
WHERE P1.PNO=W.PNO AND E1.SSN=W.SSN AND E1.LNAME=’SCOTT’)
2. Show the resulting salaries if every employee working on the ‘IoT’ project is given a 10
percentraise.
SELECT E.FNAME, E.LNAME, 1.1*E.SALARY AS INCR_SAL FROM EMPLOYEE E,
WORKS_ON W, PROJECT P WHERE E.SSN=W.SSN AND W.PNO=P.PNO AND
P.PNAME=’IOT’;
3. Find the sum of the salaries of all employees of the ‘Accounts’ department, as well as
the maximum salary, the minimum salary, and the average salary in this department
SELECT SUM (E.SALARY), MAX (E.SALARY), MIN (E.SALARY), AVG (E.SALARY)
FROM EMPLOYEE E, DEPARTMENTD WHERE E.DNO=D.DNO AND
D.DNAME=’ACCOUNTS’;
4. Retrieve the name of each employee who works on all the projects Controlled by
department number 5 (use NOT EXISTSoperator).
SELECT E.FNAME,E.LNAME FROM EMPLOYEE E WHERE NOT EXISTS
(SELECT PNO FROM PROJECT P WHERE DNO=5 AND PNO NOT IN
(SELECT PNO FROM WORKS_ON W WHERE E.SSN=SSN));
5. For each department that has more than five employees, retrieve the department
number and the number of its employees who are making more than Rs. 6, 00,000.
SELECT D.DNO, COUNT(*)
FROM DEPARTMENT D, EMPLOYEE E
WHERE D.DNO=E.DNO
AND E.SALARY>600000
AND D.DNO IN (SELECT E1.DNO
FROM EMPLOYEE E1
GROUP BY E1.DNO
HAVING COUNT (*)>5)
GROUP BY D.DNO;
Program Outcomes:
The students are able to
Create, Update and query on thedatabase.
Demonstrate the working of different concepts ofDBMS
Implement, analyze and evaluate the project developed for anapplication.
Viva Questions
1. What isSQL?
Structured Query Language
2. What isdatabase?
A database is a logically coherent collection of data with some inherent meaning,
representing some aspect of real world and which is designed, built and populated with data
for a specific purpose.
3. What isDBMS?
It is a collection of programs that enables user to create and maintain a database. In other
words it is general-purpose software that provides the users with the processes of defining,
constructing and manipulating the database for various applications.
4. What is a Database system?
The database and DBMS software together is called as Database system.
This data model is based on real world that consists of basic objects called entities and of
relationship among these objects. Entities are described in a database by a set of attributes.
11. What is Object Orientedmodel?
This model is based on collection of objects. An object contains values stored in instance
variables within the object. An object also contains bodies of code that operate on the
object. These bodies of code are called methods. Objects that contain same types of values
and the same methods are grouped together into classes.
12. What is an Entity?
It is an 'object' in the real world with an independent existence.
13. What is an Entitytype?
It is a collection (set) of entities that have same attributes.
14. What is an attribute?
It is a particular property, which describes theentity.
15. What is degree of aRelation?
It is the number of attribute of its relation schema.
16. What isRelationship?
It is an association among two or more entities.
17. What is DDL (Data DefinitionLanguage)?
A data base schema is specified by a set of definitions expressed by a special language
called DDL.
18. What is DML (Data ManipulationLanguage)?
This language that enable user to access or manipulate data as organized by appropriate
datamodel.
query. Depending on how the subquery is written, it can be executed once for the parent
query or it can be executed once for each row returned by the parent query. If the subquery
is executed for each row of the parent, this is called a correlated subquery.
A correlated subquery can be easily identified if it contains any references to the parent
subquery columns in its WHERE clause. Columns from the subquery cannot be referenced
anywhere else in the parent query. The following example demonstrates a non-correlated
subquery.
E.g. Select * From CUST Where ‘2019/03/05' IN (Select ODATE From ORDER Where
CUST.CNUM = ORDER.CNUM)
34. What are the primitive operations common to all record managementsystems?
Addition, deletion and modification
35. How do you communicate with anRDBMS?
You communicate with an RDBMS using Structured Query Language (SQL)
36. Define SQL and state the differences between SQL and other conventional
programmingLanguages
SQL is a nonprocedural language that is designed specifically for data access operations on
normalized relational database structures. The primary difference between SQL and other
conventional programming languages is that SQL statements specify what data operations
should be performed rather than how to perform them.
37. What is databaseTrigger?
A database trigger is a PL/SQL block that can defined to automatically execute for insert,
update, and delete statements against a table. The trigger can e defined to execute once for
the entire statement or once for every row that is inserted, updated, or deleted.
38. What are stored-procedures? And what are the advantages of usingthem.
Stored procedures are database objects that perform a user defined operation. A stored
procedure can have a set of compound SQL statements. A stored procedure executes the
SQL commands and return the result to the client. Stored procedures are used to reduce
network traffic.
39. Which is the subset of SQL commands used to manipulate Database structures,
including tables?
Data Definition Language (DDL)
40. What operator performs pattern matching?
LIKE operator
41. What operator tests column for the absence of data?
IS NULL operator
42. What are the wildcards used for patternmatching?
For single character substitution and % for multi-character substitution
43. What are the difference between TRUNCATE and DELETEcommands?
TRUNCATE DELETE
44. What is the use of the ADD OR DROP option in the ALTER TABLEcommand?
It is used to add/drop columns or add/drop constraints specified on the table
45. What is the use of DESC inSQL?
DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in
descending order.
The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted
on ENAME in descending order
46. What is the use of ON DELETE CASCADE?
Whenever rows in the master (referenced) table are deleted ,the respective rows of the child
(referencing) table with a matching foreign key column will get deleted as well. This is called a
cascade delete
Example Tables:
CREATE TABLE Customer
(
customer_idINT (6) PRIMARY KEY,
cname VARCHAR (100),
caddress VARCHAR (100)
);
);
Customer is the master table and Order is the child table, where 'customer_id’ is primary key in
customer table and customer_id is the foreign key in Order table and represents the customer who
placed the order. When a row of Customer is deleted, any Order row matching the deleted Customer's
customer_id will also be deleted.
47. What is the use of Floor()?
The FLOOR() function returns the largest integer value that is smaller than or equal to a
number.
EXAMPLE;
SELECT FLOOR(25.75);
OUTPUT
25
48. What is the use of Truncate()?
The TRUNCATE() function truncates a number to the specified number of decimal places.
EXAMPLE;
SELECT TRUNCATE(135.375, 2);
OUTPUT
135.37
49. What is the use of CEILING?
Return the smallest integer value that is greater than or equal to 25.75:
EXAMPLE;
SELECT CEILING(25.75)
OUTPUT
26
50. What you mean by SQL UNIQUE Constraint?
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a
column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
51. How to add and drop UNIQUE Constraint in table in mysql?
ALTER TABLE contacts ADD CONSTRAINT UNC_name_email UNIQUE(name,email)
ALTER TABLE contacts DROP INDEX UNC_name_email;
52. What is the Group by Clause?
The GROUP BY clause is a SQL command that is used to group rows that have the same
values.
The GROUP BY clause is used in the SELECT statement .Optionally it is used in conjunction
with aggregate functions to produce summary reports from the database.That's what it
does, summarizing data from the database.
The queries that contain the GROUP BY clause are called grouped queries and only return
single row for every grouped item.
Additional Queries
CREATE command
CREATE TABLE Employee
(
Empno int(4) primary key,
Empname varchar(50),
job varchar(40),
Hiredate date,
Salary decimal(10,2),
Deptno int(7),
Age int(10)
);
DESC command
DESC Employee;
INSERT command
Insert the values into the table as specified.
1) Insert into Employee values(1000,'Hemanth’,’Manager’,’2018-11-17’,35000, 30, 38);
2) Insert into Employee values(1001, 'Nitin’,’Manager’,’2018-05-01’,45000, 10, 42);
3) Insert into Employee values(1002, 'Sachin’,’Salesman’,’2018-01-09’,18000, 20, 28);
4) Insert into Employee values(1003, 'Deepak’,’Clerk’,’2018-05-15’,15000, 40, 34);
5) Insert into Employee values(1004, 'Ajay’,’Analyst’,’2018-10-22’,60000, 50, 45);
6) Insert into Employee values(1005, 'Arun’,’Programmer’,’2018-7-24’,25000, 60,25);
Queries:
Problems on select command:
2) Display the details of all employees getting salary less than 30,000.
8) Display the details of employees whose names starts with ‘a’ in them.
9) Display the details of employees whose names does not starts with ‘a’ in them.
10) Display the employee details whose names have exactly 4 characters.
11)Copy all the records of their from employee table and insert the records into a temp table
with column names same as in Employee table
ALTER command