MySQL SQL REVISION TOUR
MySQL SQL REVISION TOUR
12
Revision Tour
In TWis Chapter
12.1 INTRODUCTION
A database system is basically a computer based record keeping system. The collection of data,
usually referred to as the database, contains information about one particular enterprise. In a
typical file-processing system, permanent records are stored in various files. A number of
aifferent application programs are written to extract records from files and add records to the
limitations and disadvantages, such as
appropriate files. But this scheme has a number of major
data redundancy (duplication of data), data inconsistency, unsharable data, unstandardized
aata, insecure data, incorrect data etc. A database nanagement system is answer to all these problems
as it provides a centralized control of the data.
456
Referential Integrity
A referential integrity is a system of rules that a DBMS uses to ensure that relationships between
records in related tables are valid, and that users don't accidentally delete or change related
data.
You can set referential integrity when all of the following conditions are met
The matching field from the primary table is a primary key or has a unique index.
The related fields have the same data type.
Both tables belong to the same database. Referential integrity can't be enforced for linked
table from databases in other formats.
When referential integrity is enforced, you must observe the following rules
You can't enter a value in the foreign key field of the related table that doesn't exist in the
primary key of the primary table. However, you can enter a Null value in the foreign key
specifying that the records are unrelated.
You can't deletea record from primary table if matching records exist in a related tabie
a
Data Type
Spec
DataType Spec Integer(-2147483648 to 2147483647)
CHAR String (0 - 255) INT
BIGINT Integer(-9223372036854775808 to
VARCHAR String (0-255) 9223372036854775807)
Decimal (precise to 23 digits)
TINYTEXT String (0 - 255) FLOAT
DOUBLE
Decimal (24 to 53 digits)
TEXT String (0- 65535)
"DOUBLE" stored as string
DECIMAL
BLOB String(0 -65535)
DATE YYYY-MM-DD
MEDIUMTEXT String (0 16777215)
YYYY-MM-DDHH:MM:SS
MEDIUMBLOB String (0- 16777215) DATETIME
TIMESTAMP YYYYMMDDHHMMSS
LONGTEXXT String (0 - 4294967295)
TIME HH:MM:SS
LONGBLOB String (0 4294967295)
TINYINT Integer (- 128 to 127) ENUM One of preset options
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 logging into MySQL, you need to issue a
Commarnd
Use <databasename
the
For example, we want to work on our sample database namely menagerie, so we shall write tn
following command after logging in MySOL.
mysql UsE menagerie ;
Database changed
mysql
Chapter 12: MYSQL SQL REVISION TOUR
459
12.5 CREATING TABLES IN MYSQL
Tables are defined with the
CREATE TABLE command. When a table is
named, data types and sizes are
column.
supplied for each column. Each table created, its columns are
must have at least one
ee the order of values matches the order of columns in the CREATE TABLE
command of
poye. The same can be done with an alternate command as shown below
INSERT INTO employee (ecode, ename, sex, grade, gross)
VALUES (10e1, °Ravi', M, °E4', 4670.00) ;
ne iNSERT statement adds a new row to employee giving a value for every column in the
to
. Note that the data values are in the same order as the column names in the table. Data
b e added only to some columns in a row by specifying the columns and their data.
For instance, if you want to insert only ecode, ename and sex columns, you use the command:
INSERT INTO employee (ecode, ename, seX)
VALUES (2014, Manju', "F°)
COMPUTER SCIENCE WITH PYTHON - A
460
command will NOTE
listed in the INSERT
The columns that are not otherwise,
it is defined for them,
have their default value, if In an INSERT statement,
only
those columns can be omitted tha
NULL value.
value and is
does not have a default have either default value
defined
It any other column (that is or they allow NULL values.
defined NOT NULL) is skipped or
omitted, an error message
Inserting Dates
Dates are by default entered in YYYY-MM-DD' format i.e., first four digits depicting year,
followed by a hyphen, followed by 2 digits of month, followed by a hyphen and a two digit day.
The SELECT statement is used to pull information from a table. The general form of the
statement is :
SELECT what_to_select
FROM which_table
WHERE Conditions_to_satisfy
table
2. Display distinct species of pets from pet
mysql> SELECT DISTINCT (species) FROM pet.
ALL Keyword
In place of keyword DISTINCT, you give keyword ALL then the result retains the duplicate
DISTINCT nor ALL ; ALL is
Oput rows. It is just the same as when you specify neither
nttally a clarifier rather than a functional argument. Thus if you give
syntax
DESCRIBE | DESC <table name>
for pet will display the structure oftable pet.
1stance, the comm
mands: DESCRIBE pet o r DESC
From <tablename>
For example,
mysql> SELECT date, type AS "EVvent Type"
-FROM event.
12.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 :
SELECT icode, descp, QOH
FROM items
WHERE QOH BETWEEN 30 AND 50
The NOT IN operator finds rows that do not match in the list. So if you write
it will list members not from the cities mentioned in the list.
Even though we didn't specify a value for the Score column in the INSERT INTO statement, it
does get assigned the default value of 80 since we had already set 80 as the default value for this
column.
rOWS can hold the same value for a column with UNIQUE constraint.
ror
example, in the following CREATE TABLE statement,
Qureshi Zeeshan
Rastogi Rajiv
cOMPUTER SCIENCEWITH PYTHON - XlL
466
NOTE
the following SQL statement,
Executing Please note that a column that is specif.
INSERT INTO Customer as a primary key must also be uniqus
At
VALUES (3','Cyrus', 'Grace); the same time, a column that's
may or may not be a primary
unique
key.
will result in an error because the value 3 already exists in In
row With
addition, multiple UNIQUE constraints
the SID column, thus trying to insert another
can be defined on a table but PRIMARY KEY
that value violates the UNIQUE constraint. constraint is defined only once in thetable
Last_Name varchar(30),
First_Name varchar (30) )
CREATE TABLE Customer
or
SID integer not nul1,
469
Vou can use DESYRIBE] Command as follows:
DESC[RIBE] <tablename;
For example,
DESCempl1
DESCRIBE empl
It will extract all those rows from branch2 that have gross more than 7000.00 and insert this
produced result into the table branch1. But for above command to work, table namely branch1
must be an
existing table of the database.
UPDATE employee
SET gross = gross * 2
HERE (grade = "E3' OR grade = E4°) ;
12.12 DELETING
DATA FROM TABLES
To delete some DELETE commands. The DELETE command
Temo Ome data from tables, you can use SQL rows, not individual field values, so no field
wS from a table. This removes the entire
lm
Sument is needed or
accepted.
cOMPUTER SCIENCE WITH PYTHON.
470
form
The DELETE statement takes the following general
DELETE FROM <tablename>
[WHERE <predicate> ]s
For instance, to remove the tuples from employee table that have groSs (salary) less than 2200 00
,
the following command is used
DELETE FROM employee
WHERE gross < 2200.00;
If you specify no condition with WHERE, then all the rows of the table will be deleted, eg,
To remove all the contents of items table, you use the command:
DELETE FROM items
To modijfy existing columns of table, ALTER TABLE command can be used according to following
syntax:
ALTER TABLE <tabllename>
MODIFY (columname newdatatype (newsize)) [FIRST|AFTER column] ;
To modify column Job of table Empl (given just before the Assignment at the end of this chapter)
to have new width of 30 characters, you may give:
ALTER TABLE Empl
MODIFY (Job char(30) );
Sometimes you may need to change the name of one of your columns. For this you can use
CHANGE clause of ALTER TABLE command
ALTER TABLE
as per following syntax
CHANGE [COLUMN] old_col_name new col_name
column_definition
For instance, to change the existing column namely First Name of table Student,
you may write:
to Fi'st
ALTER TABLE Customers See, complete column
description is
given along with the new name.
CHANGE First_Name FirstName VARCHAR (20);
1 2 : MYSQL SGQL REVISION TOUR
For example,
he above SQL statement will irst join the tables EMPL and DEPT on the basis of join condition
EPL.DEPTNO = DEPT.DEPTNO. That is a record from table EMPL will join with a record
rom DEPT table whose DEPTNO is equal to its DEPTNO.
0) Cartesian Product. An SQL join query without any join condition returns all the records
of joined with all the records of the other table. It is known as a Cartesian Product, This
type of join is also known as a CROSS JON.
) Equi Join. An SQL join query that joins two or more tables based on a condition using
equality operator.
n n e r Join. An INNER JOIN implerments an equi join. In this join, only those rows are
condition. The Join conditions can
erurned from both the tables that satisfy the join
match records based on one or more columns.
(io) atural
Natural Join. A NATURAL JOIN is a type of equi join where the join condition
) Left Join. The LEFT JOIN is a particular type of join that selects rows from both left and
right tables that are matched, plus all rows from the left table (Table A) even with ne
no
matching rows found
in the right table
(Table B).
A B A
SELECT<fields list>
and right tables that FROM TableA T1
are matched, plus all INNER JOIN TableB T2
B ON T1.Key = T2.Key B
rows from the right
table (Table B) even
with no matching rows SELECT<fields list> SELECT <fields list
FROM TableA T1 FROM TableA T1
found in the left table LEFT JOIN TableB T2 RIGHT JOIN TableB T2
ON T1.Key = T2.Key ON T1.Key = T2.Key
(Table A). WHERE T2.Key IS NULL; WHERE T1.Key IS NULL;
101
102
103
Notice the Percentage
Roll No. Name
order of 104
records in 83
101 Nimish
each of
these index 102 Junaid 87
Percentage Location Pointer
tables
95
103 Gurjyot
83
Catherine
85
104
85
Table Student
87
95
Nimish
Indexes in MySQL
Creating
MySQL. also provides commands to create indexes in a database. You can create indexes
fn MvSQL using following commands. MySQL provides two ways to create indexes:
(Create index at the time of table creation i.e., along with CREATE TABLE command.
() Create index on an already existing table.
LET US REVISE
CREATE TABLE command is used to create tables in database.
INSERT INIOcommand is used to insert data in the table.
Toinsert data from other tables, subquery can be used inside INSERT INTO command.
Existing data in tables can be changed with UPDATE command.
Tuples in a table can be deleted using DELETE command.
ALTER TABLE command is used to alter the
definition of already created tables.
WithALTER TABLE, new columns can be added, existing columns can be redefined.
DROP TABLE command drops a table from a database.
A join is an SQL query that fetches records from two or more tables based ona condition.
Anindex is a data structure maintained by a database, that stores the sorted values within the index field and their
location in actual data.
You can create indexes either by using INDEX clause
of CREATE TABLE command or by using command CREAlE
INDEX.
OTQ5
Multiple Choice Ouestions
1 A relational database consists of a collection of
(a) Tables (b) Fields (c) Records (d) Keys
2 A relational database consists of collection of
a