SQL I

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

UNIT-4

RELATIONAL DATABASE MANAGEMENT SYSTEM

- UNDERSTANDING RELATIONAL DATABASE MANAGEMENT SYSTEM


- INTRODUCTION TO MY SQL
- DML COMMANDS
INTRODUCTION

Today, we are living in an era of BIG DATA so there is a need to store the data efficiently. There
are software or programs used to store computerized databases being used almost everywhere.
Such as Airforce, Police force, Medical Researches, Entertainment uses various computerized
databases for different purposes. In schools, library stores details of all their books in a
computerized database. When we want to know if a book is in stock, we cannot only look it up, but
can also check when it is due to be returned. The database also records details of all the borrowers,
what books they currently have borrowed and when they are due back.

Database Management System (DBMS)

To create and maintain a database on a computer, we need a database program or software, called
a Database management system, or DBMS. Database Management System is a software that
enables users to create and maintain databases. The popular DBMSs are MySQL, PostgreSQL,
Microsoft Access, Oracle, Microsoft SQL Server, DB2 and Sybase.

DBM S allow us to:


· store data in a structured way.
· query the database (that is, ask questions about the data)
· sort and manipulate the data in the database
· validate the data entered and check for inconsistencies
· produce flexible reports, both on screen and on paper, that make it easy to comprehend the
information stored in the database.

Relational Database

In the database named Learner shown below, the data is organized into separate tables. Once the
tables have been set up, a relationship can be created to link them together. Such a database that
stores data in separate tables that are related through the use of a common column is called a
Relational database.

Benefits of using a DBMS are:


a. Redundancy can be controlled

b. Inconsistence can be avoided

c. Data can be shared

d. Security restrictions can be applied.

RDBM S Terminology

1. Domain

It is pool of values or the collection (set) of possible values from which the value for a column
is derived.

2. Tables or Relation in a Database

Relational Databases store data or information in tables. A table is similar to a spreadsheet where
data is stored in rows and columns. A table refers to a two-dimensional representation of data using
rows and columns. The tables in a database are generally related to each other to facilitate efficient
management of the database. Interrelated tables also reduce the chances of errors in the database.

For example, consider the following table named Customer with details about customers:

2. Record - The horizontal subset of the Table is known as a Row/Tuple. Each row represents a
record, which is a collection of data about a particular entity such as person, place or thing.

3. Field - The vertical subset of the Table is known as a Column/Attribute. The term field is also
often used for column. Each column has a unique name and the content within it must be of the
same type.

4. M ySQL: It is an Open Source RDBMS Software. It is available free of cost.


5. Key: A column or a combination of columns which can be used to identify one or more rows
(tuples) in a table is called a key of the table.

6. Primary Key: The group of one or more columns used to uniquely identify each rowof a relation
is called its Primary Key.

When you got admission in the school, you were given an Admission number. The Admission
number assigned to you was not assigned to any other student of your school (it is unique). When
patients go to a hospital, each patient is given a unique patient number. When you go to open an
account in the bank, you are given a unique account number. Admission number, Patient number,
Account number are all examples of Primary key. A primary key is a field in a table that is unique
for each record. Every database table should have a column or a group of columns designated as
the primary key. The value this key holds should be unique for each record in the table. Some more
examples of Primary key are: Accession Number of a Book in the Book table, Employee ID of an
employee in the Employee Table, Item Code of an item in the Stock table, Flight Number of a flight
in the Flight Master Table, etc.

The purpose of a primary key is to uniquely identify each record in a table.

7. Candidate Key: A column or a group of columns which can be used as the primary key of a
relation is called a Candidate key because it is one of the candidates available to be the primary
key of the relation.

In a table, there may be more than one field that unique ly identifies a record. All such fields are
called candidate keys. A Candidate key is an attribute (or set of attributes) that uniquely identifies a
row. A Primary Key is one of the candidate keys. A table may have more than one candidate keys
but definitely has one and only one primary key.

8. Alternate Key: A candidate key of a table which is not selected as the primary key is called its
Alternate Key.

Example: Consider the following Table, RollNo and Admission_no both may be used to uniquely
identify each row in this Table, so both are candidate keys.

Candidate keys which are not made primary key are called Alternate keys. In the above example,
if we use one of the candidate keys, say, Admission_No as the Primary Key, the other Candidate
Key RollNo is the Alternate Key and vice-versa.
9. Foreign Key: A primary key of a base table when used in some other table is called as Foriegn
Key.

For example: Table Employee has columns : EMPID, EMPNAME, ADDRESS, CONTACT NO,
DEPTID. And the table Department has columns : DEPTID, DNAME, CITY. Then the DEPTID
column of the Employee table will be known as Foreign Key because it is declared as Primary Key
in the Department table.

Note : The primary key column and the foreign key column must have the same data type and size.

