0% found this document useful (0 votes)
462 views

Class-Xii-It-Database Concepts

This document provides an overview of database concepts and relational databases. It discusses the need for databases to organize data and extract useful information. Key points covered include the definition of a database, characteristics of database management systems (DBMS), types of database users, advantages and limitations of using a DBMS approach, and introduces relational databases.

Uploaded by

nakulshali1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
462 views

Class-Xii-It-Database Concepts

This document provides an overview of database concepts and relational databases. It discusses the need for databases to organize data and extract useful information. Key points covered include the definition of a database, characteristics of database management systems (DBMS), types of database users, advantages and limitations of using a DBMS approach, and introduces relational databases.

Uploaded by

nakulshali1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 240

INDIAN SCHOOL MUSCAT

CLASS XII

INFORMATION TECHNOLOGY(802)

1
UNIT- - DATABASE CONCEPTS
Database Concepts
The key to organizational success is effective
decision making which requires timely, relevant
WRITE
and accurate information. Hence information
plays a critical role in today's competitive
environment. Database Management Software
(DBMS) simplifies the task of managing the
data and extracting useful information out of it.
we shall learn about the basic concepts of
databases and also learn how to use DBMS for
some applications.
Data is a collection of raw facts which have not
been processed to reveal useful information.
Information is produced by processing data as
WRITE
shown in Figure.

Data Processing
For example, given the data of the test marks of all
WRITE
the students in a class (data), the average,
maximum and minimum marks in the class can be
used as indicators of the performance of
the class (information).
In other words, we can say that we have extracted
the information about average, maximum and
minimum marks for given student data.
WRITE
A database has the following properties:
WRITE
1) A database is a representation of some aspect of
the real world also called miniworld. Whenever
there are changes in this miniworld they are also
reflected in the database.
2) It is designed, built and populated with data for
specific purpose.
3) It can be of any size and complexity.
4) It can be maintained manually or it may be
computerized.
Need for a Database
WRITE
In traditional file processing, data is stored in the form of
files. A number of application programs are written by
programmers to insert, delete, modify and retrieve data
from these files. New application programs will be added
to the system as the need arises. For example,
consider the Sales and Payroll departments of a company.
One user will maintain information about all the
salespersons in the Sales department in some file
say File1 and another user will maintain details
about the payroll of the salesperson in a separate
WRITE file say File2 in the Payroll Department as shown

Traditional File Processing System


Although both the departments need information
about the salesperson but they will store
information about the salesperson in different
WRITE files and will use different application programs
to access those files. This would result in:
1. Data Redundancy: Same information is stored
in more than one file. This would result in
wastage of space.
2. Data Inconsistency: If a file is updated then all
the files containing similar information
must be updated else it would result in
inconsistency of data.
WRITE
3. Lack of Data Integration: As data files are independent,
accessing information out of multiple files becomes very
difficult. Database approach overcomes these problems
and also adds a lot of advantages as discussed later. In
database approach, a single repository of data is
maintained which is accessed by different users as per
their needs.
Database Management System (DBMS)

WRITE
A database management system is a collection of
programs that enables users to create,
maintain and use a database. It enables creation of a
repository of data that is defined once and then
accessed by different users as per their requirements.
Thus there is a single repository of data which is
accessed by all the application programs as shown
WRITE

DBMS Environment
The various operations that need to be performed on
a database are as follows:
1. Defining the Database: It involves specifying the
WRITE
data type of data that will be stored in
the database and also any constraints on that data.
2. Populating the Database: It involves storing the
data on some storage medium that is
controlled by DBMS.
3. Manipulating the Database: It involves modifying
the database, retrieving data or
querying the database, generating reports from the
database etc.
4. Sharing the Database: Allow multiple users to
WRITE access the database at the same time.
5. Protecting the Database: It enables protection of
the database from software/
hardware failures and unauthorized access.
6. Maintaining the Database: It is easy to adapt to the
changing requirements.
Some examples of DBMS are – MySQL, Oracle, DB2,
IMS, IDS etc.
Characteristics of Database Management Systems
The main characteristics of a DBMS are as follows:
1. Self-describing Nature of a Database System: DBMS
contains not only the database but also the description of
WRITE the data that it stores. This description of data is called
metadata.
Meta-data is stored in a database catalogue or data
dictionary. It contains the structure of the data and also the
constraints that are imposed on the data.
2. Insulation Between Programs and Data: Since the
definition of data is stored separately in a DBMS, any
change in the structure of data would be done in the
catalogue and hence programs which access this data
need not be modified. This property is called
Program-Data Independence.
Characteristics of Database Management Systems

WRITE

3. Sharing of Data: A multiuser environment allows multiple


users to access the database simultaneously. Thus a DBMS
must include concurrency control software to allow
simultaneous access of data in the database without any
inconsistency problems.
Types of Users of DBMS
DBMS is used by many types of users depending on their
requirements and interaction with the DBMS.
There are mainly four types of users:
WRITE 1. End Users: Users who use the database for querying,
modifying and generating reports as per their needs. They
are not concerned about the working and designing of the
database. They simply use the DBMS to get their task
done.
2. Database Administrator (DBA): As the name implies, the
DBA administers the database and the DBMS. The DBA is
responsible for authoring access, monitoring its use, providing
technical support, acquiring software and hardware
resources.
Types of Users of DBMS

3. Application Programmers: Application programmers write


WRITE application programs to interact with the database. These
programs are written in high level languages and SQL
to interact with the database.

4. System Analyst: System analyst determines the


requirements of the end users and then develops specifications
to meet these requirements. A system analyst plays a major
role in the database design and all the technical, economic and
feasibility aspects.
Advantages of using DBMS Approach
The need of DBMS itself explains the advantages of using a
DBMS. Following are the
advantages of using a DBMS:
WRITE 1. Reduction in Redundancy: Data in a DBMS is more
concise because of the central repository of data. All the data is
stored at one place. There is no repetition of the same data.
This also reduces the cost of storing data on hard disks or
other memory devices.
2. Improved Consistency: The chances of data
inconsistencies in a database are also
reduced as there is a single copy of data that is accessed or
updated by all the users.
Advantages of using DBMS Approach
3. Improved Availability: Same information is made available
to different users. This helps sharing of information by various
users of the database.
WRITE 4. Improved Security: Though there is improvement in the
availability of information to users, it may also be required to
restrict the access to confidential information. By making
use of passwords and controlling users' database access
rights, the DBA can provide security to the database.
5. User Friendly: Using a DBMS, it becomes very easy to
access, modify and delete data.It reduces the dependency of
users on computer specialists to perform various data
related operations in a DBMS because of its user friendly
interface.
Limitations of using DBMS Approach
1. High Cost: The cost of implementing a DBMS system
is very high. It is also a very time consuming process which
WRITE involves analyzing user requirements, designing the
database specifications, writing application programs and then
also providing training.
2. Security and Recovery Overheads: Unauthorized access to
a database can lead to threat to the individual or organization
depending on the data stored. Also the data must be regularly
backed up to prevent its loss due to fire, earthquakes, etc.
Hence the DBMS approach is usually not preferred when the
database is small, well defined, less frequently changed and
used by few users.
Relational Database
Various types of databases have been developed. One of
them was relational database developed by E.F Codd at IBM
WRITE
in 1970. It is used to organize collection of data as a
collection of relations where each relation corresponds to a
table of values. Each row in the table corresponds to a
unique instance of data and each column name is used to
interpret the meaning of that data in each row.

For example, consider EMPLOYEE table in Figure.


Each row in this table represents facts about a particular
employee. The column names – Name, Employee_ID,
Gender, Salary and Date_of_Birth specify how to interpret
the data in each row.
WRITE

Employee Table
In relational model,
• A row is called a Tuple.
• A column is called an Attribute.
WRITE
• A table is called as a Relation.
• The data type of values in each column is called the
Domain.
• The number of attributes in a relation is called the Degree
of a relation.
• The number of rows in a relation is called the Cardinality
of a relation.
• Relation Schema R is denoted by R (A1 , A2 , A3 …, An)
where R is the relation name and A1 , A2, A3 ,….An is the
list of attributes.
WRITE • Relation State is the set of tuples in the relation at a point in
time. A relation state r of relation schema R (A1 , A2, ..., An ),
denoted r(R) is a set of n-tuples r = {t1 , t2,...., tm }, where each
n-tuple is an ordered list of values t = <v1 , v2 , ...,vn >, where
vi is in domain of Ai or is NULL. Here n is the degree of the
relation and m is the cardinality of the relation.
Hence in the previous Figure,
• EMPLOYEE table is a relation.
• There are three tuples in EMPLOYEE relation.
• Name, Employee_ID, Gender, Salary, Date_of_Birth are
WRITE attributes.
• The domain is a set of atomic (or indivisible) values. The
domain of a database attribute is the set of all the possible
values that attribute may contain. In order to specify a domain,
we specify the data type of that attribute. Following are the
domain of attributes of the EMPLOYEE relation:
(a) Name – Set of character strings representing names of
persons.
(b) Employee_ID–Set of 4-digit numbers
(c) Gender – male or female
(d) Salary – Number
(e) Date_of_Birth – Should have a valid date, month and year.
The birth year of the employee must be greater than 1985.
Also the format should be dd-mm-yyyy.
WRITE • The degree of the EMPLOYEE relation is 5 as there are five
attributes in this relation.
• The cardinality of the EMPLOYEE relation is 3 as there are
three tuples in this relation.
• Relation Schema – EMPLOYEE (Name, Employee_ID,
Gender, Salary, Date_of_Birth)
Relation State – {<Neha Mehta, 1121,Female,20000,04-03-
1990>,
<Paras Bansal, 2134, Male, 25000, 19-10-1993>,
<Himani Verma, 3145, Female, 20000, 23-11-1992>}
• Relation State –{<Neha Mehta, 1121,Female,20000,04-03-1990>,
WRITE <Paras Bansal, 2134, Male, 25000, 19-10-1993>,
<Himani Verma, 3145, Female, 20000, 23-11-1992>}
Some More Characteristics of Relations:

Employee Table (reordered tuples)


