Chapter 5 - MySQL Revision Tour
Chapter 5 - MySQL Revision Tour
Chapter - 5
5.1 Introduction
●
The collection of data, usually referred to as the database, contains
information about one particular enterprise.
●
A database system is basically a computer based record keeping
system.
●
A typical file-processing system has a number of major limitations and
disadvantages, such as data redundancy(duplication of data), data
inconsistency, unsharable, unstandarized ,insecure,incorrect etc.
●
A database management system is solution to all these problems as it
provides a centealized control of the data.
●
Various advantages od database systems are:
1. Database system reduce data redundancu to a jarge extent.
2. Database systems control data inconsistency to a large extent.
3. Database facilitate sharing of data.
4. Database enforce standards.
5. Centralized database can ensure data security.
6. Integrity can be maintained through databases.
5.2 Relational Data Model
●
In relational data model, the data is organized into tables(i.e. Rows and columns).
These tables are called relations.
●
A row in a table represent a relationship among a set of values.
●
Since a table is a collection of such relationship, it is generally refrred to using the
mathmatical term relation, from which the relational data model derives its name.
Different terms used in relational model.
●
When referential integrity s enforced, you must observe the following rules:
➢ You cant enter a value in the foreign key field of the related table that
doesn't exist.
➢ You can't delete a record from a primary table if matching records
exist in a related table.
➢ You can't change a primary key value in the primary table,if that
record has related records.
➢
5.3 MySQL – A Popular Relational Database Management System
●
MySQL is a freely available open source Relational Database Management
System(RDBMS) that uses Structure Query Language(SQL).
●
In a MySQL database, information is stored iin Tables.
●
A single MySQL database can contain many tables at once and store thousands
of individuals records.
●
MySQL provides you with a rich set of features that support a secure
enviroment for storing, maintaining and accessing data
●
MySQL is a fast, reliable, scalable alternative to many of the commercial
RDBMSs available today.
MySQL Database System
MySQL database system refers to the combination of a MySQL server instance
and a MySQL database. MySQL operates using client/server architecture in
which the server runs on the machine containing the databases and client
connect to the server over a network.
●
The server(MySQL server) : listen for client request coming in over the
network and accesses database contents accordning to those request to the
client
●
Clients are programs that connect to the database server and issue queries in
a pre-specified format.
5.3.1 MySQL and SQL
●
In order to access data within the MySQL database, all programs and
users must use, Structure Query Language(SQL).
●
SQL is the set of commands that is recognised by nearly all RDBMSs.
●
The Structure Query Language(SQL) is a language that enables you to
create and operate on relational databases , which are sets of related
information stored in tables.
Classification of SQL Statements
SQL provides many different types of commands used for different
purposes.SQL command can be mainly divided into following categories.
Data Definition Language(DDL) Commands : Allow you to perform tasks
to data definition e,g
1. creating , altering and dropping
2. granting and revoking privileges and roles.
3. maintenance commands
Data Manipulation Language (DML) Commands : Commands that allow
you to perform data manipulation e.g.
●
Retrieval,
●
Insertion,
●
deletion
●
and modification of data stored in a database.
Char Varchar
As the name suggests, CHAR stands for As the name suggests, VARCHAR stands
characters. for varible characters.
CHAR in MySQL stores characters of fixed VARCHAR in MySQL stores characters of
length. variable size.
CHAR in MySQL is used when the length of VARCHAR in MySQL is used when the
data is known so that we declare the field length of data is unkown.
with the same length.
CHAR in MySQL can store data up to 255 VARCHAR in MySQL can store data up to
characters. 65,535 characters.
CHAR pads values with spaces to reach VARCHAR does not pad values, it stores
the defined length, even if the data is only the actual data without adding extra
shorter. spaces.
CHAR takes 1 byte for each character VARCHAR takes 1 byte for each character
and some extra bytes for holding length
information
Better performance than VARCHAR. Performance is not good as compared to
CHAR.
5.4 Accessing Database in MySQL
●
Before you start writing SQL commands or making
queries upon the data in tables of a database you
need to open the database for use.
●
For this after lgging into MySQL you need to issue a
command
use<database name>
e.g
mysql> use inventory;
5.5 Creating Tables in MySQL
●
Tables are defined with the CREATE TABLE command. When a table is
created, its columns are named, data type and sizes are supplied for
each column.Each table must have at least one column.
●
The syntax of CREATE TABLE command is:
CREATE TABLE <table-name>
(<column name> <data type> [ ( <size> )],
(<column name> <data type> [ ( <size> )....];
●
To create an employee table whose schema is as follows :
employee(ecode, ename, gender , grade, gross )
the SQL command will be
CREATE TABLE employee
( ecode integer ,
ename char(20) ,
gender char(1) ,
grade char(2) ,
grade char(2) ,
gross decimal ) ;
5.6 Inserting Data into Table
INSERT command of SQL is used to add rows (tuples) to
table( relations). In its simples form, INSERT takes the following
syntax:
INSERT INTO <table name> [ <column list> ]
VALUES ( <value>, <value> ... );
e.g.
INSERT INTO employee
VALUES(1001, 'Ravi' , 'M' , 'E4' , 4670.00 );
SELECT what_to_select
FROM which_table
WHERE condition_to_satisfy;
–
●
The DISTINCT keyword eliminates duplicate rows from the result
of a SELECT statement.
1. Display names of all pet-owners (non-redundant).
mysql>SELECT DISTINCT owner FROM pet;
–
e.g.
mysql>DESC pet;
e.g.
SELECT CustomerID AS ID
FROM Customers;
5.7.9 Condition Based on a Range
●
The BETWEEN operator defines a range of values that the
column values must fall in to make the condition true.
●
The range includes both lower value and the upper value.
●
For example, to list the items whose QOH falls between 30 to 50
(both inclusive), the command would be :
●
The NOT IN operator finds rows that do not match in the
list.So if you write
SELECT * FROM members
WHERE city NOT IN ('DELHI' 'MUMBAI','CHENNAI');
it will list members not from the cities mentioned in the list.
5.7.11 Condition Based on Pattern Matches
●
SQL also includes a string-matching operator, LIKE for
comparisons on character string using patterns. Patterns are
described using two special wildcard characters:
– Percent (%) : The % character matches any substring.
– Underscore ( _ ): The _ character matches any character.
●
The LIKE keyword is used to select rows containing columns
that match a wildcard pattern.example
1. TO list members which are in areas with pin codes starting
with 13, the command is :
SELECT firstname, lastname, city
FROM members
WHERE pin LIKE '13%';
2. To list names of pets who have names ending with 'y', the
command would be:
SELECT name FROM emp WHERE name LIKE '%y';
5.7.12 Searching for NULL
●
The NULL value in a column can be searched for in a
table using IS NULL in the WHERE clause.
●
Relational operators like =,< > etc can't be used with
NULL.
●
For example , to list details of all employees whose
department contain NULL we may use the following
command
SELECT empno, empname, job
FROM emp WHERE DeptNO IS NULL;
Output Will be
5.8.1C SQL UNIQUE constraints
●
The UNIQUE constraints ensure that all values in a column are
distinct.In other words, no two rows can hold the same value for
a column with UNIQUE constraints. For example
●
The CHECK constraints ensure that all values in a column satisfy
certain conditions.
●
Once defined, the database will only insert a new row or update
an existing row if the new value satisfied the CHECK constraint.
●
The CHECK constraint is used to ensure data quality. For example
CREATE TABLE Customer
( SID integer CHECK( SID > 0 ),
Last_Name varchar (30) ,
First_Name varchar (30) ) ;
5.8.1E PRIMARY KEY constraints
●
A primary key is used to uniquely identify each row in a table.
●
It can either be part of the actual record itself, or it can be an artificial field.
●
A primary key can consist of one or more fields on a table.When multiple
fields are used as a primary key, they are called a composite key.
Primary Key can be specified either when the table is created or by changing
the existing table structure.
●
Defining Primary Key through Alter Table Command
ALTER TABLE Cutomer
ADD PRIMARY KEY (SID );
5.8.1F Foreign KEY constraints
●
In an RDBMS, tables reference one another through common fields and
to ensure validity of references, referential integrity is enforced.
●
Referential integrity is a system of rules that a DBMS uses to ensure
that relationship between records in related tables are valid and that
users don't accidentally delete or change related data.
Just like primary key, Foreign key can also be created in two ways :
through CREATE TABLE and ALTER TABLE commands.
CREATE TABLE ORDERS
( Order_ID integer,
Order_Date date,
Cutomer_SID integer,
Amount double,
Primary Key (Order_ID),
Foreign Key ( Customer_SID ) reference CUSTOMER( SID ) ) ;
The above code will designate Cutomer_SID field of ORDERS table as foreign
key referencing SID field of CUTOMER table.
●
The above statement ensure that the combination of icode and desc in
each row must be unique.
●
A constraint applied on one column (e.g as you define not null with a
column definition) is known as column constrains.
5.9 Viewing a Table Structure
●
The DESC (DESCRIBE) command is use to view an already
created/existing table's structure.
You can use DESC command as follows:
DESC <tablename>;
For example,
DESC empl;
Or DESCRIBE empl;
5.10 Inserting Data into another Table
●
INSERT command can also be used to take or derive values from
one table and place them in another by using it with a query.To
do this,simply replace the VALUES clause with an appropriate
query as shown in the following example:
●
It will extract all those rows from branch2 that have gross more
than 7000.00 and insert this produced result into the table
brach1. But for above command to work , table namely branch1
must be an existing table of the database.
5.11 Modifying Data in Tables
●
We can modify data in tables using UPDATE command of SQL.
●
The UPDATE command specifies the rows to be changed using the
WHERE clause, and the new data using the SET keyword.
●
The new data can be a specified constant, an expression or data from
other tables.
●
For example , to change the recorder level ROL of all items to 250, you
would write
UPDATE items
SET ROL = 250;
●
To update the ROL and QOH for items having icode less than 1040
UPDATE items
SET ROL = 400 , QOH = 700
WHERE icode < 1040
–
●
To doule the gross pay of employees of grade 'E3' and 'E4'
UPDATE employee
SET gross = gross *2
WHERE (grade = 'E3' OR grade = 'E4' );
5.12 Deleting Data From Tables
●
DELETE command is used to delete some data from tables.
●
The DELETE command removes rows from a table.This removes the entire
rows, not individual field values.
●
The DELETE statement takes the following general form:
DELETE FROM <tablename>
[ WHERE <predicate> ] ;
●
For instance, to remove the tuples from employee table that have gross
(salary) less than 2200.00, the command will be
If you specify no condition with WHERE, then all the rows of the table will be
deleted e.g.
●
To remove all the contents of items table, we use the command:
DELETE FROM items;
5.13 Altering Tables
●
The ALTER TABLE command is used to chanage definitions of existing tables.
●
In general, ALTER TABLE command is used:
– To add a column
– To add an integrity constraint
– To redefine a column(datatype, size, default value).
●
To add a new column tel_number of type integer in table Empl the command
will be-
ALTER TABLE Empl
ADD ( tel_number integer ) ;
●
To modify column job of table Empl to have new width of 30 character ,
commad will be-
ALTER TABLE Empl
MODIFY (Job char(30));
●
Sometimes you may need to change the name of your columns.For this you
can use CHANGE clause of ALTER TABLE command
ALTER TABLE Customers
CHANGE First_Name FirstName VARCHAR(20);
5.14 Dropping Tables
●
The DROP TABLE command of SQL lets you drop a table from the
database.
●
The syntax for using a DROP TABLE command is:
DROP TABLE ( IF EXISTS ) <table name>
●
That is , to drop a table items, you need to write:
DROP Table items;