Introduction to MySQL:

MySQL is a relational database management system (RDBMS). It is pronounced as "My Sequel".


MySQL was originally founded and developed in Sweden by David Axmark, Allan Larsson and
Michael Widenius, who had worked together since the 1980s.

Characteristics of MySQL:

MySQL is released under an open-source license so it is customizable.

It requires no cost or payment for its usage.


MySQL has superior speed, is easy to use and is reliable.
MySQL uses a standard form of the well-known ANSI-SQL standards.
MySQL is a platform independent application which works on many operating systems like
Windows, UNIX, LINUX etc. and has compatibility with many languages including JAVA , C++,
PHP, PERL, etc.
MySQL is an easy to install RDBMS and is capable of handling large data sets.

Since MySQL is released under an open-source license, it does not require any cost or payment
for its usage. Any one can download this software from specific location on Internet. If you want to
download, follow the following steps. The step for two most popular OS platform, Windows and
Linux are discussed here.

DOWNLOADING MySQL [Windows Environment]:

Installation file for MySQL may be downloaded from the link:

https://www.mysql.com/downloads/
Scroll the above screen and Click on the "Download" button for the Community Server and choose
from the list of supported platforms (i.e., operating systems that it will run on), which include 32 -bit
and 64-bit Windows, several different Linux, Solaris, Mac OS X, and a few others.

(Choose appropriate download link as per the operating system)


Keep selecting the default options provided in subsequent windows. If the configuration does not
encounter any errors, then information will be prompted that the configuration file was created,
MySQL server was installed and started, and the security settings applied.
Note : In the process of configuration of MySQL, a prompt for password will be displayed - Here you
should enter a password and remember this password, as it will be required each time to start
MySQL.

Categories of SQL Commands


SQL commands can be classified into the following categories:
1. Data Definition Language (DDL) Commands
The DDL part of SQL permits database tables to be created or deleted. It also defines indices
(keys), specifies links between tables, and imposes constraints on tables.
Examples of DDL commands in SQL are:

CREATE DATABASE - creates a new database


CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table

2. The Data Manipulation Language (DML) Commands


The query and update commands form the DML part of SQL: Examples of DDL comma nds are:

SELECT - extracts data from a table


UPDATE - updates data in a table
DELETE - deletes data from a table
INSERT INTO - inserts new data into a table

M ySQL Data Types


Before we learn about making a table, there is one thing we need to understand first: Data Types.
They indicate the type of data that you are storing in a given table column. So, what are the
different Data Types available in MySQL? Here is a list of some of the most common ones and
what type of values they hold:

Class Data Type Description Example


Text CHAR(size) A fixed-length string from 1 'Maths'
to 255 characters in length "TexT"
right-padded
with spaces to the specified
length
when stored.
Values must be enclosed in
single quotes or double
quotes

Text VARCHAR(size) A variable-length string from 'Computer'


1 to 255 characters in length; "good morning"
i.e. VARCHAR(25).
Values must be
enclosed in single quotes or
double quotes.
Numeric DECIMAL(size,d) It can represent number with 17.32
or without the fractional part. 345
The maximum number of
digits may be specified in the
size parameter. The
maximum number of digits to
the right of the decimal point
is specified in the d
parameter
Numeric INT Or INTEGER It is used for storing integer . 76
values. You can specify a
width upto 11
Date DATE It represents the date '2009-07-
including
day, month and year
Time TIME It represents time. '-838:59:59'
Format: HH:MM:SS '838:59:59'

Creating a Database
Before creating a table we will first create a database.To create a database we will give
CREATE DATABASE command.

syntax:-CREATE DATABASE <database name>;

mysql> CREATE DATABASE School;

Once the above mentioned statement gets executed, a database with the name School is created
on system. You may give any name of the database . Now to open the database to work USE
statements are required. ! Semicolon is standard way to end SQL statement

Using a database
Syntax: USE <databasename>;
mysql> USE School;
Database Changed

Viewing the current database


We must know which database we are currently working in, to see the name of the current
database we use SELECT command.
Syntax: SELECT DATABASE();
School will be displayed.

Creating a Table
After creating a database, the next step is creation of tables in the database. For this CREATE
TABLE statement is used.