1. Ordering of tuples is not important in a Relation.
2. The ordering of attributes is also unimportant.
WRITE 3. No two tuples of relation should be identical i.e. given any
pair of two tuples, value in at least one column must be
different.
4. The value in each tuple is an atomic value (indivisible).
5. If the value of an attribute in a tuple is not known or not
applicable or not available, a special value called null is
used to represent them.
For example consider the following cases:

WRITE • Unknown value: A person has a date of birth but it is not


known at the time of data entry.
• Unavailable value: A person has a home phone but does
not want it to be listed.
• Not applicable: College degree attribute would be NULL for
a person who has no college degrees.

In all the above cases NULL value would be used.


WRITE A Relational DBMS (RDBMS) is a DBMS which is based on
the relational model as discussed above. This is one of the
most commonly used databases.

Examples of RDBMS are Oracle, MySQL, IBM DB2.


Relational Model Constraints

WRITE Constraints, are restrictions on the values, stored in a database


based on the requirements.
For example, in the relation EMPLOYEE, the Employee_ID must
be a 4-digit number, the Date_of_Birth must be such that the
birth year > 1985.
We describe below various types of constraints in Relational
model:
We describe below various types of constraints in Relational
model:
WRITE 1. Domain Constraint: It specifies that the value of every
attribute in each tuple must be from the domain of that attribute.
For example, the Employee_ID must be a 4-digitnumber. Hence
a value such as “12321” or “A234” violates the domain constraint
as the former is not 4-digit long and the latter contains an
alphabet.
2. Key Constraint: Before we can explain this constraint, we
need to describe the terms superkey,key, candidate key and
primary key.
(i) Superkey is a set of attributes in a relation, for which no two
WRITE tuples in a relation state have the same combination of values.
Every relation must have at least one superkey which is the
combination of all attributes in a relation. Thus for the
EMPLOYEE relation, following are some of the superkeys:
(a) {Name, Employee_ID, Gender, Salary, Date_of_birth} -
default superkey
consisting of all attributes.
(b) {Name, Employee_ID, Date_of_Birth}
WRITE (c) {Name, Employee_ID, Gender}
(d) {Employee_ID}

However {Gender, Salary} is not a superkey because both these


attributes have identical values for employees Neha and Himani.
ii) Key is the minimal superkey, which means it is that
WRITE superkey of a relation from which if any attribute is
removed then it no longer remains a superkey. For
example the superkey {Name, Employee_ID, Gender}is not
a key as we can remove Name and Gender from this
combination and then what is left {Employee_ID} is still a
Superkey. Now {Employee_ID} is a key as it is a superkey
as well as no more removals are possible. A relation may
have more than one key.
Consider the relation PERSON with the following schema:
WRITE

PERSON (Aadhar_number, PAN,Voter_ID_cardno, Name,


Date_of_birth, Address). This relation has three keys
namely : {Aadhar_number}, {PAN}, {Voter_ID_no} as every
individual in India has a unique Aadhar card number, PAN
as well as Voter ID card number.

iii) Candidate key: A key as described above is called


candidate key of the relation. For example, the PERSON
relation has three candidate keys as discussed above.
iv) Primary Key: One of the candidate keys may be
designated as Primary key. Primary key is used to
identify tuples in a relation. If a relation has many
WRITE candidate keys it is preferable to choose that one as
primary key which has least number of attributes.
Primary key are usually underlined in the schema of
the relation. For example in the relation schema:
PERSON (Aadhar_number, PAN, Voter_ID_cardno,
Name,Date_of_birth, Address), Aadhar_number is the
primary key.
The relation between superkey, key, candidate key
and primary key can be explained with the help of
Figure
WRITE

Figure: Superkey, Key, Candidate key and Primary key


3. Null Value Constraint: Sometimes it is required
WRITE
that certain attributes cannot have null values.
For example, if every EMPLOYEE must have a valid
name then the Name attribute is constrained to be
NOT NULL.
4. Entity Integrity Constraint: This constraint
specifies that primary key of a relation
WRITE cannot have null value. The reason behind this
constraint is that we know primary key contains no
duplicates. However if we allow null values for a
primary key then there can be multiple tuples for
which primary key is having null values. This would
imply that we are allowing duplicate values (NULL) for
a primary key which itself violates the definition
of primary key.
5. Referential Integrity Constraint: This constraint is
specified between two relations.
Before defining this constraint let us study the concept
WRITE
of foreign keys. Foreign key in a relation R1 is the set
of attributes in R1 that refer to primary key in another
relation R2 if the domain of foreign key attributes is
same as that of primary key attributes and the
value of foreign key either occurs as a value of
primary key in some tuple of R2 or is NULL.
R1 is called the referencing relation and R2 is called
referenced relation, and a referential
integrity constraint holds from R1 to R2.
The main purpose of this constraint is to check that data
entered in one relation is consistent with the data entered
WRITE in another relation. For example, consider two relation
schemas:

Department (Dept_Name, Dept_ID, No_of_Teachers)


Teacher (Teacher_Name, Teacher_ID, Dept_ID, Subject)

Following are the primary keys :


• Dept_ID is the primary key of Department relation.
• Teacher_ID is the primary key of Teacher relation.
Now you may notice that Dept_ID- the primary key of
relation in Department, is also present in relation Teacher.
WRITE The reason is that every teacher belongs to a particular
department. Now that means Dept_ID of Teacher relation
must have a value that exists in Dept_ID attribute of
Department relation or it can be NULL in case a teacher has
not yet been assigned to a department. We say that
Dept_ID of Teacher relation is a foreign key that references
primary key of Department relation (Dept_ID). It is important
to emphasize it is not necessary to have same name for
foreign key as of the corresponding referenced primary key.
The above two schemas can also be written as follows:
• Department (Dept_Name, Dept_ID, No_of_Teachers)
• Teacher (Teacher_Name, Teacher_ID, Dept_No, Subject)
Where Dept_No is the foreign key that references Dept_ID of
WRITE Department relation.
A foreign key may also refer to the same relation. For example
suppose we have to create a database of all residents in a
colony along with their best neighbors. Consider the following
relation:
Residents (Name, RID, Block_no, House_no, Floor,
Neighbor_RID)
The Primary key of this relation is RID (Resident ID). In order to
store information about neighbor we have created a foreign key
Neighbor_RID that references RID of Residents.Note that the
referencing and referenced relation are same in this case.
Structured Query Language (SQL)

SQL is a language that is used to manage data stored in a


RDBMS. It comprises of a Data Definition Language (DDL)
WRITE and a Data Manipulation Language (DML) where DDL is a
language which is used to define structure and constraints of
data and DML is used to insert, modify and delete data in a
database.
SQL commands are used to perform all the operations. In order
to study SQL commands, a database system needs to be
installed on the Computer. There are various software's
available. We will study the MySQL server.
SQL uses the terms table, row and column for the relational
model terms relation, tuple and attribute.
Structured Query Language (SQL)

For studying SQL we will use MySQL Community Server 5.6.20


WRITE which is freely downloadable. The most recent versions can be
found on the website:
http://dev.mysql.com/downloads/ Following are the steps to
install and configure MySQL
Community Server 5.6.20 for studying SQL commands.
1. Open the URL:
http://dev.mysql.com/downloads/mysql/#downloads
2. Download the MySQL Community Server 5.6.20 available on
the above webpage.
You can select the platform (Windows/Linux) as shown below.
Structured Query Language (SQL)

WRITE

3. Once you have downloaded the file mysql-installer-


community-5.6.20.0.msi, double click on the downloaded file and
then click on the “Run” button.
WRITE
WRITE
WRITE
WRITE
WRITE
WRITE
WRITE
WRITE
WRITE
WRITE
WRITE
WRITE
WRITE
WRITE
Create Table Command: This command is used
to create a new table or relation. The syntax for
this command is :
WRITE
CREATE TABLE<table name>
(
<column 1><data type> [constraint] ,
<column 2><data type>[constraint],
<column 3><data type>[constraint]
);

where [ ] means optional


The keyword CREATE TABLE is followed by the name of
WRITE
the table that you want to create.
Then within parenthesis, you write the column definition
that consists of column name followed by its data types
and optional constraints. There can be as many columns
as you require. Each column definition is separated with
a comma (,). All SQL statements should end with a
semicolon (;).
Table 1 shows the data types commonly used.

WRITE
Suppose we wish to create a database of all the
teachers working in a school. This database should
WRITE include the Teacher relation (schema given below):
Teacher (Teacher_ID, First_Name, Last_Name, Gender,
Date_of_Birth, Salary, Dept_No)
The above schema stores the information about all the
teachers working in the school such as their unique ID,
first and last name, gender, salary, date of birth and the
department to which the teacher belongs.
Password: tiger
CREATE DATABASE SCHOOL ;
WRITE
USE SCHOOL ;
To create the above relations in SQL, following CREATE
TABLE command is used:
WRITE CREATE TABLE Teacher
(
Teacher_ID INTEGER PRIMARY KEY,
First_Name VARCHAR(20) NOT NULL,
Last_Name VARCHAR(20),
Gender CHAR(1),
Salary DECIMAL(10,2),
Date_of_Birth DATE,
Dept_No INTEGER
);
WRITE
WRITE
WRITE
WRITE
WRITE
a) NOT NULL: An attribute value may not be
permitted to be NULL. For example, the
First name of the Teacher cannot be NULL.
Hence NOT NULL constraint can be
WRITE specified in this case.
CREATE TABLE TEACHER
(
Teacher_ID INTEGER,
First_Name VARCHAR(20) NOT NULL,
Last_Name VARCHAR(20),
Gender CHAR(1),
Salary DECIMAL(10,2),
Date_of_Birth DATE,
Dept_No INTEGER
);
b) DEFAULT : If a user has not entered a value for an
attribute, then default value specified while creating
the table is used. For example, if a teacher's salary has
not been entered, then by default the database
should store 40000 assuming that the minimum salary
WRITE given to every teacher is 40000. This is illustrated as
follows:
CREATE TABLE TEACHER
(
Teacher_ID INTEGER,
First_Name VARCHAR(20) NOT NULL,
Last_Name VARCHAR(20),
Gender CHAR(1),
Salary DECIMAL(10,2) DEFAULT 40000,
Date_of_Birth DATE,
Dept_No INTEGER
);
In MySQL, if you want to look at the structure and
description of the tables created, DESC command can
be used. The description of the table Teacher created
above is as follows:

