CHAPTER - 7
INTRODUCTION TO MySQL
MySQL is an open source relational database management system
(RDBMS). It 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
& requires no cost or payment for its usage.
It has superior speed, is easy to use and is reliable.
It 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.
It 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. Anyone can download this software
from specific location on Internet. If you want to download, follow the
following steps. The steps outlined here are for Windows OS platform.
1. Installation file for MySQL may be downloaded from the website
https://dev.mysql.com. (Choose appropriate download link as per the
operating system).
2. 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; in present case 32-bit or 64-bit Windows).
3. After the installation file has finished downloading, double-click it,
which begins the MySQL Setup Wizard.
7.2 Information Technology Class-XII
4. At the welcome dialog box, click the "Next" button. The MySQL Setup
Wizard allows us to choose the installation directory on the computer,
and whether or not to have optional components installed.
5. In the "Setup Type" dialog box, choose "Typical" from the three
options. MySQL will be installed in the default directory, "C:\Program
Files\MySQL\MySQL Server.
6. Click the "Next" button. Now it is ready to install MySQL's files.
7. Click the "Install" button.
8. After the Setup is complete, we should configure the new server. At
the initial Server Instance Configuration Wizard dialog box, click the
"Next" button.
9. 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 is created, MySQL server is
now 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
Testing MySQL:
Follow the steps to start MySQL
Start> Programs>MySQL>….>MySQL Command Line Client
OR
Go to the folder
C:\Program Files\MySQL\MySQL Server 5.6\bin
[Assuming C:\ drive as the drive having MySQL] and
Click on the file MySQL.EXE
MySQL will prompt a message to provide password (it requires the same
password which was entered during the installation). The above steps ensure
successful installation and configuration of MySQL database server. Next
time in the MySQL prompt, you can create and use databases, create tables
and execute SQL queries.
Relational Database Management System Introduction to MySQL 7.3
Before going to discuss more commands and statements of MySQL, let’s
revisit the concepts, we have already learnt in the previous class.
SQL (Structured Query Language): It is the language used to
manipulate and manage databases and tables within them using an
RDBMS.
DDL (Data Definition Language): This is a category of SQL
commands which are used to create, destroy, or restructure databases
and tables come under this category. Examples of DDL commands are
- CREATE, DROP, and ALTER.
o CREATE DATABASE - creates a new database
o CREATE TABLE - creates a new table
o ALTER TABLE - modifies a table
o DROP TABLE - deletes a table
DML (Data Manipulation Language): These categories of SQL
commands are used to manipulate data within tables come under this
category. Examples of DML commands are - INSERT, UPDATE, and
DELETE.
o SELECT - extracts data from a table
o UPDATE - updates data in a table
o DELETE - deletes data from a table
o INSERT INTO - inserts new data into a table
TCL (Transaction Control Language): This is a category of SQL
commands which are used to manage transactions in database. These
are also used to manage the changes made by DML statements. It
allows statements to be grouped together into logical transactions.
Examples of TCL commands are - COMMIT, SAVEPOINT,
ROLLBACK, and SETTRANSACTION.
DCL (Data Control Language): This is a category of SQL
commands. All the commands which are used to control the access to
databases and tables fall under this category. Examples of DCL
commands are - GRANT, REVOKE.
7.4 Information Technology Class-XII
Different SQL commands studied in the previous class are summarized
below:
Sl
Command, Syntax, Purpose Category
No
1 Command: CREATE DATABASE DDL
Syntax: CREATE DATABASE <database name>;
Purpose: Creates a database with the specified name.
2 Command: CREATE TABLE DDL
Syntax: CREATE TABLE <table name>
(<column name1> <data type1>
[,<column name2> <data type2>,
----------------------------------------------
<column name N> <data type N>]
);
Purpose: Creates a table with the specified name.
3 Command: ALTER TABLE DDL
Syntax: ALTER TABLE <table name>
ADD <column name> <data type>;
ALTER TABLE <table name>
DROP <column name>;
ALTER TABLE <table name>
MODIFY <column> <new definition>;
Purpose: Modifies the structure of a table
4 Command: USE DML
Syntax: USE <database name>;
Purpose: Opens the specified database for use.
5 Command: SELECT DATABASE() DML
Syntax: SELECT DATABASE();
Purpose: Shows the name of the current database
6 Command: SHOW TABLES DML
Syntax: SHOW TABLES;
Purpose: Shows a list of tables present in the current
database.
7 Command: INSERT DML
Syntax: INSERT INTO <table name>
[<column1>, <column2>, ..., <column N>]
VALUES (<value1>, <value2>, ... <value N>);
Purpose: Inserts data into a table
Relational Database Management System Introduction to MySQL 7.5
8 Command: SELECT DML
Syntax: SELECT <* / column name / expression> ,
[<column name/Expression list>]
FROM <table name>
[WHERE <condition>]
[ORDER BY <column name / expression>
[ASC/DESC]];
There are multiple ways to use SELECT.
Purpose: Retrieves data from a table
9 Command: DESCRIBE DML
Syntax: DESC[RIBE] <table name>;
Purpose: Shows the structure of a table.
10 Command: UPDATE DML
Syntax: UPDATE <table name>
SET <column name> = <value>
[,<column name> = <value>, …]
[WHERE <condition>];
Purpose: Updates/Modifies data in a table
11 Command: DELETE DML
Syntax: DELETE FROM < table name>
[ Where < condition>];
Purpose: Deletes data from a table
Different SQL clauses used with SELECT command are summarized below:
Sl Clause Used for
#
1 DISTINCT Used to display distinct values from a column of a table.
2 BETWEEN Used to define the range of values within which the
column values must fall to make a condition true. Range
includes both the upper and the lower values.
3 IN Used to select values that match any value in a list of
specified values.
4 LIKE Used for pattern matching of string data using wildcard
characters % and _ .
5 IS NULL / Used to select rows in which the specified column is
NOT NULL NULL (or is NOT NULL)
6 ORDER BY Used to display the selected rows in ascending or in
descending order of the specified column/expression.
7.6 Information Technology Class-XII
We will now revisit the commands and clauses used in MySQL
through following examples. Let’s create three tables named Student,
Employee and Book to be placed in a Library database.
After starting MySQL, we shall create a database in which all the tables will
be stored. For this we shall use the ‘CREATE DATABASE’ statement as;
CREATE DATABASE Library;
Now the database ‘Library’ is created and we have to open it for placing
tables. For this we give the statement;
USE Library; where the command USE is used.
Before creating a table; the choice of columns, their names & data types have
to be planned very carefully. The nature of data to be stored in a column
decides what datatypes should be defined. Most common datatypes used in a
table are;
Text: CHAR (size) or VARCHAR (size)
Numeric: INT (size) or INTEGER (size)
Date: DATE
After planning, we arrive at the following data types for columns of
our tables in the College database. Here the column sizes are based on our
assumption. These may be different for different databases.
Planning for the table Student:
Column Datatype Reason
Roll CHAR(8) A standard Roll Number of a student is ‘IA16-
001’ or ‘BS16-009’ consists of eight characters:
First letter stands class (I for intermediate or
+2, B for bachelor or +3), second letter stands
for stream (Arts/ Commerce/ Science), next two
digits for year of admission and last three
digits admission serial number, separated by
the character ‘-‘.
NameStd VARCHAR(18) The name of a student does not contain fixed
number of characters; here the maximum limit
has been fixed to 18. Whether the length of the
name is short or long, the number of memory
places reserved for each name would be 18.
Relational Database Management System Introduction to MySQL 7.7
AcsnNo INTEGER(5) Accession number of a book is an integer in the
range
1 to 99999.
IssueDt DATE It is the date of issue of the book.
RetnDt DATE It is the date on which the book is returned
Planning for the table Employee:
Column Datatype Reason
EmpCode CHAR(6) For example ‘BJB099’ may be an Employee
Code; where the first three letters indicates a
college and last three digits gives the
employee serial number.
NameEmp VARCHAR(18)
AcsnNo INTEGER(5)
As described earlier
IssueDt DATE
RetnDt DATE
Planning for the table Book:
Column Datatype Reason
AcsNo INTEGER(5)
Title VARCHAR(20)
Described earlier
Author VARCHAR(18)
Publisher VARCHAR(18)
Edition INTEGER(4) Year of edition of the book
Price DECIMAL(6, 2) The maximum a price of a book should
not exceed Rs. 9999.99
To create the table ‘Book’ we have to write the following code in MySql
window;
mysql> USE Library;
Database changed
mysql> CREATE TABLE Book
->(AcsnNo INTEGER(5),
->Title VARCHAR(20),
-> Author VARCHAR(18),
7.8 Information Technology Class-XII
-> Publisher VARCHAR(18),
-> Edition INTEGER(4),
-> Price DECIMAL(6,2));
Note: Each column in a table are given unique names. 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 the column 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 Std_name, Emp_Name, Book_Id, email are valid column names.
Similarly other two tables; ‘Student’ and ‘Employee’ can be created. To verify
that the tables are created, we give the statement:
SHOW TABLES;
To further verify that the tables have been created as per the required
specifications, we view the structure of each table by giving the statements:
DESC Book;
DESC Student;
DESC Employee;
mysql> DESC Book;
+-----------+--------------+------+-----+---------+---+
| Field | Type | Null | Key | Default |
Extra |
+-----------+--------------+------+-----+---------+---+
| AscnNo | int(5) | YES | | NULL |
|
| Title | varchar(20) | YES | | NULL |
|
| Author | varchar(18) | YES | | NULL |
|
| Publisher | varchar(18) | YES | | NULL |
|
| Edition | int(4) | YES | | NULL |
|
| Price | decimal(6,2) | YES | | NULL |
|
+-----------+--------------+------+-----+---------+---+
6 rows in set (0.17 sec)
Relational Database Management System Introduction to MySQL 7.9
If the structure of a table is not as per the required specifications, we can
modify it by using the ALTER TABLE command. Following are three
examples of this:
a) Suppose we decide to categorize the books into categories 'A', 'B' and
'C' based on some criteria. Then a new column Category of type
CHAR(1) can be added to the table by the statement:
ALTER TABLE Book ADD Cat CHAR(1);
The structure would look like the following;
mysql> DESC Book;
+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| AscnNo | int(5) | YES | | NULL | |
| Title | varchar(20) | YES | | NULL | |
| Author | varchar(18) | YES | | NULL | |
| Publisher | varchar(18) | YES | | NULL | |
| Edition | int(4) | YES | | NULL | |
| Price | decimal(6,2) | YES | | NULL | |
| Cat | char(1) | YES | | NULL | |
+-----------+--------------+------+-----+---------+-------+
7 rows in set (0.03 sec)
b) Suppose we wish to change the size of column 'Publisher' of ‘Book’
table from 18 characters to 20 characters, then we can give the
statement:
ALTER TABLE Books MODIFY Publisher VARCHAR(20);
c) Suppose we decide to remove the ‘RetnDt’ column from the table
Employee. We can do so by the statement:
ALTER TABLE Employee DROP RetnDt;
d) Once the tables are created as per the required specifications, we can
populate these tables with the given sample data as follows:
Now we populate the Book table by using the INSERT command as follows;
mysql> INSERT INTO Book VALUES
-> (1001,'TextBook of English','Dr N N Dash','ABC Publ',2015,162,'A'),
-> (1002,'Geology made Simple','Dr UKTripathy','TBB Odisha',2016,270,'B'),
-> (1003,'TextBook of IT-II','Dr N C Samal','TBB Odisha',2015,243,'C'),
-> (1004,'Astronomy is Easy','Dr M Patnaik','XYZ Publ',2016,500,'C');
Query OK, 4 rows affected (0.19 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> SELECT*FROM Book;
7.10 Information Technology Class-XII
+--------+---------------------+---------------+------------+-------+-------+----+
| AscnNo | Title | Author | Publisher |Edition| Price | Cat
|
+--------+---------------------+---------------+------------+-------+-------+----+
| 1001 | TextBook of English | Dr N N Dash | ABC Publ | 2015 | 162.00 | A
|
| 1002 | Geology made Simple | Dr UKTripathy | TBB Odisha | 2016 | 270.00 | B
|
| 1003 | TextBook of IT-II | Dr N C Samal | TBB Odisha | 2015 | 243.00 | C
|
| 1004 | Astronomy is Easy | Dr M Patnaik | XYZ Publ | 2016 | 500.00 | C
|
+--------+---------------------+---------------+------------+-------+--------+---+
4 rows in set (0.00 sec)
Similarly we can populate the ‘Student’ & ‘Employee’ tables by using the
INSERT command with some issue and return dates. The entered data in to
the tables can be verified by using the SELECT statements as shown above
for ‘Book’ table;
SELECT * FROM Student;
SELECT * FROM Employee;
‘*’ in the SELECT statement shows all records from a table.
In order to display selective records, we use various clauses with SELECT
command; e.g. to check the names (without repetition) of various publishers
whose books are present in the library, we enter the statement:
SELECT DISTINCT Publisher FROM Book;
To check the books of publisher ‘TBB Odisha' present in the library, we enter
the statement:
SELECT * from Books WHERE Publisher = 'TBB Odisha';
To display the books list for which the price is between 200 and 300, we enter
the statement:
SELECT * FROM Book WHERE Price > 200 and Price < 300;
REVISION TOUR OR
SELECT * FROM Books WHERE Price BETWEEN 200 and 300;
To display the details of books from the publishers 'ABC Publ' 'TBB Odisha',
or ' XYZ Publ', we enter the statement:
SELECT * from Book
WHERE Publisher = 'ABC Publ'
OR Publisher = 'TBB Odisha'
OR Publisher = ‘XYZ Publ’;
OR
Relational Database Management System Introduction to MySQL 7.11
SELECT * from Book
WHERE Publisher IN
('ABC Publ', 'TBB Odisha', ' XYZ Publ');
Note: Here ‘*’ will retrieve all the fields of specified records.
To list the AcsnNo, Title, and Price of all the books whose Title contains the
word
'Text Book', we can enter the statement:
SELECT AcsnNo, Title, Price from Book
WHERE Title LIKE '%TextBook%';
To display the AcsnNo of all the books which have been issued to students but
not returned by them, we enter the statement:
SELECT AcsnNo FROM Student
WHERE IssueDt IS NOT NULL and RetnDt IS NULL;
To Display a List of all the Books in the alphabetical ascending order of
Titles, we enter the statement:
SELECT * FROM Book ORDER BY Title;
To get the same list in descending order of Titles, we enter the statement:
SELECT * FROM Book ORDER BY Title DESC;
Suppose a student returns a Book with AcsnNo 1245 on 12 August 2016; this
information can be recorded in the ‘Student’ table as follows:
UPDATE Student
SET RetnDt = '2016-08-12'
WHERE AcsnNo = 1245;
If we want to delete the records of all the books by the Publisher 'ABC
Publication' with edition year earlier than 2010, we can enter the statement:
DELETE FROM Book
WHERE Publisher = 'ABC Publication' AND Edition <
2010;
Suppose for some analysis we decide to keep track of how many times each
book is issued. This can be done if there is an extra column 'IssueFreq' in the
table ‘Book’ to keep this count. Every time a book is issued, the corresponding
7.12 Information Technology Class-XII
value in this column is incremented by 1. To add this extra column in the
table, we enter the statement:
ALTER TABLE Book ADD IssueFreq INTEGER(3);
Till now, we discussed the topics already learnt in the previous class.
To further our grip on the subject, we shall now describe some important
MySQL commands, statements, clauses and functions in this section. To
begin with let’s put a table named ‘Student’ in a new database named
‘College’. We follow the methods, already described earlier to do this job as
follows.
mysql> USE College;
Database changed
mysql> SELECT * FROM Student;
+----------+-----------------------+------------+-------+
| Roll | Name | DoB | Mark |
+----------+-----------------------+------------+-------+
| IA16-001 | ASHIMA MISHRA | 1998-12-27 | 540.0 |
| IC16-002 | SUDHANSU SEKHAR SAHOO | 1999-07-05 | 342.0 |
| IS16-003 | SARAH SMRUTI | 1999-06-15 | 351.0 |
| IA16-005 | SARFRAZ AHMAD | 1999-11-23 | 551.0 |
| IS16-005 | AGNAJITA PATNAIK | 2000-01-03 | 554.0 |
| IC16-005 | CLEMENT XESS | 1996-02-12 | 252.0 |
| IA16-006 | BISMAY PRADHAN | 1997-05-15 | 452.0 |
| IC16-006 | PRIYANKA PATRA | 1999-11-14 | 352.0 |
| IS16-010 | SAIMA KHAN QUADRI | 1999-10-30 | 552.0 |
+----------+-----------------------+------------+-------+
9 rows in set (0.63 sec)
Constraints
Many times it is not possible to keep a manual check on the data that
is going into the tables using INSERT or UPDATE commands. 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:
SlNo Constraint Purpose
Sets a column or a group of columns as the
Primary Key of a table. Therefore, NULLs and
1 PRIMARY KEY
Duplicate values in this column are not
accepted.
Relational Database Management System Introduction to MySQL 7.13
Makes sure that NULLs are not accepted in the
2 NOT NULL
specified column.
Data will be accepted in this column, if same
data value exists in a column in another related
table. This other
3 FOREIGN KEY
related table name and column name are
specified while creating the foreign key
constraint.
Makes sure that duplicate values in the specified
4 UNIQUE
column are not accepted.
Defines a set of values as the column domain. So
any
5 ENUM
value in this column will be from the specified
values only.
Defines a set of values as the column domain.
6 SET Any value in this column will be a seubset of the
specied set only.
PRIMARY KEY:
Remember, the primary key of a table is a column or a group of
columns that uniquely identifies a row/ record of a table. Therefore no two
rows of a table can have the same primary key value. Now suppose that the
table ‘Students’ is created with the following statement:
mysql> USE College;
Database changed
mysql> CREATE TABLE Students
->(Roll CHAR(8),
-> Name VARCHAR(18),
-> DoB DATE,
-> Mark DECIMAL(4,1));
mysql> desc Students;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| Roll | char(8) | YES | | NULL | |
| Name | varchar(18) | YES | | NULL | |
7.14 Information Technology Class-XII
| DoB | date | YES | | NULL | |
| Mark | decimal(4,1) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
We know that in this table ‘Roll’ 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
Roll as the primary key of the ‘Students’ table. It can be done by using the
PRIMARY KEY clause at the time of table creation as follows:
mysql> CREATE TABLE Students
->(Roll CHAR(8)PRIMARY KEY,
-> Name VARCHAR(18),
-> DoB DATE,
-> Mark DECIMAL(4,1));
mysql> DESC Students;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| Roll | char(8) | NO | PRI | NULL | |
| Name | varchar(18) | YES | | NULL | |
| DoB | date | YES | | NULL | |
| Mark | decimal(4,1) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
Look at the two structures of the table ‘Students’ displayed above. In
the first structure, the field ‘Roll’ can accept Null value & is not associated
with any Key. In the second structure, the ‘Roll’ field will not accept any Null
value & is the Primary Key of the table.
If in a Table; combination of two or more fields has to be combined to be the
primary key, then the syntax for creating such table would be like:-
CREATE TABLE Result
(CHSE_Roll CHAR(9),
Name VARCHAR(36),
Pass_Yr DATE,
Mark DECIMAL(4,2),
PRIMARY KEY(CHSE_Roll, Pass_Yr));
In the above example, the combination of CHSE_Roll & Pass_Yr forms the
primary key of the table ‘Result’.
Relational Database Management System Introduction to MySQL 7.15
NOT NULL:
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 a Book for which the Category is
not known. It means whenever we enter a row in the Book table,
corresponding Category cannot be NULL. Similarly while entering records in
the Salary table, we must enter the salary amount, it cannot be set NULL.
There may be any number of such situations.
While creating a table we have to specify in which columns NULLs should not
be accepted as outlined below:
CREATE TABLE Book
(AcsnNo INT(5) PRIMARY KEY, Title VARCHAR(20),
Author VARCHAR(20), Category CHAR(2) NOT NULL,
Price DECIMAL(5,2), Publisher VARCHAR(20));
CREATE TABLE Salary
(Emp_SlNo INT(4), Emp_Dept VARCHAR(10),
Bill_Date DATE, Sal_Amt DECIMAL(7,2) NOT NULL,
PRIMARY KEY (Emp_SlNo, Emp_Dept));
Now if we try to enter a NULL in the specified column, MySQL will reject the
entry and give an error.
If the required constraints have not been specified at the time of creation of a
Table or required to be changed or modified later; we use ALTER TABLE
command to accomplish it.
ALTER TABLE can be used:
to add a constraint
to remove a constraint
to remove a column from a table
to modify a table column
Suppose we have created the Book table without specifying any Primary key;
later we want to make ‘AcsnNo’ as the primary key field. For that, we have to
enter the following statement:
ALTER TABLE Book ADD PRIMARY KEY(AcsnNo);
7.16 Information Technology Class-XII
This will set ‘AscnNo’ as the primary key of the table. However, if this column
contains some duplicate values, then the statement will give an error.
It is also possible to change the primary key column(s) of a table. Suppose, in
the ‘Students’ table, instead of ‘Roll’, we want to set the combination of 'Roll'
and 'DoB' as the primary key. For this first we have to DROP the already
existing primary key (i.e., Roll) and then add the new primary key (i.e., Roll
and DoB). The corresponding statements would be as follows:
The DROP statement removes the primary key status of the field.
mysql> ALTER TABLE Students DROP PRIMARY KEY;
mysql> DESC STUDENTS;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| Roll | char(8) | NO | | NULL | |
| Name | varchar(18) | YES | | NULL | |
| DoB | date | YES | | NULL | |
| Mark | decimal(4,1) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
Now we can add the new primary key by using ADD statement;
mysql> ALTER TABLE Students ADD PRIMARY KEY(Roll,DoB);
mysql> DESC STUDENTS;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| Roll | char(8) | NO | PRI | NULL | |
| Name | varchar(18) | YES | | NULL | |
| DoB | date | NO | PRI | NULL | |
| Mark | decimal(4,1) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
Remove and Modify columns:
In MySQL, it is not possible to add or drop NOT NULL constraint
explicitly after the table Is being created. But it can be done by using
MODIFY clause of ALTER TABLE command. As an example, suppose we
don't want to accept NULL values in Bill_date column of ‘Salary’ table, we
can use the following statement to do the job:
ALTER TABLE Salary MODIFY Bill_date DATE NOT NULL;
Later on if we wish to change this status again, we can do so by entering the
command:
Relational Database Management System Introduction to MySQL 7.17
ALTER TABLE bills MODIFY Bill_date DATE NULL;
ALTER TABLE can also be used to remove a column from a table. This is
done by using DROP clause in ALTER TABLE command. The syntax is as
follws:
ALTER TABLE <tablename> DROP <columnname>
[, DROP <columnname> [, DROP <columnname> [. . .]]];
Following are some self explanatory examples of SQL statemenets to remove
columns from tables:
ALTER TABLE Salary DROP Bill_date;
ALTER TABLE Student DROP DoB, DROP Mark;BASES AND SQL
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 Roll and DoB columns of the Students table constitute its primary
key. Now if we drop the Roll column from the table, DoB will be the
remaining Primary Key column of the table. Therefore, duplicate entries in
the DoB column should not be allowed. To ensure this, before removing Roll
column from the table, MySQL checks that there are no duplicate entries
present in the DoB column of the table. If there are any, then the statement
trying to remove Roll column from the table will result in an error and that
column will not be removed. If there are no duplicate entries in the DoB
column, then Roll column will be removed. Similar will be the case with the
Roll column, if we try to remove DoB 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 Students DROP Roll, DROP DoB;
ALTER TABLE can also be used to change the data type of a field in a table.
For this the syntax is as follows:
ALTER TABLE <tablename> MODIFY <col_name> <new
datatype>
[,MODIFY <col_name> <new datatype>
[,MODIFY <col_name> <new data type> [, . . . ]]];
7.18 Information Technology Class-XII
For example, the statement:
ALTER TABLE Students modify Roll VARCHAR(10), modify Name
CHAR(15);changes the data type of column Roll to VARCHAR(10) and that
of Name to CHAR(15).
When we give a statement to change the data type of a column,
MySQL executes that statement correctly only if the change in data type does
not lead to any data loss. i.e. if the number of characters(including spaces) in
any Name field is more than 15, we'll get an error. Similarly the Mark field
of this table cannot be changed to INT type, if any of the Mark value is not an
integer.
ND SQL
DROP 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>;
To remove the table ‘Customer’ from the ‘College’ database we enter the
statement:
DROP TABLE Customer;
After this statement Customer table is no longer available in the database as
shown below.
mysql> SHOW TABLES;
+-------------------+ mysql> DROP TABLE Customer;
| Tables_in_college | mysql> SHOW TABLES;
+-------------------+ +-------------------+
| customer | | Tables_in_college |
| employee | +-------------------+
| student | | employee |
| students | | student |
+-------------------+ | students |
4 rows in set (0.03 sec) +-------------------+
3 rows in set (0.00 sec)
Working with NULL values:
While inserting data in to a Table, it may so happen that we don’t
know what to enter in certain fields. Do we enter a zero or leave it blank! In a
table, we can store these unknowns as NULL. NULL means a value that is
Relational Database Management System Introduction to MySQL 7.19
unavailable, unassigned, unknown or inapplicable. NULL is not the same as
zero or a space or any other character. . In a table NULL is searched by using
IS NULL keyword.
SELECT * FROM Student WHERE Name IS NULL;
SELECT * FROM Employee WHERE Pay IS NULL;
NOT NULL values in a table can be searched using IS NOT NULL.
SELECT * FROM Employee WHERE Salary IS NOT NULL;
We saw SQL SELECT command along with WHERE clause to fetch data
from MySQL table, but when we try to give a condition, which compares a
field or column value to NULL, it does not work properly.
To handle such situation MySQL provides three operators
1. IS NULL: operator returns true if column value is NULL.
2. IS NOT NULL: operator returns true if column value is not NULL.
3. <=>: operator compares values, which (unlike the = operator) is true
even for two NULL values.
Conditions involving NULL are special. You cannot use = NULL or != NULL
to look for NULL values in columns. Such comparisons always fail because
it's impossible to tell whether or not they are true. Even NULL = NULL
fails.
To look for columns that are or are not NULL, use IS NULL or IS NOT
NULL.
# If any column value involved in an arithmetic expression is NULL, the result of the
arithmetic expression is also NULL.
Sorting the Data in a Table by using ORDER BY clause
The result obtained using SELECT statement is displayed in the order in which
the rows were entered in the table using the INSERT INTO statement. The results of the
7.20 Information Technology Class-XII
SELECT statement can be displayed in the ascending or descending values of a single
column or multiple columns using ORDER BY clause.
The syntax for using this clause is;
SELECT <column name>, [<column name>…]
[WHERE <Condition list>]
ORDER BY <column name>;
Note: The syntax enclosed within [ ] are optional.
To learn about different types of sorting, let’s insert a new field ‘Gender’ in
the ‘Student’ table and add some more records (rows) in to it by using
INSERT INTO statements as given below.
mysql> ALTER TABLE Student ADD Gender CHAR(6);
mysql> INSERT INTO Student VALUES
-> ('IA17-001','Trupti Biswal','2000-05-
27',555,'Female'),
-> ('IA17-002','Kiran Behera','1999-02-01',594,'Male'),
-> ('IC17-001','Nibedita Behera','2001-05-
15',414,'Female');
Now the Student table with these new additions looks like;
mysql> SELECT*FROM Student;
+----------+-----------------------+------------+-------+--------+
| Roll | Name | DoB | Mark | Gender |
+----------+-----------------------+------------+-------+--------+
| IA16-001 | ASHIMA MISHRA | 1998-12-27 | 540.0 | NULL |
| IC16-002 | SUDHANSU SEKHAR SAHOO | 1999-07-05 | 342.0 | NULL |
| IS16-003 | SARAH SMRUTI | 1999-06-15 | 351.0 | NULL |
| IA16-005 | SARFRAZ AHMAD | 1999-11-23 | 551.0 | NULL |
| IS16-005 | AGNAJITA PATNAIK | 2000-01-03 | 554.0 | NULL |
| IC16-005 | CLEMENT XESS | 1996-02-12 | 252.0 | NULL |
| IA16-006 | BISMAY PRADHAN | 1997-05-15 | 452.0 | NULL |
| IC16-006 | PRIYANKA PATRA | 1999-11-14 | 352.0 | NULL |
| IS16-010 | SAIMA KHAN QUADRI | 1999-10-30 | 552.0 | NULL |
| IA17-001 | Trupti Biswal | 2000-05-27 | 555.0 | Female |
| IA17-002 | Kiran Behera | 1999-02-01 | 594.0 | Male |
| IC17-001 | Nibedita Behera | 2001-05-15 | 414.0 | Female |
+----------+-----------------------+------------+-------+--------+
12 rows in set (0.03 sec)
Relational Database Management System Introduction to MySQL 7.21
Let’s arrange the students in the above table according to their Mark
and then as per their Names. For that purpose we have to use the following
SELECT statements;
mysql> SELECT*FROM Student ORDER BY Mark;
+----------+-----------------------+------------+-------+--------+
| Roll | Name | DoB | Mark | Gender |
+----------+-----------------------+------------+-------+--------+
| IC16-005 | CLEMENT XESS | 1996-02-12 | 252.0 | NULL |
| IC16-002 | SUDHANSU SEKHAR SAHOO | 1999-07-05 | 342.0 | NULL |
| IS16-003 | SARAH SMRUTI | 1999-06-15 | 351.0 | NULL |
| IC16-006 | PRIYANKA PATRA | 1999-11-14 | 352.0 | NULL |
| IC17-001 | Nibedita Behera | 2001-05-15 | 414.0 | Female |
| IA16-006 | BISMAY PRADHAN | 1997-05-15 | 452.0 | NULL |
| IA16-001 | ASHIMA MISHRA | 1998-12-27 | 540.0 | NULL |
| IA16-005 | SARFRAZ AHMAD | 1999-11-23 | 551.0 | NULL |
| IS16-010 | SAIMA KHAN QUADRI | 1999-10-30 | 552.0 | NULL |
| IS16-005 | AGNAJITA PATNAIK | 2000-01-03 | 554.0 | NULL |
| IA17-001 | Trupti Biswal | 2000-05-27 | 555.0 | Female |
| IA17-002 | Kiran Behera | 1999-02-01 | 594.0 | Male |
+----------+-----------------------+------------+-------+--------+
12 rows in set (0.08 sec)
mysql> SELECT*FROM Student ORDER BY Name;
+----------+-----------------------+------------+-------+--------+
| Roll | Name | DoB | Mark | Gender |
+----------+-----------------------+------------+-------+--------+
| IS16-005 | AGNAJITA PATNAIK | 2000-01-03 | 554.0 | NULL |
| IA16-001 | ASHIMA MISHRA | 1998-12-27 | 540.0 | NULL |
| IA16-006 | BISMAY PRADHAN | 1997-05-15 | 452.0 | NULL |
| IC16-005 | CLEMENT XESS | 1996-02-12 | 252.0 | NULL |
| IA17-002 | Kiran Behera | 1999-02-01 | 594.0 | Male |
| IC17-001 | Nibedita Behera | 2001-05-15 | 414.0 | Female |
| IC16-006 | PRIYANKA PATRA | 1999-11-14 | 352.0 | NULL |
| IS16-010 | SAIMA KHAN QUADRI | 1999-10-30 | 552.0 | NULL |
| IS16-003 | SARAH SMRUTI | 1999-06-15 | 351.0 | NULL |
| IA16-005 | SARFRAZ AHMAD | 1999-11-23 | 551.0 | NULL |
| IC16-002 | SUDHANSU SEKHAR SAHOO | 1999-07-05 | 342.0 | NULL |
| IA17-001 | Trupti Biswal | 2000-05-27 | 555.0 | Female |
+----------+-----------------------+------------+-------+--------+
12 rows in set (0.00 sec)
As shown above, the default sorting order is ascending one; if not specified in
the statement, the sorting done in ascending order. However, we can sort in
descending order by using DESC key word with ORDER BY clause in a
SELECT statement as given below;
7.22 Information Technology Class-XII
mysql> SELECT*FROM Student ORDER BY Mark DESC;
+----------+-----------------------+------------+-------+--------+
| Roll | Name | DoB | Mark | Gender |
+----------+-----------------------+------------+-------+--------+
| IA17-002 | Kiran Behera | 1999-02-01 | 594.0 | Male |
| IA17-001 | Trupti Biswal | 2000-05-27 | 555.0 | Female |
| IS16-005 | AGNAJITA PATNAIK | 2000-01-03 | 554.0 | NULL |
| IS16-010 | SAIMA KHAN QUADRI | 1999-10-30 | 552.0 | NULL |
| IA16-005 | SARFRAZ AHMAD | 1999-11-23 | 551.0 | NULL |
| IA16-001 | ASHIMA MISHRA | 1998-12-27 | 540.0 | NULL |
| IA16-006 | BISMAY PRADHAN | 1997-05-15 | 452.0 | NULL |
| IC17-001 | Nibedita Behera | 2001-05-15 | 414.0 | Female |
| IC16-006 | PRIYANKA PATRA | 1999-11-14 | 352.0 | NULL |
| IS16-003 | SARAH SMRUTI | 1999-06-15 | 351.0 | NULL |
| IC16-002 | SUDHANSU SEKHAR SAHOO | 1999-07-05 | 342.0 | NULL |
| IC16-005 | CLEMENT XESS | 1996-02-12 | 252.0 | NULL |
+----------+-----------------------+------------+-------+--------+
12 rows in set (0.00 sec)
mysql> SELECT*FROM Student ORDER BY Name DESC;
+----------+-----------------------+------------+-------+--------+
| Roll | Name | DoB | Mark | Gender |
+----------+-----------------------+------------+-------+--------+
| IA17-001 | Trupti Biswal | 2000-05-27 | 555.0 | Female |
| IC16-002 | SUDHANSU SEKHAR SAHOO | 1999-07-05 | 342.0 | NULL |
| IA16-005 | SARFRAZ AHMAD | 1999-11-23 | 551.0 | NULL |
| IS16-003 | SARAH SMRUTI | 1999-06-15 | 351.0 | NULL |
| IS16-010 | SAIMA KHAN QUADRI | 1999-10-30 | 552.0 | NULL |
| IC16-006 | PRIYANKA PATRA | 1999-11-14 | 352.0 | NULL |
| IC17-001 | Nibedita Behera | 2001-05-15 | 414.0 | Female |
| IA17-002 | Kiran Behera | 1999-02-01 | 594.0 | Male |
| IC16-005 | CLEMENT XESS | 1996-02-12 | 252.0 | NULL |
| IA16-006 | BISMAY PRADHAN | 1997-05-15 | 452.0 | NULL |
| IA16-001 | ASHIMA MISHRA | 1998-12-27 | 540.0 | NULL |
| IS16-005 | AGNAJITA PATNAIK | 2000-01-03 | 554.0 | NULL |
+----------+-----------------------+------------+-------+--------+
12 rows in set (0.00 sec)
Relational Database Management System Introduction to MySQL 7.23
Sorting on Column Alias names:
A Column Alias means giving
a different name to a column on an ad mysql> SELECT Name,Mark AS MarkX
-> FROM Student
hoc basis. If a Column alias is defined -> ORDER BY MarkX;
on a column, we can use it for +-----------------------+-------+
| Name | MarkX |
displaying rows in an ascending or +-----------------------+-------+
descending order using ORDER BY | CLEMENT XESS | 252.0 |
| SUDHANSU SEKHAR SAHOO | 342.0 |
clause. Column alias is given by using | SARAH SMRUTI | 351.0 |
AS key word. In the following | PRIYANKA PATRA | 352.0 |
| Nibedita Behera | 414.0 |
example we have given an alias name | BISMAY PRADHAN | 452.0 |
‘MarkX’ to ‘Mark’ column and sort on | ASHIMA MISHRA | 540.0 |
‘MarkX’. In the SELECT statement | SARFRAZ AHMAD
| SAIMA KHAN QUADRI
| 551.0 |
| 552.0 |
we have retrieved Name field besides | AGNAJITA PATNAIK | 554.0 |
the alias field from Student table. | Trupti Biswal | 555.0 |
| Kiran Behera | 594.0 |
+-----------------------+-------+
12 rows in set (0.05 sec)
Sorting on multiple columns:
Sometimes it may so happen that, more than one record may contain same
value in a particular field; in those cases, we try to sort on another field in
addition to the former to get a better report. This is called as ‘multiple column
sorting’. Go through the following sorting command:
mysql> SELECT*FROM Student ORDER BY Mark,Name;
+----------+-----------------------+------------+-------+--------+
| Roll | Name | DoB | Mark | Gender |
+----------+-----------------------+------------+-------+--------+
| IC16-005 | CLEMENT XESS | 1996-02-12 | 252.0 | NULL |
| IS16-003 | SARAH SMRUTI | 1999-06-15 | 351.0 | NULL |
| IC16-006 | PRIYANKA PATRA | 1999-11-14 | 352.0 | NULL |
| IC17-001 | Nibedita Behera | 2001-05-15 | 414.0 | Female |
| IA16-006 | BISMAY PRADHAN | 1997-05-15 | 452.0 | NULL |
| IS16-005 | AGNAJITA PATNAIK | 2000-01-03 | 540.0 | NULL |
| IA16-001 | ASHIMA MISHRA | 1998-12-27 | 540.0 | NULL |
| IC16-002 | SUDHANSU SEKHAR SAHOO | 1999-07-05 | 540.0 | NULL |
| IA16-005 | SARFRAZ AHMAD | 1999-11-23 | 551.0 | NULL |
| IS16-010 | SAIMA KHAN QUADRI | 1999-10-30 | 552.0 | NULL |
| IA17-001 | Trupti Biswal | 2000-05-27 | 555.0 | Female |
| IA17-002 | Kiran Behera | 1999-02-01 | 594.0 | Male |
+----------+-----------------------+------------+-------+--------+
12 rows in set (0.05 sec)
We have given sorting order on the basis of ‘Mark’ first and then on
the basis of ‘Name’. You can verify the same from the above table. Look at the
Mark=540; the corresponding records have been sorted according to their
names! (Of course in ascending order, this is the default sorting order). If you
7.24 Information Technology Class-XII
change the order, like ‘ORDER BY Name, Mark; and then sorting will be
done according to Name and then Mark. The following table shows exactly
that; where we have tried to restrict the number of records and columns by
using WHERE clause in the SELECT statement.
mysql> SELECT Roll,Name,Mark FROM Student WHERE Mark>500
-> ORDER BY Name,Mark;
+----------+-----------------------+-------+
| Roll | Name | Mark |
+----------+-----------------------+-------+
| IS16-005 | AGNAJITA PATNAIK | 540.0 |
| IA16-001 | ASHIMA MISHRA | 540.0 |
| IA17-002 | Kiran Behera | 594.0 |
| IS16-010 | SAIMA KHAN QUADRI | 552.0 |
| IA16-005 | SARFRAZ AHMAD | 551.0 |
| IC16-002 | SUDHANSU SEKHAR SAHOO | 540.0 |
| IA17-001 | Trupti Biswal | 555.0 |
+----------+-----------------------+-------+
7 rows in set (0.00 sec)
Manipulating Data in a table:
In a data table, it requires many a times to insert new records, delete records
(on many grounds), change (update) the values stored in a field, etc. All these
operations may be called as manipulation of data. In MySQL, we use the
following commands to do the job;
1. INSERT INTO to add new records
2. UPDATE to change the existing data in fields
3. DELETE to remove rows (records) from a table
Inserting Rows
We have already used the INSERT INTO statement to add new rows to a
table. It requires three values:
the name of the table
the names of the columns in the table which have to be populated
(optional)
Corresponding values for the columns.
Syntax:
INSERT INTO <tablename>[<column list>] VALUES
(<value>, <value>…);
Relational Database Management System Introduction to MySQL 7.25
Example:
mysql> INSERT INTO Student VALUES
(‘IA17-001’,'Trupti Biswal','2000-05-27',
555,’Female’);
Query OK, 1 row affected (0.18 sec)
In the above example note that the column names for which data values are
populated are not specified. We can omit the column names if values have to
be inserted for every column in a table but in such a case the data values for
each column must match exactly the default order in which they appear in
the table (as shown in the DESCRIBE statement), and a value must be
provided for each column.
As mentioned above the column names could have been specified as the
following statement shows:
INSERT INTO Student(Roll,Name,DoB,Mark,Gender) VALUES
(‘IA17-001’,'Trupti Biswal','2000-05-27',
555,’Female’);
Suppose we know the Roll Number and Mark of a student, and we
want to insert it in to the table immediately without waiting for other
information like Name, Date of Birth, etc. It can be done by using the
following statement:
INSERT INTO Student (Roll, Mark) VALUES (‘IC17-009’, 405);
Those columns that are not specified in the list will have the default values (if
defined) else NULLs will be inserted. The following table verifies the
appearance of default values.
mysql> INSERT INTO Student (Roll, Mark) VALUES
-> ('IC17-009',405);
Query OK, 1 row affected (0.17 sec)
mysql> SELECT*FROM Student WHERE Roll='IC17-009';
+----------+------+------+-------+--------+
| Roll | Name | DoB | Mark | Gender |
+----------+------+------+-------+--------+
| IC17-009 | NULL | NULL | 405.0 | NULL |
+----------+------+------+-------+--------+
1 row in set (0.01 sec)
7.26 Information Technology Class-XII
We can also explicitly add NULL value by using the NULL keyword in the
VALUES list for those columns that can hold null values.
INSERT INTO Student VALUES (‘IC17-009’, NULL, NULL, 405,
NULL);
Note: A NULL value means no value has been entered for that column i.e. the
value for that column is not known.
While inserting data in to a table, we must remember;
Text values must be enclosed in quotes.
Standard date format is "yyyy-mm-dd".
Standard time format is "hh:mm:ss".
Quotes are required around the standard date and time formats.
UPDATE statement:
After populating a data table, later it is found that some field values
need to be changed; how can we do it? MySQL provides UPDATE command to
take care of such situations. The syntax for an UPDATE statement is;
UPDATE <table_name>
SET <column name> = <value>, [<column name> = <value>,
…]
[WHERE <condition>];
The statement can be used to update one or more columns together.
‘WHERE’ clause helps in updating the field value of a particular record (row)
in a table.
a) The following statement sets the Mark of all the rows in Student table
to 594.
UPDATE Student SET Marks1 = 94;
b) The following statement sets the Mark of the row with Roll as 'IC16-
002' to 540.
UPDATE Student SET Mark = 540 WHERE Roll =’IC16-
002';
Query OK, 1 row affected (0.03 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Relational Database Management System Introduction to MySQL 7.27
c) The following statement corrects the Name and updates Mark of the
student bearing Roll Number ‘IC16-005’ to ‘CLEMENT SAMARIA’ and
351 respectively in the Student table. This updation is shown below.
mysql> SELECT Roll, Name, Mark from Student
-> WHERE Roll='IC16-005';
+----------+--------------+-------+
| Roll | Name | Mark |
+----------+--------------+-------+
| IC16-005 | CLEMENT XESS | 252.0 |
+----------+--------------+-------+
1 row in set (0.00 sec)
mysql> UPDATE Student SET Name='Clement Samaria',
-> Mark=351 WHERE Roll='IC16-005';
Query OK, 1 row affected (0.16 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> SELECT Roll, Name, Mark from Student
-> WHERE Roll='IC16-005';
+----------+-----------------+-------+
| Roll | Name | Mark |
+----------+-----------------+-------+
| IC16-005 | Clement Samaria | 351.0 |
+----------+-----------------+-------+
1 row in set (0.02 sec)
DELETE statement:
Sometimes students leave institution or an employee leaves an
organization. Their records (rows) have to be deleted from the table. DELETE
statement is used to delete rows from a table. It removes the entire row, not
the individual column values. Care must be taken while using this statement
as accidentally important data may get deleted.
Syntax:
mysql> DELETE FROM < tablename> [ Where < condition>];
Following statement deletes the information of the student bearing the Roll
Number IC16-002 from the Student table.
DELETE FROM Student WHERE Roll=‘IC16-002’;
After removal of the record of the student having Roll Number IC16-
002, the new Student table is shown below. (Compare it with the earlier table
to verify the deletion!)
7.28 Information Technology Class-XII
mysql> DELETE FROM Student WHERE Roll='IC16-002';
Query OK, 1 row affected (0.17 sec)
mysql> SELECT*FROM Student;
+----------+-------------------+------------+-------+--------+
| Roll | Name | DoB | Mark | Gender |
+----------+-------------------+------------+-------+--------+
| IA16-001 | ASHIMA MISHRA | 1998-12-27 | 540.0 | NULL |
| IS16-003 | SARAH SMRUTI | 1999-06-15 | 351.0 | NULL |
| IA16-005 | SARFRAZ AHMAD | 1999-11-23 | 551.0 | NULL |
| IS16-005 | AGNAJITA PATNAIK | 2000-01-03 | 540.0 | NULL |
| IC16-005 | Clement Samaria | 1996-02-12 | 351.0 | NULL |
| IA16-006 | BISMAY PRADHAN | 1997-05-15 | 452.0 | NULL |
| IC16-006 | PRIYANKA PATRA | 1999-11-14 | 352.0 | NULL |
| IS16-010 | SAIMA KHAN QUADRI | 1999-10-30 | 552.0 | NULL |
| IA17-001 | Trupti Biswal | 2000-05-27 | 555.0 | Female |
| IA17-002 | Kiran Behera | 1999-02-01 | 594.0 | Male |
| IC17-001 | Nibedita Behera | 2001-05-15 | 414.0 | Female |
| IC17-009 | NULL | NULL | 405.0 | NULL |
+----------+-------------------+------------+-------+--------+
12 rows in set (0.03 sec)
DELETE FROM Student;
The statement given above deletes all the rows from the Student table. Use it
very carefully; because further data entry may not be easy!
Restructuring of table:
A Table consists of rows and columns. We can insert new rows by
using INSERT command and remove existing rows by DELETE command
and modify the field values by UPDATE command. However, to add / remove
columns (fields) or changing the data types of a column can be done by using
ALTER TABLE statement; a lot of which have already been discussed. Let’s
have some simple syntaxes of this statement.
1. ALTER TABLE <table_name> ADD <column_name> [datatype];
2. ALTER TABLE <table_name> DROP <column_name>
[datatype];
3. ALTER TABLE <table> MODIFY <column> <new_definition>;
The 1st statement adds a new column [with specified data types] to the table.
The 2nd statement removes a column as specified in it.
The 3rd statement modifies the data types of an existing column the table.
Relational Database Management System Introduction to MySQL 7.29
Functions in MySQL
In mathematics, a function makes calculation over one or more of its
arguments and generates a single definite value. Every function is generally
given a name for easy comprehension these are the most powerful tools in any
computer language. MySQL also uses these functions, through we can find
sum of values stored in a column or convert all characters of a name to
lowercase or round off salaries in a column to two decimal places and so on.
MySQL supports many functions to manipulate data. We can broadly
categorize functions into two types:
1. Single Row functions
2. Multiple Row Functions.
Single row functions operate on a single value to return a single value. They
can accept one or more arguments but return only one result per row. When
applied on a table, they return a single result for every row of the queried
(using SELECT statement) table. They are further categorized into:
i. String functions
ii. Numeric / Mathematical functions
iii. Date and Time functions
Multiple row functions operate on a set of rows to return a single value.
Examples include MAX ( ), MIN ( ), SUM ( ), AVG ( ), COUNT ( ), etc. These
are also called as Aggregate functions, which are discussed in Unit-3A of this
book.
i) String (Character) functions:
String functions operate on character type data. String functions are used
to extract, change, format or alter character strings. They return either
character or numeric values. The syntax (function_name and their
argument) and result of various Character functions of MySQL are
described below.
a) ASCII (string): This function operates over its argument, which is a
string (a group of characters) and returns the ASCII value of the left
most character of the string. If the sring is empty, it returns 0; if it is
NULL, the return value is also NULL.
A string is always enclosed within quotation marks; except NULL.
7.30 Information Technology Class-XII
mysql> SELECT ASCII('IT');
mysql> SELECT ASCII('99'); +-------------+
+-------------+ | ASCII('IT') |
| ASCII('99') | +-------------+
+-------------+ | 73 |
| 57 | +-------------+
+-------------+ 1 row in set (0.00 sec)
1 row in set (0.05 sec) ASCII value of I is 73
ASCII value of 9 is 57
mysql> SELECT ASCII(NULL); mysql> SELECT ASCII('');
+-------------+
| ASCII(NULL) | +-----------+
| ASCII('') |
+-------------+
| NULL | +-----------+
| 0 |
+-------------+ +-----------+
1 row in set (0.00 sec)
1 row in set (0.00 sec)
b) CHAR (N1, N2,…): This function interprets each argument N as an
integer and returns a string consisting of the characters given by the
code values of those integers. NULL values are skipped.
mysql> SELECT CHAR(65,83,72,65);
+-------------------+
| CHAR(65,83,72,65) |
+-------------------+
| ASHA |
+-------------------+
1 row in set (0.00 sec)
c) CONCAT (str1, str2, …): This function returns the string that results
from concatenating the arguments. May have one or more arguments.
If all arguments are non-binary strings, the result is a non-binary
string. If the arguments include any binary strings, the result is a
binary string. A numeric argument is converted to its equivalent
binary string form.
d) CONCAT_WS (separator, str1, str2,...): It stands for Concatenate With
Separator and is a special form of CONCAT(). The first argument is
the separator for the rest of the arguments. The separator is added
between the strings to be concatenated. The separator can be a string,
as can the rest of the arguments. If the separator is NULL, the result
is NULL.
Relational Database Management System Introduction to MySQL 7.31
mysql> SELECT CONCAT('State-','Odisha');
+---------------------------+
| CONCAT('State-','Odisha') |
+---------------------------+
| State-Odisha |
+---------------------------+
1 row in set (0.03 sec)
mysql> SELECT CONCAT_WS('-','dd','mm','yy');
+-------------------------------+
| CONCAT_WS('-','dd','mm','yy') |
+-------------------------------+
| dd-mm-yy |
+-------------------------------+
1 row in set (0.03 sec)
e) INSTR (str, substr): This function returns the position of the first
occurrence of substring substr in the string str. This is the same as the
two-argument form of another function LOCATE ( ), except that the
order of the arguments is reversed.
mysql> SELECT mysql> SELECT
INSTR('Mrunalinee','line'); INSTR('Information','far');
+----------------------------+ +----------------------------+
| INSTR('Mrunalinee','line') | | INSTR('Information','far') |
+----------------------------+ +----------------------------+
| 6 | | 0 |
+----------------------------+ +----------------------------+
1 row in set (0.06 sec) 1 row in set (0.00 sec)
f) LCASE (str) or LOWER (str): This function converts all the
characters of the string to lowercase.
mysql> SELECT mysql> SELECT
LCASE('INFORMation'); LOWER('INFORMation');
+----------------------+ +----------------------+
| LCASE('INFORMation') | | LOWER('INFORMation') |
+----------------------+ +----------------------+
| information | | information |
+----------------------+ +----------------------+
1 row in set (0.03 sec) 1 row in set (0.00 sec)
7.32 Information Technology Class-XII
g) UCASE (str) or UPPER (str): This function converts all the
characters of the string to UPPERCASE.
mysql> SELECT mysql> SELECT
UCASE('INFORMation'); UPPER('INFORMation');
+----------------------+ +----------------------+
| UCASE('INFORMation') | | UPPER('INFORMation') |
+----------------------+ +----------------------+
| INFORMATION | | INFORMATION |
+----------------------+ +----------------------+
1 row in set (0.03 sec) 1 row in set (0.00 sec)
h) LENGTH (str): This function returns the length of the string str,
measured in bytes. For example: LENGTH (‘at least’) returns 8.
Note that, the blank space is also being counted.
i) LTRIM (str): This function removes spaces, if any from the left side of
the string str. For example: LTRIM (‘ least’) returns least.
j) RTRIM (str): This function removes spaces, if any from the right side
of the string str. For example: LTRIM (‘least ’) returns least.
k) TRIM (str): This function removes both leading and trailing spaces, if
any from the string str. For example: TRIM (‘ least ’) returns
least.
l) SUBSTR (str, m, n) or MID (str, m, n): This function returns the
specified number of characters from the middle of the string. There are
three arguments. The first argument is the source string. The second
argument is the position of first character to be displayed. The third
argument is the number of characters to be displayed.
m) REVERSE (str): It reverse the string str.
mysql> SELECT
REVERSE('Odisha');
+-------------------+
| REVERSE('Odisha') |
+-------------------+
| ahsidO |
+-------------------+
1 row in set (1.00 sec)
Relational Database Management System Introduction to MySQL 7.33
n) LEFT (str, n): It returns n number of characters from the left side of
the string str.
o) RIGHT (str, n): It returns n number of characters from the right side
of the string str.
ii) Numeric / Mathematical functions:
These functions perform operations on numeric values and return
numeric values. Some of these functions and their functionalities are
outlined below.
a) POWER(x,y) or POW(x,y): This function returns the value of x raised
to the power of y.
mysql> SELECT POW(2,4); mysql> SELECT POW(2,-4);
+----------+ +-----------+
| POW(2,4) | | POW(2,-4) |
+----------+ +-----------+
| 16 | | 0.0625 |
+----------+ +-----------+
1 row in set (0.05 sec) 1 row in set (0.00 sec)
b) ROUND(x,d): This function rounds the argument x to d decimal
places.
c) ROUND(x): This function rounds the argument x to the nearest
integer.
mysql> SELECT mysql> SELECT ROUND(2.553);
ROUND(2.553,1); +--------------+
+----------------+ | ROUND(2.553) |
| ROUND(2.553,1) | +--------------+
+----------------+ | 3 |
| 2.6 | +--------------+
+----------------+ 1 row in set (0.00 sec)
1 row in set (0.06 sec)
d) TRUNCATE(x,d): This function returns the number x truncated to d
decimal places. If d is 0, the result has no decimal point or fractional
part. If d is negative, it causes d digits left of the decimal point of the
value x to become zero. The examples given below, illustrates the
functionality of this function.
7.34 Information Technology Class-XII
Example:
mysql> SELECT TRUNCATE (2.456, 1); Result: 2.4
mysql> SELECT TRUNCATE (5.656, 0); Result: 5
mysql> SELECT TRUNCATE (456, -2); Result: 400
Note: This function does not round a number, rather chops off digits
from a number.
iii) Date & Time functions:
These functions allow us to perform different types of tasks relating to
DATE type data; like: to calculate the age of a person, to know the day of any
given date, carry out addition or subtraction of days, months & years, etc. We
discuss few of such functions and their return values here. It is left to the
user of these functions, how he/she wants to utilize them in different
applications. The default date format in MySQL is YYYY-MM-DD.
a) CURDATE ( ): It returns current date in YYYY-MM-DD format or
YYYYMMDD format depending on whether the function is used in a
string or in numeric context.
mysql> SELECT CURDATE(); mysql> SELECT CURDATE()+100;
+------------+ +---------------+
| CURDATE() | | CURDATE()+100 |
+------------+ +---------------+
| 2017-04-23 | | 20170523 |
+------------+ +---------------+
1 row in set (0.08 sec) 1 row in set (0.06 sec)
Look at the 2nd cell of the table; the current date behaves as a decimal
number yyyymmdd.
b) DATE (expr ): It extracts the date part from date or datetime
expression
Example: mysql> SELECT DATE ('2016-04-05 10:10:07')
Result: '2016-05-04'
c) MONTH (date): It returns the month number (in the range of 0 and
12) of its date argument.
Example: mysql> SELECT MONTH ('2017-04-22')
Result: 4
mysql> SELECT MONTH ('2017-00-22')
Result: 0
Relational Database Management System Introduction to MySQL 7.35
d) DAYOFMONTH (date): It returns the day of the month (in the range
of 0 and 31) of its date argument.
Example: mysql> SELECT DAYOFMONTH ('2017-04-23')
Result: 23
e) DAYOFWEEK (date): It returns the day of week (in the range of 1
and 7; as 1 for Sunday, 2 for Monday and so on) of its date argument.
f) DAYOFYEAR (date): It returns the day of a year (in the range of 1
and 366) of its date argument.
mysql> SELECT DAYOFWEEK mysql> SELECT DAYOFYEAR
->('2017-04-27'); ->('2017-04-27');
+-------------------------+ +-------------------------+
| DAYOFWEEK('2017-04-27') | | DAYOFYEAR('2017-04-27') |
+-------------------------+ +-------------------------+
| 5 | | 117 |
+-------------------------+ +-------------------------+
1 row in set (0.62 sec) 1 row in set (0.03 sec)
g) DAYNAME (date): It returns the day name of its date argument.
mysql> SELECT DAYNAME('1989-07-19');
+-----------------------+
| DAYNAME('1989-07-19') |
+-----------------------+
| Wednesday |
+-----------------------+
1 row in set (0.06 sec)
h) NOW ( ): It returns current date & time in YYYY-MM-DD HH:MM:SS
format, when used as a string. In numeric context it becomes a
decimal number of the form yyyymmddhhmmss.
mysql> SELECT NOW(); mysql> SELECT NOW()+100;
+---------------------+ +----------------+
| NOW() | | NOW()+100 |
+---------------------+ +----------------+
| 2017-04-23 11:12:14 | | 20170423111314 |
+---------------------+ +----------------+
1 row in set (0.00 sec) 1 row in set (0.00 sec)
i) SYSDATE ( ): Its return value is exactly similar to the NOW ( )
function.
Note: SYSDATE ( ) returns the time at which the function executes;
whereas NOW ( ) returns a constant time that indicates the time at which
7.36 Information Technology Class-XII
the statement began to execute. To understand the difference between
these two similar functions, let’s invoke another function SLEEP (n);
which pauses the time for n number of seconds.
mysql> SELECT SYSDATE(),SLEEP(30),SYSDATE();
+---------------------+-----------+---------------------+
| SYSDATE() | SLEEP(30) | SYSDATE() |
+---------------------+-----------+---------------------+
| 2017-04-23 11:34:23 | 0 | 2017-04-23 11:34:53 |
+---------------------+-----------+---------------------+
1 row in set (30.22 sec)
mysql> SELECT NOW(),SLEEP(30),NOW();
+---------------------+-----------+---------------------+
| NOW() | SLEEP(30) | NOW() |
+---------------------+-----------+---------------------+
| 2017-04-23 11:35:56 | 0 | 2017-04-23 11:35:56 |
+---------------------+-----------+---------------------+
1 row in set (30.02 sec)
Above table shows that, SYSDATE ( ) does not pause, where as NOW ( ) does
pause for 30second.
______
Relational Database Management System Introduction to MySQL 7.37
EXERCISE
MULTIPLE CHOICE QUESTIONS :
1. MySQL is a /an
a. Relational Database b. Database
c. RDBMS d. Table
2. USE <databasename> command
a. is not used in MySQL b. is given before quitting MySQL
c. opens a table d. opens a database
3. Which of the following is a DML command?
a. CREATE b. DELETE
c. ALTER d. DROP
4. A database
a. Contains tables b. Is a part of a table
c. Is same as a table d. Removes data from a table
5. GRANT and REVOKE are ____________ commands.
a. DDL b. DML
c. DCL d. TCL
6. ORDER BY clause is used to sort data
a. in ascending order b. in descending order
c. both (a) and (b) d. None of the above
7. A table can have
a. Only one candidate key b. Only one primary key
c. Only one alternate key d. No alternate key
8. Wild card characters are used
a. In LIKE clause b. In ORDER BY clause
c. In BETWEEN clause d. In IN clause
7.38 Information Technology Class-XII
9. DDL is
a. a part of SQL b. a part of DML
c. a part of DCL d. None of the above
10. LIKE clause is used
a. For pattern matching
b. For table matching
c. For inserting similar data in a table
d. For deleting data from a table
11. Expand the use of following SQL functions:
ASCII ( ), CONCAT ( ), INSTR ( ), TRIM ( ), REVERSE ( ), LENGTH ( ),
ROUND ( ), DAYNAME ( ), CURDATE ( ), SYSDATE ( ).
LONG ANSWER TYPE QUESTIONS :
1. Explain sorting of data in a table by using ORDER BY clause.
2. Explain the use of UPDATE statements in manipulating data in a
table.
3. Distinguish between NOW ( ) and SYSDATE ( ).
4. Write down the syntax of at least four String based functions of
MySQL with examples.
5. Write down the syntax of at least three Numeric functions of MySQL
with examples.
6. How do you deal with NULL values in a database table?
7. Explain the use of ALTER TABLE statements in restructuring a table.
8. How many types of single row functions are there in MySQL? Explan
with examples.