Syntax:
CREATE TABLE <TableName>(<ColumnName1> <Data Type1>,
<ColumnName2> <Data Type2>
Create a simple table named Learner with only two columns RollNo and Name in the School
database.
To do this, enter the following statement:
mysql> CREATE TABLE Learner
(RollNo INTEGER,
Name VARCHAR(25));
Query OK, 0 rows affected (0.16 sec) will be displayed.

If table Student already exists in database school, then the error message "Table Student already
exists" is displayed. Give meaningful name to a table. If a table will store information about students,
name it STUDENT. Table names and column names are not case sensitive. For example,
STUDENT is treated the same as STUDENT or student. Each column in the table is given a unique
name. In the example above the column names are Rollno, Name etc. This doesn't mean each
column that is named has to be unique within the entire database. It only has to be unique within
the table where it exists. Also notice that the names do not use any spaces. When naming tables
and columns be sure to keep it simple with letters and numbers. Spaces and symbols are invalid
characters except for underscore(_). Column names like first_name, last_name, email are valid
column names.

Adding constraints in table


Many times it is not possible to keep a manual check on the data that is going into the tables. The
data entered may be invalid. MySQL provides some rules, called Constraints, which help us, to
some extent, ensure validity of the data. These constraints are:

Constraint Purpose
Primary Key Sets a column or a group of columns as a
primary key of the table. Therefore, NULLs
and Duplicate values in this column are not
accepted.
NOT NULL Makes sure that NULLs are not accepted in
the specified column.
FOREIGN KEY Data will be accepted in this column, if the
same data value exists in a column in
another related table. This other related
table name and column name are specified
while creating the foreign key constraint.
UNIQUE Make sure that duplicate values in the
specified column are not accepted.

Recall that the primary key of a table is a column or a group of columns that uniquely identifies a
row of the table. Therefore no two rows of a table can have the same primary key value. Now
suppose that the table Shoes is created with the following statement:

CREATE TABLE Shoes


(Code CHAR(4),
Name VARCHAR(20),
type VARCHAR(10),
size INT(2),
cost DECIMAL(6,2),
margin DECIMAL(4,2),
Qty INT(4));
We know that in this table Code is the Primary key. But, MySQL does not know that ! Therefore it is
possible to enter duplicate values in this column or to enter NULLs in this column. Both these
situations are unacceptable. To make sure that such data is not accepted by MySQL, we can set
Code as the primary key of Shoes table. It can be done by using the PRIMARY KEY clause at the
time of table creation as follows:

CREATE TABLE Shoes


(Code CHAR(4) PRIMARY KEY,
Name VARCHAR(20),
type VARCHAR(10),
size INT(2),
cost DECIMAL(6,2),
margin DECIMAL(4,2),
Qty INT(4));
or as follows:

CREATE TABLE Shoes (Code CHAR(4), Name VARCHAR(20), type VARCHAR(10),size INT(2),
cost DECIMAL(6,2), margin DECIMAL(4,2),Qty INT(4), PRIMARY KEY (Code));

To create a table Bills with the combination of columns Order_No and Cust_Code as the primary
key, we enter the statement:

CREATE TABLE bills


(Order_Num INT(4) PRIMARY KEY,
cust_code VARCHAR(4) PRIMARY KEY,
bill_Date DATE, Bill_Amt DECIMAL(8,2));

Contrary to our expectation, we get an error (Multiple primary key defined) with this statement. The
reason is that MySQL interprets this statement as if we are trying to create two primary keys of the
table - Order_Num, and Cust_code. But a table can have at most one primary key. To set this
combination of columns a primary key we have to enter the statement as follows:

CREATE TABLE bills


(Order_Num INT(4), cust_code VARCHAR(4),bill_Date date, Bill_Amt DECIMAL(8,2),
PRIMARY KEY(Order_Num, cust_code));

Let us now check the table structure with the command: DESC bills;
The table structure is as shown below:
+-----------------+---------------------+----------+--------+-----------+------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+----------+--------+-----------+------------+
| Order_Num | INT(4) | NO | PRI | 0 | |
| cust_code | VARCHAR(4) | NO | PRI | | |
| bill_Date | date | YES | | NULL | |
| Bill_Amt | DECIMAL(8,2) | YES | | NULL | |
+-----------------+---------------------+----------+--------+-----------+------------+
NOT NULL CONSTRAINT
Many times there are some columns of a table in which NULL values should not be accepted. We
always want some known valid data values in these columns. For example, we cannot have an
order for which the customer code is not known. It means whenever we enter a row in the orders
table, corresponding customer code cannot be NULL.
Similarly while entering records in the Shoes table, we have to mention the Shoe size, it cannot be
set NULL. There may be any number of such situations.
While creating a table we can specify in which columns NULLs should not be accepted as follows:

CREATE TABLE Shoes


(Code CHAR(4) PRIMARY KEY, Name VARCHAR(20),type VARCHAR(10), size INT(2) NOT
NULL,cost DECIMAL(6,2), margin DECIMAL(4,2), Qty INT(4));

CREATE TABLE bills


(Order_Num INT(4), cust_code VARCHAR(4),bill_Date DATE, Bill_Amt DECIMAL(8,2) NOT
NULL,PRIMARY KEY (Order_Num, cust_code));

Now if we try to enter a NULL in the specified column, MySQL will reject the entry and give an
error.

Viewing the tables in the database


To see a list of tables present in the current database we will use SHOW TABLES.
Syntax: SHOW TABLES;
mysql> SHOW TABLES;
+------------------------+
| Tables_in_school |
+------------------------+
| Learner |
|-------------------------+
1 row in set (0.00 sec)

Viewing the structure of the table


The DESCRIBE statement can be used to see the structure of a table as indicated in the Create
Statement. It displays the Column names, their data types, whether Column must contain data,
whether the Column is a Primary key.
Syntax:
DESCRIBE <table name>;
OR
DESC <table name>;
mysql> DESCRIBE Student;
+-----------+-------------------+--------+-------------+---------+----------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------------+------ +------------+---------+-----------+
| Rollno | int(11) | YES | | NULL | |
| Name | varchar(25) | YES | | NULL | |
| Gender | char(1) | YES | | NULL | |
| Marks1 | decimal(4,1) | YES | | NULL | |
+----------+-----------------+----------+------------+--------------+----------+
4 rows in set (0.01 sec)
! The word "DESC" can also be used in place of "DESCRIBE"

The table structure also includes the constraints, if any. Therefore, when we use DESC
command,we are shown the table structure as well as constraints, if any. A constraint is shown
beside the column name on which it is applicable. E.g., the statement:
DESC Shoes;
displays the table structure as follows:
+--------+-----------------------+-------+-------+---------+---------
| Field | Type | Null | Key | Default | Extra |
+--------+-----------------------+---------+-----+---------+--------
| Code | CHAR(4) | NO | PRI | NULL | |
| Name | VARCHAR(20) | YES | | | |
| type | VARCHAR(10) | YES | | NULL | |
| size | INT(2) | NO | |0 | |
| cost | DECIMAL(6,2) | YES | | NULL | |
| margin | DECIMAL(4,2) | YES | | NULL | |
| Qty | INT(4) | YES | | NULL | |
+---------+--------------------+--------+-------+---------+--------

M odifying the structure of table


When we create a table we define its structure. We can also change its structure i.e. dd,remove or
change its column(s) using the ALTER TABLE statement.ALTER TABLE is used to add a
constraint,to remove a constraint,to remove a column from a table,to modify a table column.
Syntax:
ALTER TABLE <table_name> ADD/DROP <column_name> [datatype];
ALTER TABLE <table> MODIFY <column> <new_definition>;

If we want to add a column named Games in the student table .


mysql> ALTER TABLE Student ADD Games VARCHAR(20);
To check the structure of the table to see that the new column Games is added use DESCRIBE
command
mysql> DESCRIBE Student;
+--------+----------------+------+------+---------+--------+
| Field | Type | Null | Key | Default | Extra |
+--------+----------------+------ +-----+----------+--------+
| Rollno | int(11) | YES | | NULL | |
| Name | varchar(25) | YES | | NULL | |
| Gender | char(1) | YES | | NULL | |
| Marks1 | decimal(4,1) | YES | | NULL | |
| Games | varchar(20) | YES | | NULL | |
+--------+--------------+------+-----+---------+------------+

After execution of the above ALTER TABLE statement, the Games column is added and
a NULL value is assigned to all the rows in this column.
Now, suppose we want to change the newly added Games column to hold integers(in
place of character data) using ALTER TABLE statement:
mysql> ALTER TABLE Student MODIFY games INTEGER;

To delete a column of a table the ALTER TABLE statement is used with Drop clause.

mysql> ALTER TABLE Student DROP Games;

mysql> DESC student;


+--------+-----------------+--------+-----+---------+--------+
| Field | Type | Null | Key | Default | Extra |
+--------+-----------------+------+-----+---------+----------+
| Rollno | int(11) | YES | | NULL | |
| Name | varchar(25) | YES | | NULL | |
| Gender | char(1) | YES | | NULL | |
| Marks1 | decimal(4,1)| YES | | NULL | |
+--------+--------------+------+-----+---------+-------------+
4 rows in set (0.00 sec)
The above display shows that Games column is removed from the table.

Add, M odify, and Remove constraints:

If we create a table without specifying any primary key, we can still specify its primary key by
ALTER TABLE command. Suppose we have created the Shoes table without specifying any
Primary key, then later we can enter the statement as follows:

ALTER TABLE Shoe ADD PRIMARY KEY(code);

This will set Code as the primary key of the table. But if the Code column already contains some
duplicate values, then this statement will give an error. In MySQL, it is also possible to change the
primary key column(s) of a table. Suppose, in the Shoes table, instead of Code, we want to set
the combination of 'Name' and 'Size' as the primary key. For this first we have to DROP the
already existing primary key (i.e Code) and then add the new primary key (i.e., Name and Size).
The corresponding statements are as follows:

ALTER TABLE Shoes DROP PRIMARY KEY;


After this statement, there is no primary key for the Shoe table. Now we can add the new primary
key as follows:
ALTER TABLE Shoes ADD PRIMARY KEY (Name, Size);

Now if we see the table structure by DESC Shoes; statement, it will be shown as follows:
+--------+-----------------------+------+--------+-----------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-----------------------+------+--------+-----------+-------+
| Code | CHAR(4) | NO | | NULL | |
| Name | VARCHAR(20) | NO | PRI| | |
| type | VARCHAR(10) | YES | | NULL | |
| size | INT(2) | NO | PRI | 0 | |
| cost | DECIMAL(6,2) | YES | | NULL | |
| margin | DECIMAL(4,2) | YES | | NULL | |
| Qty | INT(4) | YES | | NULL | |
+--------+-----------------------+------+---------+-------+-----------+
In MySQL, it is not possible to add or drop NOT NULL constraint explicitly after the table creation.
But it can be done using the MODIFY clause of ALTER TABLE command. As an example,
suppose we don't want to accept NULL values in bill_date column of bills table, we can issue the
statement:
ALTER TABLE bills MODIFY bill_date DATE NOT NULL;

Although any column of a table can be removed, MySQL puts the restriction that a primary key
column can be removed only if the remaining, primary key columns, if any, do not contain any
duplicate entry. This can be understood more clearly with the help of following example:

The Name and Size columns of the Shoe table constitute its primary key. Now if we drop the Name
column from the table, Size will be the remaining Primary Key column of the table. Therefore,
duplicate entries in the Size column should not be allowed. To ensure this, before removing the
Name column from the table, MySQL checks that there are no duplicate entries present in the Size
column of the table. If there are any, then the statement trying to remove the Name column from
the table will result in an error and the Name column will not be removed. If there are no duplicate
entries in the Size column, then the Name column will be removed. Similar will be the case with the
Name column, if we try to remove the Size column. But there won't be any problem if we try to
remove both the primary key columns simultaneously with one ALTER TABLE statement as follows:
ALTER TABLE Shoes DROP name, DROP size;

Deleting the structure of the table


Sometimes there is a requirement to remove a table from the database. In such cases we don't
want merely to delete the data from the table, but we want to delete the table itself. DROP TABLE
command is used for this purpose. The syntax of DROP TABLE command is as follows:
DROP TABLE <tablename>;
e.g. to remove the table Orders from the database we enter the statement:
DROP TABLE Orders;
And after this statement orders table is no longer available in the database. It has been removed.

DM L COMMANDS :

DML stands for Data Manipulation Language. DML commands are used for retrieving, inserting,
modifying/updating or deleting data from a relation. is used to manipulate the data in the relation.
Following are the DML commands :
- INSERT
- SELECT
- UPDATE
- DELETE

INSERT COMM AND


After creating database and relations, we can add data in the relations. INSERT INTO command
is used to enter values in a table. Syntax of insert command is as follows :

INSERT INTO <TABLENAME >(COLUMN

INSERT command is used in various ways to insert values within a table. Following points should
be kept in mind while inserting records in a relation. :
- Numeric values may be entered as numerals
- string must be enclosed in single/ double quotes
- -mm-
- NULL value should be entered as NULL without any quotes. NULL value means blank value in
the table.

Use of insert command to enter values for selected columns only:

Values entered in the column must be in same order as given in the list enclosed with table name
in INSERT command.
For example :

mysql> INSERT INTO STUDENT(RNO,GENDER, LNAME,FNAME) VALUES(8,'F','SHANU',


'DEEPAKSHI');

Above command will enter the values only in specified columns of the table. Remaining columns
of the table will have a NULL value inserted by default.

If we have to enter a record with values for all the attributes(columns) then list of columns is not
specified with table name in the command then we need to enter value for all the attributes of the
table. The order of values must be same as the order of attributes specified in the table
For example :
INSERT INTO STUDENT VALUES(1,'ABHISHEK','NARULA','M', '1998-10-05',98);

It can be observed that the numeric values can be inserted directly while string and date is
entered enclosed within single quotes.
The order of entering the values must be same as the order of attributes defined in the relation.

A select statement can also be used with the insert command provided, the result of select
query is of the same order as the given list of columns

Main purpose after storing the data in a table is to retrieve the data for generating various reports.
Data from tables can be retrieved/ fetched using Select Command.

SELECT COMM AND :


SELECT command is used to view the data from a relation in a database. It returns a result set of
data/ records from one or more relations.
Syntax of SELECT Command :
SELECT <column name> FROM <table name >;
Command to retrieve single column display
select Rno from STUDENT;

mysql> select rno from student;

+----------+

| r no |

+----------+

| 1|

| 2|

The above command displays only the roll numbers of students.

Command to display multiple columns :


Select Rno, gender , Fname from Student;
Above command fetches the result set having roll number, first name and gender of students and
displays the list on screen as follows :

The output displayed the data in same order as the order of columns given in the command.

Select * from Student;

* is the wild card character ( means ALL) that is used to display names of all the columns.
DISTINCT ( Displaying values without repetition)

If a column contains repeated values then the select statement gives the result set with repeated
values like if a command is given to display DISTINCT keyword is used to eliminate repeated
values
Consider the query:
Select marks from student:
mysql> select marks from student;
+---------+
| marks |
+---------+
| 98 |
| 92 |
| 95 |
| 94 |
| 93 |
| 84 |
| 84 |
| NULL |
+---------+
8 rows in set (0.00 sec)

In above example it can be noticed that value 84 appears twice.


When duplicate value appears only one instance of the value is considered and is displayed.

For example :

Select DISTINCT marks from student;

+---------+
| marks |
+---------+
| 98 |
| 92 |
| 95 |
| 94 |
| 93 |
| 84 |
| NULL |
+---------+
7 rows in set (0.00 sec)

A number of keywords and clauses are used with SELECT statement to retrieve data as per the
requirement. These are discussed below:
ALL
Keyword ALL when used with Select statement is used to display values of all columns in the row.
It displays even the duplicate values.

WHERE Clause

Where clause is used to fetch data based on a criteria/ condition. Criteria can be given using an
expression. Table has many records in it and it is not always desir able to show all the records every
time. At times only certain set of specific rows need to be displayed. based on the criteria. Keyword
WHERE is used for selection of rows with select statement. We can also say that WHERE clause
is used to filter records. It is used to fetch only those records that satisfy a specified criterion.

Syntax:

WHERE <condition>;

For example if we wish to display records of students who have a got marks greater thn we will 90
then following command needs to be entered:

mysql> select fname, marks from student


-> where marks > 90;
+------------------- +-------+
| fname | marks |
+--------------------+------+
| ABHISHEK | 98 |
| BHISHEK | 92 |
| BHUSHAN | 95 |
| CHETALI | 94 |
| CHETANYA | 93 |
+-----------------------+-------+
5 rows in set (0.11 sec)

Use of arithmetic operators


SQL supports a set of arithmetic operators that can be used .in select query. Arithmetic operators
are used with numeric values. Following is the set of arithmetic operators supported by SQL:

Operator Description
+ For addition of values
- Subtraction of values
* For finding the product of values
/ Divide
% Modulo operator. Returns the remainder
Following set of examples show the use of arithmetic operators for performing calculations :

Arithmetic operators are used to perform calculations over the numeric fields of a table.
For example, if we wish to see the result after adding 10 marks for activity in each record then
what would be the total then this can also be done using expression as shown below:

mysql> select fname, marks + 10 from student


-> where marks > 90;
+------------------- +-------+
| fname | marks |
+--------------------+--------+
| ABHISHEK | 108 |
| BHISHEK | 102 |
| BHUSHAN | 105 |
| CHETALI | 104 |
| CHETANYA | 103 |
+-----------------------+---------+
5 rows in set (0.11 sec)

Another example: in case to view the salary of employees after adding a bonus of 10 percent to
the salary , following command may be used:

mysql> select empname, salary+salary*0.1 from employee


-
+------------------- +---------------------------+
| empname | salary+salary*0.1 |
+--------------------+---------------------------+
| ABHINAV | 69803.20 |
| VISHESH | 49290.70 |
| B.RATNAKAR | 118982.95 |
| CHETANYA | 198675.45 |
| SOURABH | 99456. 93 |
+-----------------------+-------------------------+
5 rows in set (0.11 sec)
Note that the calculations done on column values only appear on the output screen and does not
make any changes in the records of the table. The values remain the same in table. Actually the
operation is performed over the result set and not on the actual table. For making any changes
within a UPDATE command that is discussed after this topic.

Relational Operators

Relational Operators compare two values and gives a result in the form of true of false. Every row
is filtered using the relational operator in the expression in where clause. Given below are the
relational operators used in MySQL alongwith their functions:

These operators are of great help to fetch data on a particular criteria. If we need to display data

mysql> select name


from employee

mysql> select empname from employee where esal<50000.00;

mysql> select empname from employee where edept<>'Sales';


Logical Operators
SQL supports following set of logical operators:
AND, OR, NOT
AND Operator is used with where clause and returns true if both the conditions are true. Those
records are displayed which are true for both the conditions.

For example:
mysql> select fname from student where gender ='f' and marks>90;;

AND operator can be used to fetch records satisfying in a range of values as shown in the
example given below:
mysql> select fname, lname, marks
FROM student
WHERE marks >= 92 and marks<= 95;
In the above query, the output will display records of all the students who have marks greater than
or equal to 92 and less than or equal to 95. Similar result can be obtained using keyword
BETWEEN .

BETWEEN operator
Keyword BETWEEN is used to fetch data based on a range of values on a column. The result set
includes the values of the upper and lower bound given in the range.
For example , following command displays firstname, last name and marks of the students whose
marks are from 92 to 95;
mysql> select fname, lname, marks
FROM student
WHERE marks BETWEEN 92 and 95;
Output will be :
OR operator returns True if either one of the conditions is True.

For example : to view list of all the sports coach who give coaching for either football or hockey;

Coachname Game

Birender Singh Hockey


Jasvinder Pal Football
Dharmender Hockey

NOT Operator
Not is used for negation. It returns the result set that is opposite to the given condition
For example : following command displays name and salary of employees whose salary is not
less than 50000.00

mysql>select empname, esal from employee where NOT(esal<50000.00);

Following command displays name and zone of employees who are not in north zone:
HANDLING NULL Values
IS operator is used to match NULL value in the expression.

For example, following command is to display the records with NULL values in column edesig
from table employee
mysql>select empname, zone from employee where zone IS NULL;

IS operator is used to compare equality with NULL whereas IS NOT may be used for comparing
the values not equal to NULL;

mysql> select empname, zone from employee where zone IS NOT NULL;

Note: the operations = NULL and <> NULL are not defined!

Alias Name to columns

To make the output more user friendly we can give customized heading to column name in the
select command. Keyword AS is used to give column alias in a set of single quotes as shown in
the example below:

For example :

from Student;
Remember : the name of column if for the query only and no changes are made in the original
table.

Inserting Text within the Query SQL


To make the output more user friendly SQL supports inserting text within the output display. The
text is displayed only in the output and no changes are made in the table.
For example :
mysql>
from student;

IN operator
IN operator is very useful when we wish to fetch selected records which match a certain set of
values. Suppose we wish to display list of students who have score marks 88,90,92,95 , then IN
operator can be used as follows :

mysql> select fname, marks from student


WHERE marks IN (88, 92, 95);
Output will be :

IN operator helps in removing multiple conditions. Without IN operator the above command would
have been as follows :
mysql>select fname , marks from student
where marks=88 OR marks=92 OR marks=95;

LIKE keyword
LIKE is used for pattern matching and is very useful. Following characters used for applying
pattern matching:
% percent symbol is used to match none or more characters
_ underscore character is used to match occurrence of one character in the string

mysql>select * from student

output is:

mysql>select * from student


where fname
Command to display list of all the students whose name has upto five characters:

mysql>select * from student

Following command displays list of students whose name starts and ends with a specified lett er.

Notice that in case no record matches the given pattern then the query returns empty set on
execution.
Similarly many more patterns may be given as follows :
matches any string with exactly four characters
matches any s

matches any string with at least three or more characters

ORDER BY
The result set fetched by the query can be displayed in sorted order. The sorting can be on the
basis of any particular column from the table using ORDER BY clause.
Syntax is :

FROM <table name>


[ WHERE <condition> ]
ORDER BY < column name> [DESC];
By default the records are displayed in ascending order of the column name. Keyword ASC is
used with ORDER BY clause for displaying the list in ascending order and keyword DESC is used
with ORDER BY clause to display the records in descending order.

Following commands are used to display records in sorted order of marks of students
mysql>select fname, lname, marks
from STUDENT
order by marks;

It can be observed that the output is displayed in the sorted order of marks. NULL value is
displayed first and records are displayed in ascending order.
Following command displays the records in descending order of fname:
mysql> select fname, lname
from STUDENT
ORDER BY fname DESC;

ORDER By clause can be used to sort the records on the basis of two columns also.
Following command displays the result based on order of marks and then on fname.
mysql> select fname, lname , marks from STUDENT
ORDER BY marks ASC, fname DESC;
It can be observed from the above figure that the records are d isplayed in ascending order of
marks and for records having similar value of marks are sorted on the basis of descending order
of fname.

Order by clause may be used with Where Clause as follows:


mysql> select fname, lname , marks from STUDENT
WHERE marks >90
ORDER BY marks DESC, fname ASC;
Output :

UPDATE
UPDATE command is used to modify data of records within the table. It is a type of DML and is
used to make changes in the values entered in the table :

Syntax: `
UPDATE <table name>

[WHERE <condition> ];

The command can be used to update one or more columns and WHERE clause is used for
modifying the records that matches a criteria.
For example:

Following command increases the salary of all the employees by 10%;

Consider the table student with following records:

Now with the help of update command we can add values to date of birth and marks for
Deepakshi :

Again the records as displayed and we can see that the changes have been made:
DELETE

DELETE Command is used to remove records from the table.


Syntax of the command is :
DELETE from <table name>
[Where <condition>];

Command to delete record of student whose roll number is 13 is

Earlier the table was having 12 records and after the execution of the command it has 11 rows. It
may be noticed that record of Saurabh Makania has been removed.

Consider the command :


mysql> DELETE FROM STUDENT;
If no condition is specified then all the records of the table are removed i.e. the table becomes
empty.

POINTS TO REMEMBER :

In an RDBMS data is stored in tables.


A table refers to a two dimensional representation of data arranged in columns and rows.
MySQL (Structured Query Language) is used to manage databases in an RDBMS.
MySQL commands are divided .into different categories: DDL, DML, and DCL.
CREATE command is used to create databases and tables.
CREATE DATABASE statement is used to create a new database.
CREATE TABLE statement is used to create a new table.
The DESCRIBE statement is used to see the structure of a table.
The DESCRIBE command is used to view the structure of a table.
ALTER TABLE statement is used to change the structure of a table ie. to add, remove or
change its column(s)
Constraints: These are the rules which are applied on the columns of tables to ensure data
integrity and consistency.
DROP TABLE command is used to delete tables.
INSERT INTO statement is used to insert a new row in a table.
The SELECT statement is used to fetch data from one or more database tables.
SELECT * means display all columns.
The WHERE clause is used to select specific rows.
The DESCRIBE statement is used to see the structure of a table.
We can change the structure of a table ie. add, remove or change its column(s) using the
ALTER TABLE statement.
The keyword DISTINCT is used to eliminate redundant data from display.
Logical operators OR and AND are used to connect relational expressions in the WHERE
clause.
Logical operator NOT is used to negate a condition.
The BETWEEN operator defines the range of values that the column values must fall into to
make the condition true.
The IN operator selects values that match any value in the given list of values.
% and _ are two wild card characters. The percent (%) symbol is used to represent any sequence
of zero or more characters. The underscore (_) symbol is use d to represent a single character.
NULL represents a value that is unavailable, unassigned, unknown or inapplicable.
The results of the SELECT statement can be displayed in the ascending or descending order of
a single column or columns using ORDER BY clause.
UPDATE statement is used to modify existing data in a table.
DELETE statement is used to delete rows from a table.

EXERCISE
1. Write a short note on MySQL.
2.Mention features of a DBMS.
3.What is the difference between DBMS and RDBMS?
4.List some features of MySQL.
5.How is Primary Key different from Candidate Key?
6.Define the key(s) used in MySQL.
7.State the similarity and difference between the Primary Key, Candidate Key, Alternate Key
and Foreign Key
8.Which statement is used to select a database and make it current?
9.How is a database related to table(s)?
10Write SQL statement to view names of all the tables contained in the current database
11.In a database there is a table Cabinet. The data entry operator is not able to put NULL in a
column of Cabinet? What may be the possible reason(s)?
12. In a database there is a table Cabinet. The data entry operator is not able to put duplicate
values in a column of Cabinet? What may be the possible reason(s)?
13. Do Primary Key column(s) of a table accept NULL values?
14. There is a table T1 with combination of columns C1, C2, and C3 as its primary key? Is
it possible to enter:
a. NULL values in any of these columns?
b. Duplicate values in any of these columns?
15. At the time of creation of table X, the data base administrator specified Y as the
Primary key. Later on he realized that instead of Y, the combination of column P and
16should have been the primary key of the table. Based on this scenario, answer the
following questions:
a. Is it possible to keep Y as well as the combination of P and Q as the primary key?
b. What statement(s) should be entered to change the primary key as per the
requirement.
17. Does MySQL allow to change the primary key in all cases? If there is some special
case, please mention.
18. What are the differences between DELETE and DROP commands of SQL?
19Which statement is used to modify data in a table?
A. CHANGE
B. MODIFY
C. UPDATE
D. SAVE AS
20. Which SQL statement is used to delete data from a table?
A. DELETE
B. DROP
C. TRUNCATE
D. REMOVE

Fill up the blanks :


1, ______________ command is used to add records in a relation.
2. Select is a type of ___________ command.
3. _________ command is used to modify records in a table.
4. _________ is used to match string patterns.
5. BETWEEN operator includes __________ and _____________ values given in the range.

Lab exercises:
Consider the following table named "GYM" with details about Fitness products
being sold in the store.
Table Name : GYM
PrCode stores Codes of Products
PrName stores names of Products
(UnitPrice is in Rs.)

Write SQL statements to do the following:


a) Display the names of all the products in the store.
b) Display the names and unit price of all the products in the store
c) Display the names of all the products with unit price less than Rs.20000.00
d) Display details of all the products with unit price in the range 20000 to 30000
e) Display names of all products by the manufacturer "Fit Express"
f) Display all rows sorted in descending order of unit price.
g) Add a new row for product with the details: "P106","Vibro Exerciser", 23000, manufacturer : "Avon
Fitness".
h) Change the Unit Price data of all the rows by applying a 10% discount reduction on all the
products.
i) Display details of all products with manufacturer name starting with "A"

You might also like