WRITE
c) CHECK: In order to restrict the values of an attribute within a
range, CHECK constraint may be used. For example Dept_No of any
teacher must not exceed 110.
This can be specified as follows:
CREATE TABLE TEACHER
WRITE ( MySQL does not support CHECK
Teacher_ID INTEGER, constraint, although it will not
First_Name VARCHAR(20) NOT NULL, give any error if you have a check
constraint in your table.
Last_Name VARCHAR(20),
Gender CHAR(1),
Salary DECIMAL(10,2) DEFAULT 40000,
Date_of_Birth DATE,
Dept_No INTEGER CHECK (Dept_No<=110)
);
You can also use the CHECK constraint to compare two attributes
within the same relation having same data type.
d) KEY CONSTRAINT: Primary Key of a table can be specified in two
ways. If the primary key of the table consist of a single attribute,
then the corresponding attribute
can be declared primary key along with its description. For
example, if Teacher_ID attribute of the Teacher relation is the
WRITE PRIMARY KEY then it can be specified as
follows:
CREATE TABLE TEACHER
(
Teacher_ID INTEGER PRIMARY KEY,
First_Name VARCHAR(20) NOT NULL,
Last_Name VARCHAR(20),
Gender CHAR(1),
Salary DECIMAL(10,2) DEFAULT 40000,
Date_of_Birth DATE,
Dept_No INTEGER
);
WRITE
As shown above First_Name has value NO in the Null
column as it was specified to be NOT NULL in the Create
table command. Further Teacher_ID being the primary key
WRITE
(PRI in the Key column) cannot be NULL. Also, note that
default value is specified only for SALARY, and shown NULL
for other attributes indicating no default value.
However if primary key contains more than one attribute
then it must be specified separately as a list of attributes it
comprises of, within parenthesis, separated by
commas. For example, the primary key of the TEACHER
relation comprises of Teacher_ID and Date_of_Birth.
CREATE TABLE TEACHER
(
Teacher_ID INTEGER,
WRITE
First_Name VARCHAR(20) NOT NULL,
Last_Name VARCHAR(20),
Gender CHAR(1),
Salary DECIMAL(10,2) DEFAULT 40000,
Date_of_Birth DATE,
Dept_No INTEGER,
PRIMARY KEY (Teacher_ID, Date_of_Birth)
);
By default, Primary keys are NOT NULL and there is no
need to mention this constraint separately.
e) REFERENTIAL INTEGRITY CONSTRAINT- This constraint
is specified by using the foreign key clause. This clause
contains the foreign key and the primary key referred to
WRITE
by this foreign key along with the name of the relation.
For example
consider the following tables created in the School
Database:Department (Dept_ID, Dept_Name)
Teacher (Teacher_ID, First_Name, Last_Name, Gender,
Salary, Date_of_Birth,Dept_No)
In this example Dept_No is the foreign key that
references Dept_ID of Department relation which is a
primary key. The SQL command for creating these tables
would be as follows:
CREATE TABLE Department
(
Dept_ID INTEGER PRIMARY KEY,
Dept_Name VARCHAR(20) NOT NULL
);
WRITE
CREATE TABLE Teacher
(Teacher_ID INTEGER PRIMARY KEY,
First_Name VARCHAR(20) NOT NULL,
Last_Name VARCHAR(20),
Gender CHAR(1),
Salary DECIMAL(10,2) DEFAULT 40000,
Date_of_Birth DATE,
Dept_No INTEGER,
FOREIGN KEY (Dept_No) REFERENCES Department(Dept_ID)
);
The foreign key is created separately by using the key words
FOREIGN KEY followed by the attribute that is the foreign
key within parenthesis, then the keyword REFERENCES
followed by the name of the referred relation and its
primary key within parenthesis.
WRITE
As shown in above Figure, the key column for Dept_No
contains MUL which implies multiple occurrences of a
WRITE given value can appear within the column. This is also
because it is a foreign key.

Note that the referenced table must be created before it


is referred in any other table.
You can also specify the action to be taken in case the
foreign key attribute or the primary key attribute value
are changed as that may result in violation of the
referential integrity constraint.
This may be done using the following commands:
WRITE 1. ON DELETE
2. ON UPDATE

Actions that can be taken are as follows:

1. SET NULL
2. CASCADE
3. RESTRICT
Let us discuss each in detail:
CREATE TABLE Teacher
(
Teacher_ID INTEGER PRIMARY KEY,
WRITE First_Name VARCHAR(20) NOT NULL,
Last_Name VARCHAR(20),
Gender CHAR(1),
Salary DECIMAL(10,2) DEFAULT 40000,
Date_of_Birth DATE,
Dept_No INTEGER,
FOREIGN KEY (Dept_No) REFERENCES Department (Dept_ID)
ON DELETE SET NULL ON UPDATE SET NULL
);
Thus if a department with a given value of
WRITE
Dept_ID is deleted in Department table, then
the corresponding tuples that contains the
deleted value for Dept_No attribute in Teacher
table would be set to NULL. Similarly, if Dept_ID
value is updated then also the corresponding
attribute in Teacher table would be set to NULL.
CREATE TABLE Teacher
(
Teacher_ID INTEGER PRIMARY KEY,
WRITE First_Name VARCHAR(20) NOT NULL,
Last_Name VARCHAR(20),
Gender CHAR(1),
Salary DECIMAL(10,2) DEFAULT 40000,
Date_of_Birth DATE,
Dept_No INTEGER,
FOREIGN KEY (Dept_No) REFERENCES Department (Dept_ID)
ON DELETE CASCADE ON UPDATE CASCADE
);
In the above table, if a department with a given value
WRITE
of the Dept_ID attribute in Department table is
deleted, then the corresponding rows in the Teacher
table would also be deleted. However if Dept_ID
value is updated in the Department table, the change
in corresponding value is also reflected in Teacher
Table.
CREATE TABLE Teacher
(
Teacher_ID INTEGER PRIMARY KEY,
WRITE First_Name VARCHAR(20) NOT NULL,
Last_Name VARCHAR(20),
Gender CHAR(1),
Salary DECIMAL(10,2) DEFAULT 40000,
Date_of_Birth DATE,
Dept_No INTEGER,
FOREIGN KEY (Dept_No) REFERENCES Department (Dept_ID)
ON DELETE RESTRICT ON UPDATE RESTRICT
);
WRITE RESTRICT option will reject the delete or update
operation for the referenced table if there are one or
more related foreign key values in a referencing
table, i.e, you cannot delete or update a department
if there are teachers who belong to that department.
Self-Referencing Tables: A foreign key constraint can
WRITE reference columns within the same table. These
tables are called as self-referencing tables. For
example, consider a table Employee that contains
five columns: Employee_ID, Name,Age, Salary and
Manager_ID. Because the manager is also an
employee, there is a foreign key relationship
between the Manager_ID and Employee_ID as
shown below:
CREATE TABLE Employee
(
WRITE Employee_ID INTEGER PRIMARY KEY,
Name VARCHAR(30),
Age INTEGER,
Salary DECIMAL(10,2),
Manager_ID INTEGER,
FOREIGN KEY (Manager_ID) REFERENCES Employee (Employee_ID)
);
1. Naming of Constraint:
WRITE

Constraints can be named in the Create Table command.


The advantage is that named constraints can be easily
deleted or updated using the Alter Table command.
A constraint can be named by using the keyword
CONSTRAINT followed by the name of the constraint and its
specification.
For example consider the following Create Table command:
CREATE TABLE Teacher
(
Teacher_ID INTEGER,
WRITE First_Name VARCHAR(20) NOT NULL,
Last_Name VARCHAR(20),
Gender CHAR(1),
Salary DECIMAL(10,2) DEFAULT 40000,
Date_of_Birth DATE,
Dept_No INTEGER,
CONSTRAINT TEACHER_PK PRIMARY KEY (Teacher_ID),
CONSTRAINT TEACHER_FK FOREIGN KEY (Dept_No) REFERENCES
Department(Dept_ID) ON DELETE SET NULL ON UPDATE SET NULL
);
2. Drop Table Command: This command is used to delete
tables. For example, suppose you want to drop the Teacher
WRITE
table then the command would be:
DROP TABLE Teacher CASCADE;
Thus Teacher table would be dropped and with the
CASCADE option, i.e. all the constraints that refer this table
would also be automatically dropped.
However if the requirement is that the table should not be
dropped if it is being referenced in some other table then
RESTRICT option can be used as shown below:
DROP TABLE Teacher RESTRICT;
Drop table command can also be used to drop named
WRITE constraints. However it is used along with the Alter Table
command which is discussed in next section.
Note in MySQL server 5.6.20, RESTRICT and CASCADE
options are not supported though they are permitted to
make porting easier. In MySQL server 5.6.20, you can simply
type Drop Table followed by the table name to delete a
table from the database. However, it will not allow you to
drop a table if the table to be deleted is being referenced in
some other table.
WRITE
As shown in the Figure, there were two tables
Department and Teacher. Table Teacher contained a
above foreign key that references the primary key of
Department table.
WRITE
Hence when we attempt to drop Department table, error
is shown as Department table is being referred in
Teacher Table. Also note that the CASCADE option is not
working as it is not supported in MySQL server 5.6.20.
Department table can only be deleted if all the tables
that refer Department table are deleted so that there are
no references to this table anywhere else. That is why
after we have dropped Teacher table, Department table
deletion was possible as shown above.
3. Alter Table Command: This command is used to modify the
base table definition. The modifications that can be done using
this command are:
(a) Adding a column: Suppose we want to add a column Age in
WRITE the Teacher table.
Following command is used to add the column:
ALTER TABLE Teacher ADD Age INTEGER;
(b) Dropping a column: A column can be dropped using this
command but one must specify the options (RESTRICT or
CASCADE) for the drop behavior. As discussed earlier, RESTRICT
would not let the column be dropped if it is being referenced in
other tables and CASCADE would drop the constraint associated
with this column in this relation as well as all the constraints that
refer this column.
ALTER TABLE Teacher DROP Dept_No CASCADE;
This will drop the Dept_No column in the Teacher Table and it
would also drop the foreign key constraint TEACHER_FK as it
uses this column. As stated earlier, RESTRICT and CASCADE
options are not supported in MySQL server 5.6.20. Hence it
will not allow to drop a column if it is referred anywhere else.
WRITE
The MySQL command to drop Age Column from Teacher is:
ALTER TABLE Teacher DROP Age ;
(c) Altering a Column: A column definition can also be
altered. For example – dropping the default value or defining
a new default value. For example, in the Teacher table
the default value of Salary is 40000. If you want to drop this
default value or change this value to 30000 then it can be
done by using the following commands:
ALTER TABLE Teacher ALTER Salary DROP DEFAULT ;
ALTER TABLE Teacher ALTER Salary SET DEFAULT 30000 ;
(d) Dropping keys: A foreign key/primary key/key can be
dropped by using ALTER TABLE command. For example if you
want to delete the foreign key TEACHER_FK in the Teacher table
then following command can be used:
WRITE

