5.introduction To MySQL
5.introduction To MySQL
5.introduction To MySQL
2
MySQL Basics
• A database is a structured collection of records or data stored in a
computer system and organized in such a way that it can be quickly
searched and information can be rapidly retrieved.
• The SQL in MySQL stands for Structured Query Language.
• This language is loosely based on English and also used in other databases
such as Oracle and Microsoft SQL Server.
• It is designed to allow simple requests from a database via commands such
as:
SELECT title FROM publications WHERE author = 'Charles Dickens';
3
Summary of Database Terms
• Database: The overall container for a collection of MySQL data
• Table: A subcontainer within a database that stores the actual data
• Row: A single record within a table, which may contain several fields
• Column: The name of a field within a row
4
Example- publications table
5
Show
databases
MySQL Commands
Command Action
ALTER Alter a database or table
BACKUP Backup a table \c
CREATE Create a database
DELETE Delete a row from a table
DESCRIBE Describe a table’s columns
DROP Delete a database or table
GRANT Change user privileges
INSERT Insert data
7
MySQL Commands
Command Action
LOCK Lock table(s)
RENAME Rename a table
SHOW List details about an object
SOURCE Execute a file
TRUNCATE Empty a table
UNLOCK Unlock table(s)
UPDATE Update an existing record
8
MySQL Commands
• SQL commands and keywords are case-insensitive. CREATE, create,
and CrEaTe all mean the same thing. However, for the sake of clarity,
the recommended style is to use uppercase.
• Table names are case-sensitive on Linux and OS X.
• but case-insensitive on Windows.
• So for portability purposes, you should always choose a case and stick
to it. The recommended style is to use lowercase for tables.
9
Creating a database
• create a new database called publications using SQL tab in phpMyAdmin:
10
Creating a database
• Using script, now that you’ve created the database, you want to work
with it, so issue the following:
USE uwinid_pbl;
11
Creating a user
• As you probably won’t want to grant your PHP scripts root access to
MySQL; it could cause a real headache should you get hacked
• To create a user, issue the GRANT command, which takes the
following form
• GRANT PRIVILEGES ON database.object TO 'username'@'hostname'
IDENTIFIED BY 'password';
• This should be pretty straightforward, with the possible exception of
the data base.object part, which refers to the database itself and the
objects it contains, such as tables
12
Granting access to the created user
• Lets assume that we have created the following user:
• ENGINE MyISAM tells MySQL the type of database engine to use for
this table.
DESCRIBE classics;
14
sajak
sajak_db
sajak_pbl
sajak_test
15
sajak
sajak_db
16
We use DESCRIBE:
1- to check the table
has been created sajak_db
CORRECTLY. sajak_pbl
2- to remember the
fields of the table, If
they are needed for
development or
query
17
Data Types - The CHAR data type
• All these types offer a parameter that sets the maximum (or exact) length
of the string allowed in the field
Data type Bytes used Examples
CHAR(5)“Hello” uses 5 bytes
CHAR(n) Exactly n (<= 255)
CHAR(57)“Goodbye” uses 57 bytes
VARCHAR(7) “Morning” uses 7 bytes
VARCHAR(n) Up to n (<= 65535)
VARCHAR(100) “Night” uses 5 bytes
• CHAR more efficient when the length fixed or mostly fixed e.g year field
• VARCAR saves more spaces when the values in the columns vary.
18
The TEXT and VARCHAR data types
19
The TEXT and VARCHAR data types
• The differences between TEXT and VARCHAR are small:
TEXT fields cannot have default values.
MySQL indexes only the first n characters of a TEXT column (you specify n
when you create the index).
• VARCHAR is the better and faster data type to use if you need to
search the entire contents of a field.
• If you will never search more than a certain number of leading
characters in a field, you should probably use a TEXT data type
20
Data Types - The BINARY data type
• The BINARY data type is used for storing strings of full bytes that do
NOT have an associated character set.
• For example, you might use the BINARY data type to store a GIF image
21
The BLOB data type
• The term BLOB stands for Binary Large Object and, therefore, as you
would think, the BLOB data type is most useful for binary data in
excess of 65,536 bytes in size.
• The main other difference between the BLOB and BINARY data types
is that BLOBs cannot have default values
Data type Bytes used Attributes
TINYBLOB(n) Up to n (<= 255) Treated as binary data—no character set
BLOB(n) Up to n (<= 65535) Treated as binary data—no character set
MEDIUMBLOB(n) Up to n (<= 1.67e+7) Treated as binary data—no character set
LONGBLOB(n) Up to n (<= 4.29e+9) Treated as binary data—no character set
22
Numeric data types
• MySQL supports various numeric data types from a single byte up to
double precision floating-point numbers.
• Although the most memory that a numeric field can use up is 8
bytes, you are well advised to choose the smallest data type that will
adequately handle the largest value you expect.
• Your databases will be small and quickly accessible.
23
Numeric data types
Data Type Bytes Minimum value Maximum
used Signed Unsigned Signed Unsigned
TINYINT 1 –128 0 127 255
SMALLINT 2 –32768 0 32767 65535
MEDIUMINT 3 –8.38e+6 0 8.38E+06 1.67E+07
INT/INTEGER 4 –2.15e+9 0 2.15E+09 4.29E+09
BIGINT 8 –9.22e+18 0 9.22E+18 1.84E+19
FLOAT 4 –3.40e+38 n/a 3.40E+38 n/a
DOUBLE/REAL 8 –1.80e+308 n/a 1.80e+308 n/a
24
Numeric data types
• To specify whether a data type is signed or unsigned, use the
UNSIGNED qualifier, default is SIGNED.
• CREATE TABLE tablename (fieldname INT UNSIGNED);
• you can also pass an optional number as a parameter:
• CREATE TABLE tablename (fieldname INT(4));
• Unlike BINARY and CHAR data types, the size parameter does not
indicate the number of bytes of storage to use.
• It actually represents is the display width of the data in the field
when it is retrieved.
25
DATE and TIME
• The main remaining data types supported by MySQL relate to the
date and time
Data type Time/date format
DATETIME '0000-00-00 00:00:00'
DATE '0000-00-00'
TIMESTAMP '0000-00-00 00:00:00'
TIME '00:00:00'
YEAR 0000 (Only years 0000 and 1901–2155)
26
DATE and TIME
• The DATETIME and TIMESTAMP data types display the same way.
• The main difference is that TIMESTAMP has a very narrow range
(from the years 1970 through 2037),
• DATETIME will hold just about any date you’re likely to specify, unless
you’re interested in ancient history or science fiction.
• TIMESTAMP is useful, however, because you can let MySQL set the
value for you. If you don’t specify the value when adding a row, the
current time is automatically inserted.
27
The AUTO_INCREMENT function
• Sometimes you need to ensure that every row in your database is
guaranteed to be unique.
• ISBN (International Standard Book Number) as an example.
CREATE TABLE classics ( author VARCHAR(128),
title VARCHAR(128),
type VARCHAR(16),
year CHAR(4),
id INT UNSIGNED NOT NULL AUTO_INCREMENT KEY) ENGINE MyISAM;
• An auto-increment column is useful as a key, because you will tend to
search for rows based on this column.
28
Add column to a table
• Changing structure of a table needs ALTER TABLE command
• If you already have created classics table in slide 15, and you want to
add ID
• You can do so as:
ALTER TABLE classics ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT KEY;
29
Adding data to a table
• To add data to a table, use the INSERT command
INSERT INTO classics(author, title, type, year) VALUES('Mark Twain','The
Adventures of Tom Sawyer','Fiction','1876');
INSERT INTO classics(author, title, type, year) VALUES('Jane Austen','Pride and
Prejudice','Fiction','1811');
INSERT INTO classics(author, title, type, year) VALUES('Charles Darwin','The
Origin of Species','Non-Fiction','1856');
INSERT INTO classics(author, title, type, year) VALUES('Charles Dickens','The
Old Curiosity Shop','Fiction','1841');
INSERT INTO classics(author, title, type, year) VALUES('William
Shakespeare','Romeo and Juliet','Play','1594');
30
Renaming a table
• like any other change to the structure or meta information about a
table, is achieved via the ALTER command.
• If you tried that command, you should revert the table name by
entering the following, so that later examples in this chapter will work
as printed:
31
Changing the data type of a column
• Changing a column’s data type also makes use of the ALTER
command, this time in conjunction with the MODIFY keyword.
• So to change the data type of column year from CHAR(4) to
SMALLINT
32
Adding a new column
• Here’s how to add the new column pages, which will be used to store
the number of pages in a publication:
33
Renaming a column
• A column named ‘type’ can be confusing, because that is the name
used by MySQL to identify data types.
• let’s change its name to category, like this:
34
Removing a column
• you might decide that the page count column pages isn’t actually all
that useful for this particular database
• To remove it:
• Remember that DROP is irreversible and you should always use it with
caution, because you could inadvertently delete entire tables (and
even databases) with it if you are not careful!
35
Deleting a table
• I don’t want you to have to reenter all the data for the classics table, let’s
quickly create a new table
DESCRIBE disposable;
• Lets drop it now
SHOW tables;
36
Indexes
• As things stand, the table classics works and can be searched without
problem by MySQL
• Until it grows to more than a couple of hundred rows, that is.
• At that point, database accesses will get slower and slower with
every new row added.
• because MySQL has to search through every row whenever a query is
issued.
37
Creating an Index
• It can be done when creating a table or at any time afterward.
• You must decide which columns require an index.
• Judgment that requires you to predict whether you will be searching
any of the data in that column.
• You can combine multiple columns in one index
• The Pages column that we deleted, is an example of columns that
usually people don search, so no need to index it.
38
Creating an Index
• In classics table , all those columns can be searched- lets create indexes for
them:
ALTER TABLE classics ADD INDEX(author(20));
ALTER TABLE classics ADD INDEX(title(20));
ALTER TABLE classics ADD INDEX(category(4));
ALTER TABLE classics ADD INDEX(year);
DESCRIBE classics;
• The first two commands create indexes on both the author and title
columns, limiting each index to only the first 20 characters to optimize the
search speed.
• E.g. The Adventures of Tom Sawyer =only=> The Adventures of To
• For category column it can be reduced to 1 (F for Fiction, N for Nonfiction,
and P for Play)
39
Using CREATE INDEX
• Create index independently from creating table
40
Adding indexes when creating tables
• CREATE TABLE classics ( author VARCHAR(128),
title VARCHAR(128),
category VARCHAR(16),
year SMALLINT, INDEX(author(20)),
INDEX(title(20)),
INDEX(category(4)),
INDEX(year))
ENGINE MyISAM;
41
Primary keys
• Primary key columns are indexed columns
• The slide “The AUTO_INCREMENT data type” , briefly introduced the idea
of a primary key when creating the auto-incrementing column id, which
could have been used as a primary key for this table.
• However, we are going to use ISBN
• Unique, You cannot duplicate this value (give same ISBN for 2 different
publications
• You cannot insert/update NULL as an entry value to this column
42
UPDATE .. SET .. WHERE
• If you wish to change the contents of one or more fields, you need to
first narrow in on just the field or fields to be changed.
• Luckily, each of the years is unique in the current set of data, so we
can use the year column to identify each row for updating.
ALTER TABLE classics ADD isbn CHAR(13);
UPDATE classics SET isbn='9781598184891' WHERE year='1876';
UPDATE classics SET isbn='9780582506206' WHERE year='1811';
UPDATE classics SET isbn='9780517123201' WHERE year='1856';
UPDATE classics SET isbn='9780099533474' WHERE year='1841';
UPDATE classics SET isbn='9780192814968' WHERE year='1594';
ALTER TABLE classics ADD PRIMARY KEY(isbn);
DESCRIBE classics;
43
Creating primary key when create a table
• CREATE TABLE classics1 ( author VARCHAR(128),
title VARCHAR(128),
category VARCHAR(16), Classics1, or rename classics to
classics1 then recreate it using
year SMALLINT, this slide command
isbn CHAR(13),
INDEX(author(20)),
INDEX(title(20)),
INDEX(category(4)),
INDEX(year),
PRIMARY KEY (isbn)) ENGINE MyISAM;
44
Creating a FULLTEXT index
• Unlike a regular index, MySQL’s FULLTEXT allows super-fast searches
of entire columns of text
• FULLTEXT indexes can be used only with MyISAM tables.
• MySQL has tens of different engine, to change ENGINE use:
ALTER TABLE tablename ENGINE = MyISAM;.
• FULLTEXT indexes can be created for CHAR, VARCHAR, and TEXT
columns only.
• FULLTEXT INDEX can take place either in CREATE TABLE or ALTER
TABLE
Charles Dicken has to appear 1 time with DISTINCT twice without DISTINCT
47
MATCH...AGAINST
• The MATCH...AGAINST construct can be used on columns that have
been given a FULL TEXT index
• It uses Natural Language algorithm.
• Unlike the use of WHERE.. It let you enter multiple words in a search
query and checks them against all words in the FULLTEXT columns.
• It is case-insensitive
• FULLTEXT index can search all words, except a list of common word
“and, is ,or ..etc” called stopword list, MySQL ignore searcing
stopword words.
48
MATCH...AGAINST
• SELECT author,title FROM classics WHERE MATCH(author,title)
AGAINST('and');
This select will return NOTHING, since ‘and’ is stopword
• SELECT author,title FROM classics WHERE MATCH(author,title)
AGAINST('curiosity shop');
49
MATCH...AGAINST...in Boolean Mode
• Boolean mode also allows you to preface search words with a + or -
sign to indicate whether they must be included or excluded.
SELECT author,title FROM classics WHERE MATCH(author,title)
AGAINST('+charles -species' IN BOOLEAN MODE);
50
MATCH...AGAINST...in Boolean Mode
• To understand the diference between with/without IN BOOLEAN + -
SELECT author,title FROM classics WHERE MATCH(author,title)
AGAINST('charles species'); ….(ANY)
51
ORDER BY
• ORDER BY sorts returned results by one or more columns in
ascending or descending order
53
• Learning PHP, MySQL & JavaScript, 4th
Edition. With jQuery, CSS & HTML5, by
Robin Nixon, O'Reilly Media, 2014,
References 978-1-4919-1866-1, chapter 7
54