ALTER TABLE Teacher DROP FOREIGN KEY TEACHER_FK;


CASCADE or RESTRICT option can be specified for the drop
behavior (though not supported in MySQL server 5.6).
Primary key can be dropped by using the command:

ALTER TABLE Teacher DROP PRIMARY KEY TEACHER_PK;


However, primary key cannot be removed if it is the only
primary key of the table. Hence the above command will result
in an error.
WRITE
(e) Adding a Constraint: If you want to add the foreign key constraint
TEACHER_FK back, then the command would be:
ALTER TABLE Teacher ADD CONSTRAINT TEACHER_FK FOREIGN KEY
(Dept_No) REFERENCES Department(Dept_ID) ON DELETE SET NULL
ON UPDATE SET NULL;
4. Insert Command: This command is used to insert a tuple in
a relation. We must specify the name of the relation in which
tuple is to be inserted and the values. The values must be in
the same order as specified during the Create Table command.
For example, consider the following table Teacher:
WRITE
CREATE TABLE Teacher
( Teacher_ID INTEGER,
First_Name VARCHAR(20) NOT NULL,
Last_Name VARCHAR(20),
Gender CHAR(1),
Salary DECIMAL(10,2) DEFAULT 40000,
Date_of_Birth DATE,
Dept_No INTEGER,
CONSTRAINT TEACHER_PK PRIMARY KEY (Teacher_ID)
);
To insert a tuple in the Teacher table INSERT command can be
used as shown below:
WRITE
INSERT INTO Teacher
VALUES (101,"Shanaya", "Batra", 'F', 50000, '1984-08-11', 1);
Note that the values listed above are in the same order of the
attributes as specified in the Create Table command.
Another form of INSERT command is used to insert a tuple in
which the ordering of values is done by explicitly specifying the
attribute names as shown below:
INSERT INTO Teacher (First_Name, Last_Name, Gender,
Teacher_ID, Date_of_Birth, Dept_No, Salary)
VALUES ("Shanaya", "Batra", 'F', 101, '1984-08-11', 1, 50000);
Note that the values entered are ordered with respect
to the attributes mentioned. If an attribute value is not
explicitly specified its DEFAULT value is used. If
WRITE
DEFAULT value is also not specified then NULL value is
used. Thus in the above example if salary was not
specified in the INSERT command, then its default
value i.e.40000 as given in the table creation command
would have been used as shown below.
INSERT INTO Teacher (First_Name, Last_Name, Gender,
Teacher_ID, Date_of_Birth, Dept_No, Salary)
VALUES ("Shanaya", "Batra", 'F', 101, '1984-08-11', 1, );
To insert a tuple in the Teacher table INSERT command
can be used as shown below:
INSERT INTO Teacher VALUES (101,"Shanaya", "Batra",
'F', 50000, '1984-08-11', 1);
WRITE Note that the values listed above are in the same order
of the attributes as specified in the Create Table
command. Another form of INSERT command is used
to insert a tuple in which the ordering of values is done
by explicitly specifying the attribute names as shown
below:
INSERT INTO Teacher (First_Name, Last_Name, Gender,
Teacher_ID, Date_of_Birth, Dept_No, Salary)
VALUES ("Shanaya", "Batra", 'F', 101, '1984-08-11', 1, 50000);
INSERT INTO Teacher (First_Name, Last_Name, Gender,
Teacher_ID, Date_of_Birth, Dept_No, Salary) VALUES
WRITE
("Shanaya", "Batra", 'F', 101, '1984-08-11', 1, 50000);
Note that the values entered are ordered with respect to the
attributes mentioned. If an attribute value is not explicitly
specified its DEFAULT value is used. If DEFAULT value is
also not specified then NULL value is used. Thus in the above
example if salary was not specified in the INSERT command,
then its default value i.e.40000 as given in the table
creation command would have been used as shown below.
INSERT INTO Teacher (First_Name, Last_Name, Gender,
Teacher_ID, Date_of_Birth, Dept_No, Salary)
VALUES ("Shanaya", "Batra", 'F', 101, '1984-08-11', 1, );
WRITE

5.Update command: This command is used to update the


attribute values of one or more tuples in a table. For
example in the Teacher table, we want to update the Salary
of teacher with Teacher_ID =101 to 55000. This can be
done using the following
command:
UPDATE Teacher SET Salary = 55000 WHERE Teacher_ID=101;
WRITE
We can also have an algebraic expression in the SET clause.
Suppose it is required to increase the salary of a Teacher
Shanaya by 5000, the command would be:

UPDATE Teacher SET Salary=Salary+5000


WHERE Teacher_Name="Shanaya";
6. Delete Command: In order to delete one or more tuples,
DELETE command is used. If we want to delete the tuple for
WRITE
Teacher with ID=101 the command would be:

DELETE FROM Teacher WHERE Teacher_ID=101;

If the WHERE clause is missing then it will delete all the


tuples in a table as shown below:

DELETE FROM Teacher;


7. Select Command: The SELECT Command is used to retrieve
information from a database. There are various ways in which
the SELECT command can be used.
Syntax of SELECT Command is as follows:
WRITE
SELECT <attribute list> FROM <table list> WHERE <condition>
The basic structure of a SELECT command comprises of the
keyword SELECT followed by the attribute list (separated by
comma (,)) you want to select, followed by FROM clause
followed by the table name and lastly an optional WHERE
clause which is followed by a condition that can be a Boolean
expression or another SELECT command that identifies the
tuples to be selected.
Consider the following tables in the School Database for all the queries that follow:
CREATE TABLE Department
( Dept_ID INTEGER PRIMARY KEY,
Dept_Name VARCHAR(30) NOT NULL
);
WRITE CREATE TABLE Teacher
( Teacher_ID INTEGER,
First_Name VARCHAR(20) NOT NULL,
Last_Name VARCHAR(20),
Gender CHAR(1),
Salary DECIMAL(10,2) DEFAULT 40000,
Date_of_Birth DATE,
Dept_No INTEGER,
CONSTRAINT TEACHER_PK PRIMARY KEY (Teacher_ID),
CONSTRAINT TEACHER_FK FOREIGN KEY (Dept_No) REFERENCES Department (Dept_ID)
);
The Teacher table refers Department table to keep track of
the department to which a teacher belongs.
Assume that the following data has been inserted in the
above tables using the Insert commands:
WRITE
WRITE
a) Query: To retrieve all the information about Teacher
with ID=101. In this query we have to specify all the
attributes in the SELECT clause. An easier way to do this
is to use asterisk (*), which means all the attributes.
WRITE

SELECT * FROM Teacher WHERE Teacher_ID=101;


b) Query: To find the names of all teachers earning more
than 50000.
SELECT First_Name,Last_Name FROM Teacher WHERE
salary > 50000;
WRITE

Result:

Logical comparisons equal to (=), less than (<), greater than (>), less
than or equal to (<=), greater than or equal to(>=), not equal to(<>)
can be used in the WHERE clause.
c) Query: To display Teacher_ID,First_Name,Last_Name
and Dept_No of teachers who belongs to department
number 4 or 7.
WRITE
SELECT Teacher_ID, First_Name,Last_Name, Dept_No
FROM Teacher WHERE Dept_No = 4 OR Dept_No = 7;
d) Query: To retrieve names of all the teachers and
the names and numbers of their respective
departments.
WRITE
Note that the above query requires two tables –
Teacher and Department. Consider the following
query:
SELECT First_Name, Last_Name, Dept_ID,
Dept_Name FROM Teacher, Department;
This query will result in a set in which the number
of rows will be the number of rows in Teacher table
(14) multiplied with number of rows in Department
table (9), i.e. 126 rows.
Since we have not specified any WHERE clause, this
query will combine each row in Teacher table with
each row of Department table resulting in Cartesian
WRITE
product of two tables. This is called as Cross Join.
Now if we have to combine each teacher with
his/her respective department, there should be a
connecting column between the two tables which
can be used to join them. Thus Dept_No (Teacher
table) and Dept_ID (Department table) can be used
to join the two tables. This type of join will result in
joining rows from Teacher and Department table
WRITE
based on the equality between Dept_No and
Dept_ID columns. The query is as follows:
SELECT First_Name, Last_Name, Dept_ID,
Dept_Name FROM Teacher, Department
WHERE Dept_ID=Dept_No;
Here Dept_ID=Dept_No is the join condition.
This would produce the following result:

WRITE
Now suppose we have to retrieve the similar details for
the teacher in Chemistry department, the query would
WRITE be:
SELECT First_Name, Last_Name, Dept_ID, Dept_Name
FROM Teacher, Department WHERE Dept_ID = Dept_No
AND Dept_Name= “Chemistry”;
e) Suppose the teacher and department table both had
WRITE
same names for the department number, say Dept_ID as
shown below:

CREATE TABLE Department


(
Dept_ID INTEGER PRIMARY KEY,
Dept_Name VARCHAR (30) NOT NULL
);
CREATE TABLE Teacher
(
Teacher_ID INTEGER,
First_Name VARCHAR(20) NOT NULL,
WRITE Last_Name VARCHAR(20),
Gender CHAR(1),
Salary DECIMAL(10,2) DEFAULT 40000,
Date_of_Birth DATE,
Dept_ID INTEGER,
CONSTRAINT TEACHER_PK PRIMARY KEY (Teacher_ID),
CONSTRAINT TEACHER_FK FOREIGN KEY (Dept_ID)
REFERENCES Department (Dept_ID)
);
In such case, when the join condition is specified, there
will be an ambiguity about which Dept_ID we are talking
about. To resolve this problem, we have to prefix the
WRITE name of the attribute with the relation name followed
by a period as shown in the query below:
Query: To retrieve names of all the teachers who belong
to Hindi department.
SELECT First_Name, Last_Name
FROM Teacher, Department
WHERE Department. Dept_ID = Teacher. Dept_ID AND
Dept_Name="Hindi";
WRITE
Another method is to create aliases. Aliases are used to resolve
ambiguity of the relations. They are created by using the keyword
'AS'. For example the above query can
also be written as:
SELECT First_Name, Last_Name FROM Teacher AS T, Department
AS D WHERE D.Dept_ID = T. Dept_ID AND Dept_Name="Hindi";
Here T is an alias for Teacher table and D is an alias for Department
table.
We can also create alias to rename a column name as
shown below:
WRITE SELECT First_Name AS Fname, Last_Name AS Lname
FROM Teacher AS T, Department AS D WHERE
D.Dept_ID = T. Dept_ID AND Dept_Name="Hindi";
f) In SQL, duplicate tuples can appear more than once in
a table and in the result of a query.
WRITE However if the requirement is to list distinct values of an
attribute then this can be done by
using the keyword – 'DISTINCT'.
For example, following query will list all the Department
numbers corresponding to departments having male
teachers.
SELECT Dept_No FROM Teacher WHERE GENDER ='M';
WRITE

In the above result, 2 is appearing twice which is not required as


the query is to find only the department numbers. Hence we can
use DISTINCT keyword in the SELECT clause so that there is no
repetition in the result.
SELECT DISTINCT Dept_No FROM Teacher WHERE GENDER ='M';
WRITE

In the above result, 2 is appearing twice which is not required as


the query is to find only the department numbers. Hence we can
use DISTINCT keyword in the SELECT clause so that there is no
repetition in the result.
SELECT DISTINCT Dept_No FROM Teacher WHERE GENDER ='M';
g) Sometimes it is required to match part of the string.
This is called as string pattern matching. We can use
'LIKE' keyword along with two more reserved characters -
WRITE %(percent) and _ (underscore) for specifying different
number of characters. % replaces zero or more number of
random characters and _ replaces a single character.
Some examples:
Query: To retrieve names of all the teachers starting from
letter 'S'.
SELECT First_Name FROM Teacher WHERE First_Name LIKE "S%";
WRITE

Query: To retrieve names of all the teachers having 6 characters


in the first name and starting with 'S'.

SELECT First_Name FROM Teacher WHERE First_Name LIKE "S_ _ _ _ _";


WRITE
WRITE
h) Suppose it required to sort the result of a query based
on some attributes. This can be achieved by using the
clause – ORDER BY followed by the attributes which
WRITE needs to be sorted. (By default the order is ascending)
For ascending order the keyword ASC and for descending
order the keyword DESC is used. By default the order is
ascending.
Query: To list the names of teachers in alphabetical
order.
SELECT First_Name, Last_Name FROM Teacher ORDER BY
First_Name, Last_Name;
WRITE
Query: To list the names of all the Departments in the
descending order of their names.

WRITE SELECT Dept_Name FROM Department ORDER BY Dept_Name DESC;


Query: To retrieve the names and department numbers of all
WRITE
the teachers ordered by the Department number and within
each department ordered by the names of the teachers in
descending order.

SELECT First_Name, Last_Name, Dept_No FROM Teacher ORDER BY


Dept_No ASC, First_Name DESC, Last_Name DESC;
WRITE
i) To test whether a value is unavailable or unknown or
not applicable in a column (i.e, NULL values), SQL
allows us to test this condition using keywords IS NULL
and IS NOT NULL.
WRITE

Query: To retrieve all the details of those employees whose last


name is not specified.

SELECT * FROM Teacher WHERE Last_Name IS NULL;


j) We can have another query in the WHERE clause of
SQL query if the condition is based on the result of
WRITE another query as shown below:
Query: To retrieve the names of all the departments
having female teachers.

SELECT DISTINCT Dept_Name FROM Department WHERE Dept_ID IN


(Select Dept_No FROM Teacher WHERE Gender = 'F');
WRITE

The above query is a nested query (query within another query). The
outer one is called outer query and the inner one is called as inner
query. The inner query will return those department ID's which have
female teachers and the outer query will retrieve the names
of those departments respectively
We could have also written the above query by using JOIN
WRITE
condition as shown below:

SELECT DISTINCT Dept_Name FROM Department , Teacher WHERE


Dept_ID = Dept_No AND Gender='F';
k) Sometimes it is required to apply certain mathematical
functions on group of values in a database. Such
functions are called Aggregate Functions. For example
WRITE
retrieving the total number of teachers in all the
Departments. Following are the commonly used built-in
aggregate functions:
COUNT()- It counts the numbers of tuples in the result of
the query.
SUM() – It finds the sum of all the values for a selected
attribute which has numeric data type.
MAX() –It finds the maximum value out of all the values
WRITE for a selected attribute which has numeric data type.
MIN() - It finds the minimum value out of all the values
for a selected attribute which has numeric data type.
AVG() – It finds the average value of all the values for a
selected attribute which has numeric data type.
Query: To find total salary of all the teachers.

SELECT SUM(Salary) AS Total_Salary FROM Teacher;


WRITE
Query: To find the maximum and minimum salary.

SELECT MAX(Salary) AS Max_Salary, MIN(Salary) AS Min_Salary FROM Teacher;

WRITE
Query: To count the number of teachers earning more than
Rs 40000.
WRITE

SELECT COUNT(Salary) FROM Teacher WHERE Salary > 40000;


The above query can also be written as follows:

WRITE SELECT COUNT(*) FROM Teacher WHERE Salary > 40000;

The difference is in the use of asterisk (*). Asterisk symbol is used to count
the number of rows in the result of the query.

Query: To retrieve the number of teachers in “Computer Science”


Department.
SELECT COUNT(*) AS No_of_Computer_Science_Teachers
FROM Department, Teacher WHERE Dept_Name = "Computer Science“
AND Dept_No = Dept_ID;
WRITE
l) We can also use arithmetic operators in the SELECT clause.
For example, if we want to display Teacher name, current salary
WRITE and a 10% increase in the salary for those teachers who
belongs to Department number 4, the SELECT statement can be
written as shown below:

SELECT First_Name, Last_Name, Salary, Salary+Salary*0.10 AS


“New_Salary” FROM Teacher WHERE Dept_No = 4;
m) Grouping based on an attribute can be done in SQL. For such
grouping, GROUP BY clause is added in the SQL query.
WRITE For example, we have to find the number of teachers teaching
in each Department. Thus we have to group the result based on
the Departments and for each Department we have
to count number of teachers who teach in that Department.
This query is written by using GROUP BY clause and aggregate
function as shown below:

SELECT Dept_No, COUNT(*) AS “No_of_Teachers” FROM Teacher GROUP


BY Dept_No;
WRITE
The above result can be enhanced if we display the name of
WRITE
Departments also as shown below:
SELECT Dept_No, Dept_Name, COUNT(*) AS “No_of_Teachers”
FROM Teacher, Department WHERE Dept_ID = Dept_No
GROUP BY Dept_No;
WRITE
Also it is important to note that the attribute used for grouping
(Dept _No in the above query) must also be present in the
WRITE SELECT clause.
It is also possible to apply some condition on the group. This
condition will not come under the WHERE clause, but in a new
clause HAVING.
For example, we have to find those departments which have
more than one teacher.
SELECT Dept_No, Dept_Name, COUNT(*) AS No_of_Teachers
FROM Teacher, Department WHERE Dept_No=Dept_ID
GROUP BY Dept_No HAVING COUNT(*) > 1;
WRITE
n) A Select command can also result in an empty set.
For example, retrieve the name of Teacher with ID=115. Since
WRITE there is no such teacher in
the Teacher table, following query results in an empty set.

SELECT * FROM Teacher WHERE Teacher_ID = 115 ;

Result:

Empty set
STRUCTURED QUERY LANGUAGE( MySQL )
SQL Commands

CREATE A TABLE EMPLOYEE WITH THE FOLLOWING DETAILS

Name Data type size constraints


PLEASE
WRITE
------- ----------- _____ ------------
Ecode integer Primary Key
Ename character 25 Not Null
Sex character 1 Not Null
Dept character 25 Not null
Desig character 25
DOJ date Not null
Salary decimal(8,2) Salary > 500
STRUCTURED QUERY LANGUAGE( MySQL )
SQL Commands
CREATING TABLE EMPLOYEE IN MySQL:

CREATE TABLE EMPLOYEE (


PLEASE Ecode integer not null primary key,
WRITE Ename varchar(25) not null,
Sex char(1) not null,
Dept varchar(25) not null,
Desig varchar(25),
DOJ date not null,
Salary decimal(8,2) check(Salary > 500) );
STRUCTURED QUERY LANGUAGE( MySQL )
SQL Commands

INSERT THE FOLLOWING DATA TO TABLE EMPLOYEE

Ecode EName Sex Dept Desig DOJ Salary


PLEASE
WRITE 1101 Brian M Accounts Manager 2015-02-03 2000
1102 Mrinal M Logistics Clerk 2012-03-02 650
1103 Sunita F Production Asst. 2010-04-01 1900
Manager
1104 Vansh M Accounts Clerk 2009-05-07 700
1105 Samira F Logistics Manager 2011-07-11 2200
STRUCTURED QUERY LANGUAGE( MySQL )
SQL Commands

INSERTING ROWS TO TABLE EMPLOYEE

INSERT INTO EMPLOYEE VALUES(1101, ‘Brian’, ‘M’, ‘Accounts’,


PLEASE
‘Manager’, ‘2015-02-03’, 2000),
WRITE
(1102, ‘Mrinal’, ‘M’, ‘Logistics’, ‘Clerk’, ‘2012-03-02’, 650),
(1103, ‘Sunita’, ‘F’, ‘Production’, ‘Asst. Manager’, ‘2010-04-01’, 1900),
(1104, ‘Vansh’, ‘M’, ‘Accounts’, ‘Clerk’, ‘2009-05-07’, 700),
(1105, ‘Samira’, ‘F’, ‘Logistics’, ‘Manager’, ‘2011-07-11’, 2200) ;
STRUCTURED QUERY LANGUAGE( MySQL )
SQL Commands
Write MySQL commands to the following questions

1) To describe the structure of the table employee


2) To display all records from employee table
PLEASE 3) To display name and designation of all employees
WRITE
4) To display the records in the descending order of their salaries
5) To display name, department and DOJ of all employees whose
salary is between 1500 and 2000
6) To display the details of all managers
7) To display the number of employees department wise
8) To display all records in the ascending order of their DOJ
9) To display the name of employees starting with the letter ‘S’
10) To display the name of employees ending with letter ‘a’
11) To display the name of employees whose name has exactly 5 letters
12) To display the details of male employees
STRUCTURED QUERY LANGUAGE( MySQL )
SQL Commands
ANSWERS
1) Mysql> DESC Employee ;
2) mysql> SELECT * FROM EMPLOYEE ;
PLEASE 3) mysql> SELECT Ename, Desig FROM EMPLOYEE ;
WRITE 4) mysql> SELECT * FROM EMPLOYEE ORDER BY SALARY DESC ;
5) mysql> SELECT Ename, Dept, DOJ FROM EMPLOYEE WHERE SALARY
BETWEEN 1500 AND 2000 ;
6) mysql> SELECT * FROM EMPLOYEE WHERE Desig =‘Manager’ ;
7) mysql> SELECT Dept ,count(Dept) FROM EMPLOYEE GROUP BY Dept ;
8) mysql> SELECT * FROM EMPLOYEE ORDER BY DOJ ASC ;
9) mysql> SELECT Ename FROM EMPLOYEE WHERE Ename like ‘S%’ ;
10) mysql> SELECT Ename FROM EMPLOYEE WHERE Ename like ‘%a’ ;
11) mysql> SELECT Ename FROM EMPLOYEE WHERE Ename like ‘_ _ _ _ _’ ;
12) mysql> SELECT * FROM EMPLOYEE WHERE SEX =‘M’ ;
STRUCTURED QUERY LANGUAGE( MySQL )

PLEASE
WRITE
STRUCTURED QUERY LANGUAGE( MySQL )

Write MySQL commands for the following questions

(a) To change the Basic salary to 10500 of all those teachers from COLLEGE,
who joined the COLLEGE after 01/02/89 and are above the age of 50.
(b) To display -Name, Age and Basic of all those from COLLEGE, who belong
to Physics and Chemistry department only.
(c) To display all the department names from COLLEGE, with no duplication.
(d) To list names of all teachers from COLLEGE with their date of joining in
ascending order within their Basic salaries in ascending order.
(e) To display maximum salary amongst the female teachers and also amongst
the male teachers from COLLEGE. (Give a single command)
(f) To insert a new row in the table COLLEGE with the following data:
15, "ATIN", 27, "Physics", '15/05/02', 8500, "M"
(g) To delete a row from COLLEGE in which name is VIREN.
PLEASE
WRITE
STRUCTURED QUERY LANGUAGE( MySQL )

Write MySQL commands for the following questions

(a)UPDATE COLLEGE SET Basic = 10500 WHERE


DateofJoin>’01/02/89 ' AND Age>50;
(b)SELECT Name, Age, Basic FROM COLLEGE WHERE
Department='Physics' OR Department ='Chemistry' ;
(c)SELECT DISTINCT Department FROM COLLEGE;
(d)SELECT Name,DateofJoin,Basic FROM COLLEGE ORDER BY
Basic,DateofJoin;
(e)SELECT Sex,MAX(Basic) FROM COLLEGE GROUP BY Sex;
(f)INSERT INTO COLLEGE VALUES(15, 'ATIN', 27, 'Physics',
'15/05/02', 8500, 'M');
(g)DELETE FROM COLLEGE WHERE Name = ‘VIREN';
PLEASE
WRITE
STRUCTURED QUERY LANGUAGE( MySQL )

PLEASE
WRITE
STRUCTURED QUERY LANGUAGE( MySQL )

Write MySQL commands for the following questions

(a) Display the names of the students, who have grade ‘C in either
GAME1 or GAME2 or both.
(b) Display the number of students getting grade A in Cricket.
(c) Display the names of the students who have same game for both
GAME1 and GAME2.
(d) Display the games taken up by the students, whose name starts
with A.
(e) Add a new column named MARKS.
(f) Assign a value 200 for Marks for all those, who are getting grade ‘A’
or grade ‘B’ in both GAME1 and GAME2.
PLEASE
WRITE (g) Arrange the whole table in the alphabetical order of Name.
STRUCTURED QUERY LANGUAGE( MySQL )

Write MySQL commands for the following questions

(a)SELECT NAME FROM SPORTS WHERE GRADE ='C’ OR GRADE1='C';


(b)SELECT COUNT(*) FROM SPORTS WHERE (GAMEl='Cricket' AND
GRADE='A' ) OR (GAME2 ='Cricket' AND GRADE1 ='A');
(c)SELECT NAME FROM SPORTS WHERE GAME1=GAME2;
(d)SELECT GAME1, GAME2 FROM SPORTS WHERE NAME LIKE ’ A%';
(e)ALTER TABLE SPORTS ADD MARKS integer;
(f)UPDATE SPORTS SET MARKS = 200 WHERE GRADE = 'A' OR
GRADE = 'B’ OR GRADE1 = 'A' OR GRADE1 = 'B';
(g)SELECT * FROM SPORTS ORDER BY NAME;

PLEASE
WRITE
STRUCTURED QUERY LANGUAGE( MySQL )

PLEASE
WRITE
STRUCTURED QUERY LANGUAGE( MySQL )
Write the SQL commands for (a) to (f) and write the
outputs for SQL queries (g) parts (i) to (iv) on the basis
of the table HOSPITAL.

PLEASE (a) To show all information about the patients of Cardiology Department.
WRITE
(b) To list the name of female patients, who are in Orthopaedic Department.

(c) To list names of all patients with their date of admission in ascending order.

(d) To display Patient’s Name, Charges, Age for male patients only.

(e) To count the number of patients with age>20.

(f) To insert a new row in the HOSPITAL table with the following data:
{11,'Mustafa',37,'ENT','25/02/98',250,'M'}
STRUCTURED QUERY LANGUAGE( MySQL )

(g) Give the output of following SQL statements:


PLEASE (i) SELECT COUNT(DISTINCT Charges) FROM HOSPITAL;
WRITE

(ii) SELECT MIN(Age) FROM HOSPITAL WHERE Sex = 'M' ;

(iii) SELECT SUM(Charges) FROM HOSPITAL WHERE Sex = ' F' ;

(iv) SELECT AVG(Charges) FROM HOSPITAL WHERE Dateofadm <


'12/02/98' ;
STRUCTURED QUERY LANGUAGE( MySQL )
PLEASE
WRITE

(a) SELECT * FROM HOSPITAL WHERE Department = 'Cardiology';

(b) SELECT Name FROM HOSPITAL WHERE Department = 'Orthopaedic' AND


Sex = ' F' ;

(c) SELECT Name FROM HOSPITAL ORDER BY Dateofadm;

(d) SELECT Name, Charges, Age FROM HOSPITAL WHERE Sex = 'M' ;

(e) SELECT COUNT(*) FROM HOSPITAL WHERE Age > 20;

(f) INSERT INTO HOSPITAL VALUES (11,'Mustafa',37,'ENT','25/02/98',250, 'M');


STRUCTURED QUERY LANGUAGE( MySQL )

PLEASE
WRITE
WRITE
Write SQL commands for the following:
(a) Create the above table.

WRITE CREATE TABLE Employee (


Employee_ID integer not null primary key,
Employee_Name varchar(25) not null,
Job_Title varchar(20) not null,
Salary decimal(8,2) not null,
Bonus decimal(8,2),
Age integer,
Manager_ID integer,
FOREIGN KEY (Manager_ID) REFERENCES
Employee(Employee_ID) );
(b) Insert values as shown above.
INSERT INTO Employee VALUES(1201, ‘Divya’, ‘President’, 50000,
WRITE NULL,29, NULL),
(1205, ‘Amyra’, ‘Manager’, 30000, 2500,26, 1201),
(1211, ‘Rahul’, ‘Analyst’, 20000, 1500,23, 1205),
(1213, ‘Manish’, ‘Salesman’, 15000, NULL, 22, 1205),
(1216, ‘Megha’, ‘Analyst’, 22000, 1300, 25, 1201),
(1217, ‘Mohit’, ‘Salesman’, 16000, NULL, 22, 1205) ;

(c) Delete the Employee having Employee_ID 1217.


DELETE FROM Employee WHERE Employee_ID= 1217 ;
(d) Update the salary of “Amyra” to 40000.
UPDATE Employee SET Salary = 40000 WHERE Employee_Name= “Amyra” ;
(e) Alter the table Employee so that NULL values are not allowed
for Age column.
WRITE ALTER TABLE Employee MODIFY Age integer not null ;
(f) Write a query to display names and salaries of those
employees whose salary are greater than 20000.
SELECT Employee_Name, Salary FROM Employee WHERE Salary > 20000 ;
(g) Write a query to display details of employees who are not
getting any bonus.
SELECT * FROM Employee WHERE Bonus IS NULL ;
(h) Write a query to display the names of employees whose name
contains “a” as the last alphabet.
SELECT Employee_Name FROM Employee WHERE Employee_Name LIKE “%a” ;
WRITE
(i) Write a query to display the name and Job title of those employees
whose Manager_ID is 1201.
SELECT Employee_Name,Job_Title FROM Employee WHERE Manager_ID= 1201 ;

(j) Write a query to display the name and Job title of those employees
whose Manager is “Amyra”.
SELECT Employee_Name, Job_Title FROM Employee WHERE Manager_ID= 1205 ;

(k) Write a query to display the name and Job title of those employees
aged between 26 years and 30 years (both inclusive)
SELECT Employee_Name, Job_Title FROM Employee WHERE Age BETWEEN 26 AND 30 ;
Q 2.A Railway company uses machines to sell tickets. The
machine details and daily sales information are recorded
in two tables:
WRITE
Q 2.A Railway company uses machines to sell tickets. The
machine details and daily sales information are recorded
in two tables:
WRITE

The primary key of the table


Machine is Machine_ID.
Records in the table Sales are
uniquely identified by the fields
Machine_ID and Date.
WRITE a) Create the tables Machine and Sales.

CREATE TABLE Machine (Machine_ID char(3) Primary key,


Station Char(30)) ;

CREATE TABLE Sales(Machine_ID Char(3), Date date,


Ticket_Sold integer, Income decimal(8,2),
Primary key(Machine_ID ,Date),
Foreign key Machine_ID References Machine(Machine_ID) );
b) Insert the following data in the table Machine

WRITE

INSERT INTO Machine VALUES(“C01”, “Chennai”),(“C02”, “Chennai”),


(“M01”, “Mumbai”),(“M02”, “Mumbai”),(“N01”, “New Delhi”),
(“N02”, “New Delhi”) ;
b) Insert the following data in the table Sales

WRITE
INSERT INTO Sales VALUES(“C01”, “2019-03-15”,100,7000),
WRITE
(“C01”, “2019-03-16”,200,10000),
(“C02”, “2019-03-15”,150,8000),
(“C02”, “2019-03-16”,350,15000),
(“M01”, “2019-03-15”,125,6250),
(“M01”, “2019-03-16”,150,8000),
(“M02”, “2019-03-15”,200,9000),
(“M02”, “2019-03-16”,100,6000),
(“N01”, “2019-03-15”,100,5000),
(“N01”, “2019-03-16”,150,7500),
(“N02”, “2019-03-15”,200,10000),
(“N02”, “2019-03-16”,100,5000) ;
c) Write a query to find the number of ticket machines in each
station.
WRITE
SELECT Station,COUNT(*) AS “No: of Machines” FROM Machine
GROUP BY Station ;

d) Write a query to find the total ticket income of the station


“New Delhi” of each day.

SELECT Station, Date, SUM(Income) FROM Machine M , Sales S


where M.Machine_ID = S.Machine_ID AND Station =“New Delhi”
GROUP BY Date ;
e) Write a query to find the total number of tickets sold by the
WRITE
machine (Machine_ID = N01) till date.

SELECT Machine_ID, SUM(Tickets_Sold) FROM Sales WHERE


Machine_ID = “N01” ;
LAB WORKSHEET-1
ANSWERS
Q1.
WRITE
WRITE

Q2. Insert the details of 5 employees.

INSERT INTO Employee VALUES(1002, “Varun”,”Sales”,30000),


(1003, “Devesh”,”Accounts”,34000),
(1004, “Krishnan”,”Sales”,25000),
(1005, “Abdul”,”Stores”,38000),
(1006, “Arun”,”Production”,35000) ;
Q3. Display the structure and content of the table.
WRITE
Desc Employee ;
SELECT * FROM Employee ;

Q 4.Display in the following format


Ajay gets a salary 2000 for the employees in Accounts Department.

SELECT Name, “ gets a salary ”, SALARY, “ for the employees in”,


Dept, “ Department” FROM Employee;
Q5. Display the various departments from the table.
WRITE
SELECT DISTINCT(Dept) FROM EMPLOYEE;

Q 6. Add a Column bonus of data type Decimal(8,2).

ALTER TABLE Employee ADD Bonus decimal(8,2) ;

Q7. Compute the bonus as 20% of the salary.

UPDATE Employee SET Bonus = Salary *(20.0/100.0) ;


WRITE
Q8. Add a Column NetPay of type Decimal(10,2).
ALTER TABLE Employee ADD NetPay decimal(10,2) ;

Q 9. Compute Netpay as salary + bonus.

UPDATE Employee SET NetPay = Salary + Bonus;

Q10. Display the names of the employees whose salary is in the range
20,000 – 50,000.

SELECT Name FROM Employee where Salary BETWEEN 20000 AND 50000 ;
WRITE
Q11. Display the details of employees whose name ends with the
letter ‘n’.
SELECT * FROM Employee WHERE Name LIKE “%n” ;

Q12. Display the names of the employees whose name is starting with
letter ‘A’.
SELECT Name FROM Employee WHERE Name LIKE “A%” ;

Q13. Display the name,department and salary of employees having


exactly 5 letters in the name.
SELECT Name, Dept,Salary FROM Employee WHERE Name LIKE “_ _ _ _ _” ;
WRITE
Q14. Display the details of employees who have the letter
combination ‘sh’ in their name.
SELECT * FROM Employee WHERE Name LIKE “%sh%” ;

Q15. Change the data type of Dept to 12 characters.

ALTER TABLE Employee MODIFY Dept char(12) ;

Q16. Delete the details of the employees from Sales Department.

DELETE FROM Employee WHERE Dept =“Sales” ;


Q17. Drop the column Bonus from the table.

WRITE ALTER TABLE Employee DROP Bonus;

Q18. Drop the default value for Salary.


ALTER TABLE Employee ALTER Salary DROP DEFAULT;

Q19. Add a new default value for salary as 3500.

ALTER TABLE Employee ALTER Salary SET DEFAULT 3500;

Q.20 Delete the table.


DROP TABLE Employee ;
LAB WORKSHEET-2
ANSWERS
WRITE Q1.
CREATE TABLE PAINTING( ID integer Primary Key,
A_NAME char(20) ,
TITLE char(25) ,
PRICE decimal(10,2) ,
TYPE char(25) ) ;

CREATE TABLE GALLERY( G_ID integer Primary Key,


FEES decimal(8,2),
G_NAME char(20) ,
D_OF_DISPLAY date ) ;
LAB WORKSHEET-2
ANSWERS
WRITE Q2. Insert the records in the tables with the given values.

INSERT INTO GALLERY VALUES (113, 5000,”RENIM”, “2010-12-10”) ,


(103, 30000,”AMYA”, “2001-02-11”) ,
(110, 6000,”TRIKHA”, “2002-11-10”) ;
WRITE

Q3. Display A_NAME(Artist Name) and TITLE of all Modern type paintings.

SELECT A_NAME, TITLE FROM PAINTING WHERE TYPE = “MODERN” ;

Q4. Display all the details of all the Paintings in descending order of TITLE.

SELECT * FROM PAINTING ORDER BY TITLE DESC ;


WRITE
Q5.Display the A_NAME, G_NAME and Date of Display (D_OF_DISPLAY) for
all the Paintings which are having a display at the gallery from the tables
PAINTING and GALLERY.

SELECT A_NAME, G_NAME, D_OF_DISPLAY FROM PAINTING P, GALLERY G


WHERE P.ID = G.G_ID ;

Q6. Display the highest price of paintings in each type from table PAINTING.
SELECT TYPE, MAX(PRICE) FROM PAINTING GROUP BY TYPE ;
WRITE
Q7.Display A_NAME , TITLE and PRICE of all Paintings whose PRICE in the
range 120000 and 300000.

SELECT A_NAME, TITLE,PRICE FROM PAINTING WHERE PRICE BETWEEN


120000 AND 300000 ;

Q8. Display the different TYPE from the table PAINTING.

SELECT DISTINCT(TYPE) FROM PAINTING ;


WRITE
Q9. Find the highest and lowest FEES from GALLERY table.

SELECT MAX(FEES) ,MIN(FEES) FROM GALLERY ;

Q10. Find the number of records whose PRICE is less than 30000 from the
table PAINTING.

SELECT COUNT(PRICE) FROM PAINTING WHERE PRICE < 30000;


WRITE
Q11. Display the Average value of FEES from table GALLERY.

SELECT AVG(FEES) FROM GALLERY ;

Q12. Display the sum of PRICE of ABSTRACT Paintings from table PAINTING
under the heading TOTAL.

SELECT SUM(PRICE) AS “TOTAL” FROM PAINTING WHERE TYPE = “ABSTRACT” ;


Q13. Display 10% of PRICE under the heading DISCOUNT.
WRITE

SELECT PRICE*(10.0/100.0) AS “DISCOUNT” FROM PAINTING ;

Q14. Display the records in descending order of Price.

SELECT * FROM PAINTING ORDER BY PRICE DESC ;

Q 15. Display the lowest price in ABSTRACT category.

SELECT MIN(PRICE) FROM PAINTING WHERE TYPE = “ABSTRACT” ;


Q16. Display the paintings which are having the letter ‘R’
WRITE
anywhere in TITLE.

SELECT * FROM PAINTING WHERE TITLE LIKE “%R%” ;

Q17. Display all TYPE from table PAINTING.

SELECT TYPE FROM PAINTING ;

Q 18. Display the number of different TYPE from table PAINTING.

SELECT TYPE,COUNT(TYPE) FROM PAINTING GROUP BY TYPE ;


Q19. Delete the records whose PRICE is greater than 300000.
WRITE
DELETE FROM PAINTING WHERE PRICE > 300000 ;

Q20. Delete both the tables PAINTING and GALLERY.

DROP TABLE PAINTING , GALLERY ;


REVISION
1. USE keyword in MYSQL is used to select a
I. Table
II.Column
III.Database
IV.All of the above

2. An attribute of a relation means


I. A Row
II. A Column
III. Total rows.
IV. Total columns
3. The wild card character used in MYSQL for pattern
searching is
I. * (asterisk)Database
II. % (percentage)
III. & (ampersand)
IV.- (hyphen)

4. Which of the following is an aggregate function ?


I. Calculate()
II.Sum()
III.Find()
IV.Search()
5. On executing DELETE command, if you get an error
‘‘foreign key constraint’’, what does it imply ?
I. Foreign key is not defined
II.Table is empty
III.Connectivity issue
IV.Data is present in the other table

6. What is the default order of sorting in ORDER BY clause?


I. DESC
II.ASC
III.Both
IV.None of these
7. Which operator performs pattern matching ?
I. BETWEEN operator
II. LIKE operator
III.EXISTS operator
IV.None of the above

8. In SQL which command is used to change a table’s


storage characteristics ?
I. Alter table
II.Modify table
III.Change table
IV.All of the above
9. Which of the following is a DML command?
I. Create Table
II.Select
III.Alter
IV.Drop

10. The data type of values in each column is called _____


I. Tuple
II.Domain
III.Attribute
IV.Degree
Answers

1. Database
2. A Column
3. % (percentage)
4. Sum()
5. Data is present in the other table
6. ASC
7. LIKE operator
8. Alter table
9. Select
10. Domain
LAB WORKSHEET-3
ANSWERS

WRITE
CREATE TABLE TRAINER(TID integer Primary Key,
TNAME char(20) ,
TCITY char(20) ,
HIREDATE date,
SALARY decimal(8,2) ) ;

CREATE TABLE COURSE(CID char(5) Primary Key,


CNAME char(20),
FEES decimal(8,2) ,
STARTDATE date ,
TID integer,
FOREIGN KEY TID REFERENCES TRAINER(TID) );
LAB WORKSHEET-3
ANSWERS
WRITE Insert the records in the tables with the given values.

INSERT INTO TRAINER VALUES (101, “SUNAINA”, “MUMBAI”,“1998-10-15”,90000) ,


(102, “ANAMIKA”, “DELHI”, “1994-12-24”,80000),
(103, “DEEPTI”, “HANDIGARG”, “2001-12-21”,82000),
(104, “MEENAKSHI”, “DELHI”, “2002-12-25”,78000),
(105, “RICHA”, “MUMBAI”, “1996-01-02”,95000),
(106, “MANIPRABHA”, “CHENNAI”, “2001-12-12”,69000) ;
LAB WORKSHEET-3
ANSWERS
WRITE Insert the records in the tables with the given values.

INSERT INTO COURSE VALUES (“C201”, “AGDCA”, 12000,“2018-07-02”,101) ,


(“C202”, “ADCA”, 15000,“2018-07-15”,103),
(“C203”, “DCA”, 10000,“2018-10-01”,102),
(“C204”, “DDTP”, 9000,“2018-09-15”,104),
(“C205”, “DHN”, 20000,“2018-08-01”,101),
(“C206”, “O LEVEL”, 18000,“2018-07-25”,105) ;
WRITE

Q1. Display the Trainer Name, City & Salary in descending order of their
Hiredate.

SELECT TNAME, CITY, SALARY FROM TRAINER ORDER BY HIREDATE DESC ;

Q2. Display the TNAME and CITY of trainer who joined the Institute in the month
of December 2001.

SELECT TNAME,CITY FROM TRAINER WHERE HIREDATE BETWEEN “2001-12-01” AND


“2001-12-31” ;
WRITE

Q3. Display TNAME, HIREDATE, CNAME, STARTDATE from tables TRAINER


and COURSE of all those courses whose FEES is less than or equal to 10000.

SELECT TNAME, HIREDATE, CNAME,STARTDATE FROM TRAINER T, COURSE C


WHERE T.TID = C.TID AND FEES <= 10000;

Q4. Display number of Trainers from each city.

SELECT CITY, COUNT(CITY) FROM TRAINER GROUP BY CITY ;


WRITE

Q5. Display TID, TNAME for those trainers who does not belong to DELHI and
MUMBAI.

SELECT TID,TNAME FROM TRAINER WHERE CITY NOT IN(“DELHI”,”MUMBAI”) ;

Q6. Display the different cities listed in table TRAINER

SELECT DISTINCT CITY FROM TRAINER ;


WRITE

Q7. Display the minimum fees of each Course.

SELECT CNAME,MIN(FEES) FROM COURSE GROUP BY CNAME;

Q8. Display the total fees for the course which started before 2018-09-15

SELECT SUM(FEES) FROM COURSE WHERE STARTDATE < “2018-09-15” ;


WRITE

Q9. Display the details of COURSE table in ascending order of FEES.

SELECT * FROM COURSE ORDER BY FEES ASC ;

Q10. Display the details of TRAINER table whose TNAME starts with the letter
‘M’.

SELECT * FROM TRAINER WHERE TNAME LIKE “M%”;


WRITE

Q11. Display SALARY and 20% of SALARY of all TRAINERS from the table
under the heading ‘BONUS’.

SELECT SALARY, SALARY * 0.20 AS “BONUS” FROM TRAINER ;

Q12. ADD a new record in TRAINER table with the data


108, RAJ,MUMBAI,2001-08-23,70000.

INSERT INTO TRAINER VALUES (108 ,“RAJ”, “MUMBAI”, “2001-08-23”,70000) ;


WRITE

Q13. Change the SALARY of RICHA as 100000.

UPDATE TRAINER SET SALARY = 100000 WHERE TNAME =“RICHA” ;

Q14. Display the number of records from COURSE table whose Fees is greater
than 10000.

SELECT COUNT(*) AS “GREATERTHAN10000” FROM COURSE WHERE FEES >10000 ;


WRITE

Q15. Remove the records of TRAINERS who were hired after 2000-01-01.

DELETE FROM TRAINER WHERE HIREDATE > “2000-01-01” ;

Q16. Add a new column HRA (Decimal (10,2) to TRAINER table.

ALTER TABLE TRAINER ADD HRA decimal(10,2) ;


WRITE

Q17. Find the average salary of Trainers from Mumbai.

SELECT AVG(SALARY) FROM TRAINER WHERE CITY = “MUMBAI”;

Q18. Write the output of the following command:


SELECT TID, COUNT(*), MAX(FEES) FROM COURSE GROUP BY TID HAVING COUNT(*) > 1;
WRITE

Q19. Display TNAME, CITY, CNAME and FEES from the two tables.

SELECT TNAME,CITY,CNAME,FEES FROM TRAINER T, COURSE C WHERE T.TID = C.TID ;

Q20. Remove the table COURSE.

DROP TABLE COURSE ;


LAB WORKSHEET-4
ANSWERS
WRITE

CREATE TABLE OWNER(PLACE char(20) ,


OWNEDBY char(20) ) ;

CREATE TABLE RESORT(RCODE char(10) Primary Key ,


PLACE char(20),
RENT decimal(8,2) ,
TYPE char(10) ,
STARTDATE date ) ;
LAB WORKSHEET-4
ANSWERS
WRITE Insert the records in the tables with the given values.

INSERT INTO OWNER VALUES( “GOA”, “SUN VILLAGE”) ,


( “KERALA”, “KTDC”) ,
( “HIMACHAL”, “KALRA RESORTS”) ,
( “GUJARAT”, “KINJAL GROUP”) ,
( “ORISSA”, “OTDC”) ;
LAB WORKSHEET-4
ANSWERS
WRITE Insert the records in the tables with the given values.

INSERT INTO RESORT VALUES (“R101”, “GOA”, 15000, “5 Star”, “2008-01-23”) ,


(“R102”, “HIMACHAL”, 12000, “4 Star”, “2007-11-12”) ,
(“R103”, “KERALA”, 12500, “5 Star”, “2006-03-18”) ,
(“R104”, “HIMACHAL”, 10900, “3 Star”, “2007-01-09”) ,
(“R105”, “GUJARAT”, 8000, “2 Star”, “2008-04-29 ”) ;
WRITE

Q1. To display the RCODE and PLACE of all ‘2 Star’ resorts.

SELECT RCODE, PLACE FROM RESORT WHERE TYPE = “2 Star” ;

Q2. To display the details of RESORT in the alphabetical order of the place.

SELECT * FROM RESORT ORDER BY PLACE ASC ;


WRITE

Q3. To display the maximum rent for each type of resort from table RESORT.

SELECT TYPE, MAX(RENT) FROM RESORT GROUP BY TYPE ;

Q4. To display the details of all resorts which are started after 31-Dec-04 from
table RESORT.

SELECT * FROM RESORT WHERE STARTDATE > “2004-12-31”;


WRITE

Q5. To display the owner name(ownedby) of all ‘5 Star’ resorts from tables
RESORT and OWNER.

SELECT OWNEDBY FROM OWNER O, RESORT R WHERE O.PLACE = R.PLACE


AND TYPE = “5 Star” ;

Q6. To change the TYPE of RCODE R104 as 4 Star


UPDATE RESORT SET TYPE = “4 Star” WHERE RCODE = “R104” ;
WRITE

Q7. To find the total rent of 5 star types.

SELECT SUM(RENT) FROM RESORT WHERE TYPE = “5 Star” ;

Q8. To remove the details of all records whose RENT is below 10000.

DELETE FROM RESORT WHERE RENT < 10000 ;


WRITE

Q9. To display the least RENT from RESORT table.

SELECT MIN(RENT) FROM RESORT ;

Q10. To display 25% of RENT under the heading ‘DISCOUNT’.

SELECT RENT*0.25 AS “DISCOUNT” FROM RESORT;


WRITE

Q11. To add a new record with the data R106,GOA,13000, 5STAR,24 May 2010
to the table RESORT.

INSERT INTO RESORT VALUES (“R106”, “GOA”, 13000, “5 Star”, “2010-05-24”) ;

Q12. To insert one more column called ADDRESS with the data type
VARCHAR(30).
ALTER TABLE RESORT ADD ADDRESS varchar(30) ;
WRITE

Q13. To find the total RENT of all resorts from GOA.

SELECT SUM(RENT) FROM RESORT WHERE PLACE = “GOA”;

Q14. To display the details of resorts whose PLACE is ending with the letter ‘A’.

SELECT * FROM RESORT WHERE PLACE LIKE “%A” ;


WRITE

Q15. To display TYPE and STARTDATE in descending order of STARTDATE.

SELECT TYPE, STARTDATE FROM RESORT ORDER BY STARTDATE DESC ;

Q16. To show the number of different TYPE from the table RESORT.

SELECT TYPE, COUNT(TYPE) FROM RESORT GROUP BY TYPE;


WRITE

Q17. To display different TYPE from RESORT.

SELECT DISTINCT TYPE FROM RESORT ;

Q18. To display all TYPE from RESORT.

SELECT TYPE FROM RESORT;


WRITE

Q19. Find the number and maximum rent of resort of each TYPE.

SELECT TYPE,COUNT(*),MAX(RENT) FROM RESORT GROUP BY TYPE ;

Q20. Delete the table RESORT.

DROP TABLE RESORT ;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy