You are on page 1of 121

1

CHAPTER 09
DATABASE CONNECTIVITY: MYSQL AND SQL
COMMANDS

9.1 Understanding
The Database
Learning Outcome :
Design
Process
Some advantages to good database design

Three types of table relationships

How to normalize your database

How to implement a good database design


process

9.1 Understanding
The Database
Topics covered in this lesson are.
Design Process

Chapter 15: Understanding the Database


Design Process

Chapter 16: Learning Basic SQL Commands

4
Chapter 15: Understanding the Database Design Process
9.1 The Importance of Good Database Design
9.2 Types of Table Relationships
9.3 Understanding Normalization
9.4 Following the Design Process

5
Chapter 16: Learning Basic SQL Commands
9.5 Learning the MySQL Data Types
9.6 Learning the Table Creation Syntax
9.7 Using the INSERT Command
9.8 Using the SELECT Command
9.9 Using WHERE in Your Queries
9.10

Selecting from Multiple Tables

9.11

Using the UPDATE Command to Modify Records

9.12

Using the REPLACE Command

9.13

Using the DELETE Command

9.14

Frequently Used String Functions in MySQL

9.15

Using Date and Time Functions in MySQL

9.1 The Importance


of Good Database
Important
for
a
high-performance
Design
application

Optimized
efficiently

Should be easy to maintain

relationships,

perform

store only a limited amount (if any) of repetitive


data

More time in designing database, before


start coding an application,

9.2 Types of Table


Relationships

Types

One-to-one relationships

One-to-many relationships

Many-to-many relationships

9.2 Types of Table


Relationships (cont)

One-to-one relationships

key appears only once in a related table

example

Figure 15.2(a) : one-to-one


relationship

Figure 15.2(b) : one-to-one


relationship (database view)

9.2 Types of Table


Relationships (cont)

One-to-many relationships

keys from one table appear multiple times in a


related table

most common type of relationship

example

Figure 15.2(c) : one-to-many


relationship

Figure 15.2(d) : one-to-many


relationship (database view)

9.2 Types of Table


Relationships (cont)

10

Many-to-many relationships

often causes problems in practical examples of


normalized databases

key value of one table can appear many times in


a related table

example

Figure 15.2(e) : many-to-many


relationship

9.2 Types of Table


Relationships (cont)

this relationship does not present an


easy method for relating tables

create an intermediate table, one


that sits between the two tables and
essentially maps them together

Figure 15.2(f) : many-to-many


relationship (database view)

11

9.3 Understanding
Normalization

Process of structuring data to minimize


duplication and inconsistencies

Art of organizing your database in such a


way that your tables relate where
appropriate and are flexible for future
growth

Rules used in normalization are called


normal forms

12

9.3 Understanding
Flat Table
Normalization
(cont)
A spreadsheetit has many, many columns

13

No relationships between multiple tables; all the


data could be found in right there

Inefficient and consumes more physical space

Example

StudentName student name

CourseID1 ID of first course taken by the student

CourseDescription1 - The description of the first course

CourseInstructor1 - The instructor of the first course

CourseID2 - ID of the second course taken by the student

CourseDescription2 - The description of the second course

CourseInstructor2 - The instructor of the second course

StudentName

CourseID1

CourseDescrip
tion1

CourseInstruct
or1

CourseID2 - ID

CourseDescrip
tion2

CourseInstruct
or2

9.3 Understanding
Normalization (cont)

First Normal Form

Rules

eliminate repeating information

create separate tables for related data

Example

two tables represent one-to-many relationship

14

9.3 Understanding
Normalization (cont)

Second Normal Form

Rules

no nonkey attributes depend on a portion of the


primary key

table are not entirely related to a primary key

Example

many-to-many relationship using an intermediary


mapping table

15

9.3 Understanding
Normalization (cont)

Third Normal Form

Rules

no attributes depend on other nonkey attributes

look at the tables and see whether more fields can


be broken down and not dependent on a key

Example

adequate for removing redundancy and allowing for


flexibility and growth

16

9.4 Following the


Design Process

Include a thorough evaluation of your


databasewhat it should hold, how data
relates to each other, and most important,
whether it is scalable

Steps

define the objective

design the data structures (tables, fields)

discern relationships

define and implement business rules

create the application

17

Learning Basic SQL


Commands
Learning

18

Outcome

The basic MySQL data types

How to use the CREATE TABLE command to create a table

How to use the INSERT command to enter records

How to use the SELECT command to retrieve records

How to use basic functions, the WHERE clause, and the GROUP
BY clause in SELECT expressions

How to select from multiple tables, using JOIN or subselects

How to use the UPDATE and REPLACE commands to modify


existing records

How to use the DELETE command to remove records

How to use string functions built in to MySQL

How to use date and time functions built in to MySQL

9.5 Learning the


MySQL Data Types

Three Categories

numeric

date & type

string

19

9.5 Learning the


MySQL Data Types
Numeric Data Types
(cont)

20

Standard ANSI SQL

Lists

INT - normal-sized integer that can be signed or


unsigned
if signed, the
2147483647

range

is

from

2147483648

to

if unsigned, the range is from 0 to 4294967295


can specify a width of up to 11 digits

TINYINT - small integer that can be signed or


unsigned.
if signed, the range is from 128 to 127
if unsigned, the range is from 0 to 255

9.5 Learning the


MySQL Data Types
(cont)

SMALLINT - small integer that can be signed or


unsigned
if signed, the range is from 32768 to 32767
if unsigned, the range is from 0 to 65535
can specify a width of up to 5 digits

MEDIUMINT - medium-sized integer that can be


signed or unsigned.
if signed, the range is from 8388608 to 8388607
if unsigned, the range is from 0 to 16777215
can specify a width of up to 9 digits

21

9.5 Learning the


MySQL Data Types
(cont)

BIGINT - large integer that can be signed or


unsigned
if signed, the range is from 9223372036854775808
to 9223372036854775807
if unsigned, the allowable range is from 0 to
18446744073709551615
can specify a width of up to 11 digits

FLOAT(M,D) - floating-point number that cannot


be unsigned.
can define the display length (M) & the number of
decimals (D)
decimal precision can go to 24 places for a FLOAT

22

9.5 Learning the


MySQL Data Types
(cont)

DOUBLE(M,D) - double-precision floating-point


number that cannot be unsigned
can define the display length (M) & the number of
decimals (D)
decimal precision can go to 53 places for a DOUBLE

DECIMAL(M,D)- unpacked floating-point number


that cannot be unsigned
in unpacked decimals, each decimal corresponds to 1
byte
defining the display length (M) & the number of
decimals (D) is required

23

9.5 Learning the


MySQL Data Types
Date and Time Types
(cont)

flexible in their input & can store dates with


missing information

MySQL checks only two elements for validity

month: between 0 and 12 & day: between 0 and 31

list

DATE - date in YYYY-MM-DD format


between 1000-01-01 and 9999-12-31

DATETIME - date and time combination in YYYYMM-DD HH:MM:SS format


between
23:59:59

1000-01-01

00:00:00

and

9999-12-31

24

9.5 Learning the


MySQL Data Types
(cont)

25

TIMESTAMP - define multiple lengths to the


TIMESTAMP field, which directly correlates to what
is stored in it
the default length
TYYYMMDDHHMMSS

for

TIMESTAMP

is

14,

example : 3:30 in the afternoon on December 30,


1973, is stored as 19731230153000

TIME - stores the time in HH:MM:SS format

9.5 Learning the


MySQL Data Types
(cont)

YEAR(M) - stores a year in two-digit or four-digit


format
if the length is specifies as 2 (for example, YEAR(2)),
YEAR can be 1970 to 2069 (70 to 69)
if the length is specified as 4, YEAR can be 1901 to
2155
the default length is 4.

26

9.5 Learning the


MySQL Data Types
String Data Types
(cont)
most data store will be in string format

list
CHAR(M) - fixed-length string between 1
and 255 characters in length
example :
CHAR(5); defining a length is not
required, but the default is 1

VARCHAR(M)
variable-length
string
between 1 and 255 characters in length
example : VARCHAR(25); must define a length
when creating a VARCHAR field

27

9.5 Learning the


MySQL Data Types
(cont)

BLOB or TEXT - field with a maximum length of


65,535 characters
BLOBs are Binary Large Objects ; used to store large
amounts of binary data, such as images
TEXT also hold large amounts of data
the difference is sorts and comparisons on stored data
are case sensitive on BLOBs and are not case
sensitive in TEXT fields
do not specify a length with BLOB or TEXT

28

9.5 Learning the


MySQL Data Types
(cont)

29

TINYBLOB or TINYTEXT - BLOB or TEXT column


with a maximum length of 255 characters
do not specify a length with TINYBLOB or TINYTEXT

MEDIUMBLOB or MEDIUMTEXT - BLOB or


TEXT column with a maximum length of 16,777,215
characters
do not specify a length with MEDIUMBLOB or
MEDIUMTEXT

LONGBLOB or LONGTEXT - BLOB or TEXT


column with a maximum length of 4,294,967,295
characters
do not specify
LONGTEXT

length

with

LONGBLOB

or

9.5 Learning the


MySQL Data Types
(cont)

ENUM - an enumeration, which is a fancy term for


list

defining an ENUM, are creating a list of items from


which the value must be selected (or it can be
NULL)
example, if you want your field to contain A or B or C,
you would define your ENUM as ENUM (A, B, C),
and only those values (or NULL) could ever populate
that field
can have 65,535 different values and use an index for
storing items.

30

Creating Database
1. Open any bowser, type localhost in search box and press enter

2. Click phpMyAdmin under Tools menu.

3. Click SQL

4. Type CREATE DATABASE 101 in Run SQL query/queries on server localhosts text area and click Go.

31

Creating Database
2nd option to create database

Create a name for the database (eg


database101)
then click
the button
Create

32

9.6 Learning the


Table Creation
Table-creation command requires
Syntax

name of the table

names of fields

definitions for each field

Generic table-creation syntax

CREATE TABLE
column_type);

table_name

(column_name

33

9.6 Learning the


Table Creation
Example
Syntax (cont)

CREATE TABLE grocery_inventory (


id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
item_name VARCHAR (50) NOT NULL,
item_desc TEXT,
item_price FLOAT NOT NULL,
curr_qty INT NOT NULL
);

34

9.7 Using the


INSERT Command

Adding new records to the tables

Consists of two main parts

35

the column list & the value list

Basic syntax of INSERT

INSERT INTO table_name (column list) VALUES (column


values);

9.7 Using the


INSERT Command
Example
(cont)

INSERT INTO grocery_inventory (id, item_name, item_desc,


item_price, curr_qty) VALUES (1, 'Apple', 'Red/Ripe', '0.25',
1000);

INSERT INTO grocery_inventory VALUES (2, 'Grapes',


'Purple/Seedless', '2.99', 500);

36

9.7 Using the


INSERT Command
(cont)
INSERT INTO grocery_inventory VALUES (3, 'Water Bottle
(12-pack)', NULL, '4.49', 500);

37

9.8 Using the


SELECT Command

To retrieve records from tables

Basic syntax of SELECT

SELECT expressions_and_columns FROM


table_name [ORDER BY some_column [ASC |
DESC]] [LIMIT offset, rows]

38

9.8 Using the


SELECT Command
Selecting
(cont)
Example

SELECT * FROM grocery_inventory;

SELECT id, item_name, curr_qty FROM grocery_inventory;

39

9.8 Using the SELECT


Command (cont)

Ordering

ASC - the selected rows will be ascending order

DESC - the selected rows will be in descending


order

Example
SELECT id, item_name, curr_qty FROM grocery_inventory
ORDER BY item_name DESC;

40

9.8 Using the SELECT


Command (cont)

Limiting

to return only a certain number of records

requirements needed

the offset (the starting position)

the number of rows should (be self-explanatory)

Example
SELECT id, item_name, curr_qty FROM grocery_inventory
ORDER BY item_name DESC LIMIT 0, 2;

41

9.9 Using the


WHERE in Your
To retrieve particular columns from your
Queries
tables but not specific rows

Basic syntax of WHERE

SELECT expressions_and_columns
FROM table_name [WHERE
some_condition_is_true]

42

9.9 Using the


WHERE in Your
Example
Queries (cont)

SELECT * FROM grocery_inventory WHERE curr_qty = 500;

43

9.9 Using the


WHERE in Your
Operators in WHERE
Queries (cont)

operator

meaning
=

Equal to

!=

Not equal to

<=

Less than or equal to

<
>=
>

Less than
Greater than or equal to
Greater than

44

9.9 Using the


WHERE in Your
BETWEEN Operator
Queries
(cont)
Example

SELECT * FROM grocery_inventory WHERE item_price


BETWEEN 1.50 AND 3.00;

45

9.9 Using the


WHERE in Your
LIKE Operator
Queries (cont)

comparing strings

uses two characters as wildcards in pattern


matching

% - matches multiple characters

_ - matches exactly one character

Example
SELECT * FROM grocery_inventory WHERE item_name LIKE 'A
%' ;

46

9.10 Selecting from


Multiple Tables

Select from more than one table in one


SELECT statement, you are really joining
the tables together

Example

two separate table

47

9.10 Selecting from


Multiple Tables
Create fruit and colour tables
(cont)

48

CREATE TABLE fruit (


id INT NOT NULL PRIMARY KEY
AUTO_INCREMENT,
fruit_name VARCHAR (50) NOT NULL,
fruit_status VARCHAR (50) NOT NULL
);
INSERT INTO fruit VALUES (1, 'Apple', 'Ripe'),
(2, 'Orange', 'Ripe'), (3, 'Grape', 'Ripe'), (4,
'Banana', 'Rotten');

CREATE TABLE colour (


id INT NOT NULL PRIMARY
KEY AUTO_INCREMENT,
colour_name VARCHAR (50)
NOT NULL
);
INSERT INTO colour VALUES (1,
'Red'), (2, 'Orange'), (3, 'Purple'),
(4, 'Yellow');

9.10 Selecting from


Multiple Tables
(cont)

select from both tables at once

ensure that all the tables youre


using in your query appear in
the FROM clause of the SELECT
statement

SELECT * FROM fruit, colour;

49

9.10 Selecting from


Multiple Tables
(cont)
When selecting from multiple tables

must build proper WHERE clauses to ensure that


get what really wanted

Append the table name to the field name

tablename.fieldname

SELECT fruit_name, colour_name FROM fruit, colour


WHERE fruit.id = colour.id;

50

9.10 Selecting from


Multiple Tables
Attempt to select a column that appears in
(cont)
both tables with the same name, you get

an ambiguity error

Example
SELECT id, fruit_name, colour_name FROM fruit, colour
WHERE fruit.id = colour.id;

51

9.10 Selecting from


Multiple Tables
Only use one column name from one table
(cont)

Example
SELECT fruit.id, fruit_name, colour_name FROM fruit,
colour WHERE fruit.id = colour.id;

52

9.10 Selecting from


Multiple Tables
Using JOIN
(cont)

to the order in which the tables are put together


and the results are displayed

Types

INNER JOIN

LEFT JOIN

RIGHT JOIN

53

9.10 Selecting from


Multiple Tables
INNER JOIN
(cont)
Example

SELECT fruit_name, colour_name FROM fruit INNER JOIN


colour ON fruit.id = colour.id;

54

9.10 Selecting from


Multiple Tables
Create student_name table
(cont)

CREATE TABLE student_name (


id INT NOT NULL PRIMARY KEY
AUTO_INCREMENT,
first_name VARCHAR (50) NOT NULL,
last_name VARCHAR (50) NOT NULL
);
INSERT INTO student_name VALUES (1, 'Alvin',
'Jimmy'), (2, 'Victor', 'Luhat'), (3, 'Jason', 'Anthony'),
(4, 'Asma', 'Izzati'), (5, 'Dulcie', 'David'), (6, 'Wai',
'Kei'), (7, 'Cheril', 'Henry');

55

9.10 Selecting from


Multiple Tables
Create student_email table
(cont)

CREATE TABLE student_email (


id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
email VARCHAR (50) NOT NULL
);
INSERT INTO student_email VALUES (1,
alvin@hotmail.com'), (4, asmamamia@gmail.com'), (5,
dulciesisis@gmail.com');

56

9.10 Selecting from


Multiple Tables
LEFT JOIN
(cont)

Example
SELECT student_name.id, first_name, last_name, email
FROM student_name LEFT JOIN student_email ON
student_name.id = student_email.id ORDER BY
student_name.id;

57

9.10 Selecting from


Multiple Tables
RIGHT JOIN
(cont)

Example
SELECT student_name.id, first_name, last_name, email
FROM student_name RIGHT JOIN student_email ON
student_name.id = student_email.id ORDER BY
student_name.id;

58

9.10 Selecting from


Multiple Tables
Using SUBQUERY
(cont)

a SELECT statement that appears within another


SQL statement

extremely useful

eliminate the need for bulky JOIN queries

subqueries can eliminate the need for multiple


queries
within
loops
(case
of
application
programming)

Basic SUBQUERY syntax

SELECT
expressions_and_columns
FROM
table_name WHERE somecolumn = (SUBQUERY);

59

9.10 Selecting from


Multiple Tables
Example
(cont)

SELECT first_name, last_name FROM student_name


WHERE id IN (SELECT id FROM student_email);

60

9.11 Using the


UPDATE Command
to Modify Records

To modify the contents of one or more columns in


an existing record or set of records

Basic syntax of UPDATE

UPDATE
table_name
SET
column1=new
value,
column2=new value2 [WHERE some_condition_is_true]

Guidelines for updating a record

appropriate to the data type of the field

must enclose the strings in single or


double quotes, escaping where necessary

61

9.11 Using the


UPDATE Command
Example
to Modify Records
(cont)

UPDATE fruit SET fruit_status = 'Rotten';

62

9.11 Using the


UPDATE Command
Must be careful and use a condition when
toupdating
Modify
Records
a table
Unless really intend to change all the
(cont)
columns for all records to the same value

Example
UPDATE fruit SET fruit_name = 'Grape';

63

9.11 Using the


UPDATE Command
Conditional UPDATEs
to Modify Records
(cont)

using WHERE clauses to match specific records

a WHERE clause in an UPDATE statement is just


like using a WHERE clause in a SELECT
statement

All the same comparison and logical operators can


be used

Example

UPDATE fruit SET fruit_name = 'Anggur' WHERE fruit_name


= 'Grape';

64

9.11 Using the


UPDATE Command
Using Existing Column Values with UPDATE
to Modify Records
(cont)
Example

the capability to use the current value in the


record as the base value

UPDATE grocery_inventory SET curr_qty = curr_qty - 15


WHERE id = 1;

65

9.12 Using the


REPLACE Command

To modifying records,
INSERT command

Basic syntax of REPLACE

similar

REPLACE INTO table_name


VALUES (column values);

66

to

the

(column

list)

If the record that been inserted into the


table contains a primary key value that
matches a record already in the table, the
record in the table is deleted and the new
record inserted in its place.

9.12 Using the


REPLACE Command
(cont)
Example

REPLACE INTO grocery_inventory VALUES (1, 'Granny


Smith Apples', 'Green/Sweet', '0.59', 1000);

67

9.13 Using the DELETE


Command

No column specification is used in the


DELETE command

When DELETE is used, the entire record is


removed

careful when using DELETE

Example
DELETE FROM fruit;

68

9.13 Using the


DELETE Command
Conditional DELETE
(cont)

using WHERE clauses to match specific records

Example
DELETE FROM fruit WHERE fruit_name = 'Anggur';

69

9.14 Frequently
Used String
MySQLs built-in string-related functions
Functions
can be used several in
ways MySQL

can use functions in SELECT statements without


specifying a table to retrieve a result of the
function

can use functions to enhance your SELECT


results by concatenating two fields to form a new
string

70

9.14 Frequently
Used String
Length and Concatenation Functions
Functions in MySQL
(cont)

Length-related functions (count characters in a


string)

LENGTH()

OCTET_LENGTH()

CHAR_LENGTH()

CHARACTER_LENGTH(),

Example
SELECT LENGTH('This is cool!');

71

9.14 Frequently
Used String
CONCAT() function
Functions in MySQL
(cont)
Example

concatenates two or more strings

SELECT CONCAT('My', 'S', 'QL');

72

9.14 Frequently
Used String
Using CONCAT() function with a table
Functions
containing names in MySQL
(cont)
Instead of using two strings, use two field

names to concatenate

reduce the lines of code necessary to achieve the


same result in your application

73

9.14 Frequently
Used String
Example
Functions in MySQL
(cont)

SELECT CONCAT (first_name, last_name) FROM student_name;

The function useful if there were some sort


of separator between the names

74

9.14 Frequently
Used String
CONTACT_WS()
Functions in MySQL
(cont)

concatenate with separator

separator can be anything

example : whitespace

Example
SELECT CONCAT_WS(' ', first_name,
last_name) FROM student_name;

75

9.14 Frequently
Used String
Shorten the width of result table
Functions in MySQL
(cont)
Example

use AS to name the custom result field

SELECT CONCAT_WS(' ', first_name, last_name) AS


student_fullname FROM student_name;

76

9.14 Frequently
Used String
Trimming and Padding Functions
Functions in MySQL
Adding and removing extra characters
(cont)
(including whitespace) from strings

RTRIM() and LTRIM() functions

remove whitespace from either the right or left


side of a string

77

9.14 Frequently
Used String
Example
Functions in MySQL
(cont)

SELECT RTRIM ('stringstring ');

SELECT LTRIM (' stringstring');

78

9.14 Frequently
Used String
TRIM() function
Functions in MySQL
(cont)
Example

to name the characters you want to remove

LEADING remove characters at the front

SELECT TRIM(LEADING 'X' FROM 'XXXneedleXXX');

79

9.14 Frequently
Used String
Functions in MySQL
(cont)

TRAILING remove characters at the end

SELECT TRIM(TRAILING 'X' FROM 'XXXneedleXXX');

if any not indicated, both are assumed

SELECT TRIM('X' FROM 'XXXneedleXXX');

80

9.14 Frequently
Used String
RPAD() and LPAD() functions
Functions in MySQL
(cont)

add characters to a string

elements : string, the target length, the padding


character

Example
SELECT RPAD('needle', 10, 'X');

SELECT LPAD('needle', 10, 'X');

81

9.14 Frequently
Used String
Location and Position Functions
Functions in MySQL
(cont)
LOCATE() function

for finding parts of strings within other strings

returns the position of the first occurrence of a


given substring within the target string

Example
SELECT LOCATE('needle', 'haystackneedlehaystack');

82

9.14 Frequently
Used String
Substring Functions
Functions in MySQL
(cont)
SUBSTRING() function

to extract a substring from a target string

a string, starting position, and length

Example

SUBSTRING

SELECT SUBSTRING('MySQL', 2, 3);

83

9.14 Frequently
Used String
Functions in MySQL
(cont)

LEFT function retain characters from the left


end

SELECT LEFT('MySQL', 2)

RIGHT function retain characters from the


SELECT
RIGHT('MySQL',
3);
right
end

84

9.14 Frequently
Used String
String Modification Functions
Functions in MySQL
Example
(cont)

LCASE () function - transform a string into


lowercase

SELECT LCASE('MYSQL');

UCASE () function - transform a string into


SELECT
UCASE('mysql');
uppercase

85

9.14 Frequently
Used String
Functions in MySQL
(cont)

use the functions with field names, no quotation


marks

SELECT UCASE(last_name) FROM student_name;

86

9.14 Frequently
Used String
Functions in MySQL
(cont)

REPEAT() function - repeats a string for a given


number of times

SELECT REPEAT('bowwow');

REPLACE() function - replaces all occurrences of


a given string with another string

SELECT REPLACE('bowwowbowwowbowwowbowwow',
'wow', 'WoW');

87

9.15 Using Date


and Time Functions
MySQLs built-in date-related functions in
in SELECT
MySQL
statements, with or without

specifying a table

to retrieve a result of the function

use the functions with any type of date field

date, datetime, timestamp, and year

depending on the type of field in use, the results


of the date-related functions are more or less
useful

88

9.15 Using Date


and Time Functions
Working with Days
in MySQL (cont)

DAYOFWEEK() and WEEKDAY() functions

both functions find the weekday index of a date

the difference lies in the starting day and


position

DAYOFMONTH () function

DAYOFYEAR() function

DAYNAME() function

89

9.15 Using Date


and Time Functions
Example
in MySQL (cont)

DAYOFWEEK - uses Sunday as the first day at


position 1 and Saturday as the last day at
position 7

SELECT DAYOFWEEK('2015-10-28');

WEEKDAY - uses Monday as the first day at


position 0 and Sunday as the last day at position
6

SELECT WEEKDAY('2015-10-28');

90

9.15 Using Date


and Time Functions
in MySQL (cont)

DAYOFMONTH - one result and a range that


starts at 1 and ends at 31

SELECT DAYOFMONTH('2015-10-28');

DAYOFYEAR - one result and a range that starts


at 1 and ends at 366

SELECT DAYOFYEAR('2015-12-31');

91

9.15 Using Date


and Time Functions
Create orders table
in MySQL (cont)

CREATE TABLE orders (


id INT NOT NULL PRIMARY KEY
AUTO_INCREMENT,
item_name VARCHAR (50) NOT NULL,
date_of_order VARCHAR (50) NOT NULL
);

INSERT INTO orders VALUES (1, 'black tshirt',


'2015-10-01'), (2, 'black jeans', '2015-10-01'), (3,
'purple poloshirt', '2015-10-05'), (4, 'white skirt',
'2015-10-07'), (5, 'yellow tshirt', '2015-10-15'),
(6, 'white blouse', '2015-10-20'), (7, 'brown
shorts', '2015-10-21'), (8, 'black shorts', '201510-21'), (9, 'black tshirt', '2015-11-24'), (10,
'purple blazer', '2015-11-27'), (11, 'white blouse',
'2015-11-27'), (12, 'black dressshirt', '2015-11-

92

9.15 Using Date


and Time Functions
in MySQL (cont)

DAYNAME - add more life to results because it


returns the name of the weekday for any given
date

SELECT DAYNAME(date_of_order) FROM orders;

93

9.15 Using Date


and Time Functions
Working with Months and Years
in MySQL (cont)

MONTH() and MONTHNAME() functions

return the number of the month in a year and the


name of the month for a given date

Example
SELECT MONTH('2015-01-01'), MONTHNAME('2012-01-01');

94

9.15 Using Date


and Time Functions
in MySQL (cont)

use MONTHNAME() on the orders table shows


the proper results but can show a lot of repeated
data

SELECT MONTHNAME(date_of_order) FROM orders;

95

9.15 Using Date


and Time Functions
in MySQL (cont)

use DISTINCT to get nonrepetitive results

SELECT DISTINCT MONTHNAME(date_of_order) FROM


orders;

96

9.15 Using Date


and Time Functions
YEAR() function
in MySQL (cont)

return the years of a given date

Example
SELECT DISTINCT YEAR(date_of_order) FROM orders;

97

9.15 Using Date


and Time Functions
Working with Weeks
in MySQL (cont)

WEEK ()

return the week of a given date

Example
SELECT WEEK('2015-12-31');

98

9.15 Using Date


and Time Functions
with Hours, Minutes,
and Seconds
inWorking
MySQL
(cont)

99

includes the exact time, such as datetime or timestamp,


or time field

HOUR(), MINUTE(), and SECOND() function

return hour in a given time, between 0 and 23, and return


minutes and seconds in a given time, each between 0 and
59

9.15 Using Date


and Time Functions
Example
in MySQL (cont)

SELECT HOUR('2015-10-28 14:30:26') AS hour,


MINUTE('2015-10-28 14:30:26') AS minute, SECOND('201510-28 14:30:26') AS second;

100

9.15 Using Date


and Time Functions
The hour and minute together
in MySQL (cont)

use CONCAT_WS() to put the : between the


results

get a representation of the time

Example
SELECT CONCAT_WS(':',HOUR('2015-10-28 14:30:26'),
MINUTE('2015-10-28 14:30:26')) AS sample_time;

101

9.15 Using Date


and Time Functions
Formatting Dates and Times with MySQL
in MySQL (cont)

DATE_FORMAT() function

formats a date, datetime, or timestamp field into


a string

using options that tell it exactly how to display


the results

Basic syntax of DATE_FORMAT

DATE_FORMAT(date,format);

102

9.15 Using Date


and Time Functions
Lists of formatting options
in MySQL (cont)

103

9.15 Using Date


and Time Functions
Example
in MySQL (cont)

SELECT DATE_FORMAT('2015-10-28 14:30:26', '%h:%i') AS


sample_time;

SELECT DATE_FORMAT('2015-10-28', '%W, %M %D, %Y')


AS sample_time;

SELECT DATE_FORMAT(NOW(),'%W the %D of %M, %Y


around %l o\'clock %p') AS sample_time;

104

9.15 Using Date


and Time Functions
Performing Date Arithmetic with MySQL
in MySQL (cont)

DATE_ADD() and DATE_SUB() function

more efficient to allow MySQL to do the math


than PHP script

return a result given a starting date and an


interval

Basic syntax of DATE_ADD and DATE_SUB

DATE_ADD(date,INTERVAL value type)

DATE_SUB(date,INTERVAL value type)

105

9.15 Using Date


and Time Functions
Lists of possible types and their expected
in value
MySQL
(cont)
format

106

9.15 Using Date


and Time Functions
Example
in MySQL (cont)

SELECT DATE_ADD(NOW(), INTERVAL 10 DAY);

SELECT DATE_SUB(NOW(), INTERVAL 10 DAY);

107

9.15 Using Date


and Time Functions
in MySQL (cont)
SELECT DATE_ADD('2015-10-28', INTERVAL 5 DAY);

SELECT DATE_ADD('2015-10-28', INTERVAL 12 HOUR);

SELECT '2015-10-28' + INTERVAL 3 DAY;

108

9.15 Using Date


and Time Functions
Special Functions and Conversion Features
in MySQL (cont)

MySQL NOW() function

returns a current datetime result

useful for timestamping login or access times

109

9.15 Using Date


and Time Functions
CURDATE()
and
CURRENT_DATE()
in functions
MySQL (cont)

synonymous

returns the current date in YYYY-MM-DD format

Example
SELECT CURDATE(), CURRENT_DATE();

110

9.15 Using Date


and Time Functions
CURTIME()
and
CURRENT_TIME()
in functions
MySQL (cont)

return the current time in HH:MM:SS format

Example
SELECT CURTIME(), CURRENT_TIME();

111

9.15 Using Date


and Time Functions
NOW(),
SYSDATE(),
and
in CURRENT_TIMESTAMP()
MySQL (cont)
functions

return values in full datetime format (YYYY-MMDD HH:MM:SS)

Example
SELECT NOW(), SYSDATE(), CURRENT_TIMESTAMP();

112

9.15 Using Date


and Time Functions
UNIX_TIMESTAMP() function
in MySQL (cont)

returns the current date in/or converts a given


date to UNIX timestamp format

UNIX timestamp format is in seconds

Example
SELECT UNIX_TIMESTAMP();

113

9.15 Using Date


and Time Functions
FROM_UNIXTIME() function
in MySQL (cont)

conversion of a UNIX timestamp to a full


datetime format when used without any options

Example
SELECT FROM_UNIXTIME('1445751492');

114

9.15 Using Date


and Time Functions
Use
the
format
options
from
the
in DATE_FORMAT()
MySQL (cont)

to display a timestamp in a more appealing manner

Example
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(), '%D %M %Y
at %h:%i:%s');

115

9.16 Summary

116

Following proper database design is the only


way that application will be efficient, flexible,
and easy to manage and maintain

Relationship Types; one-to-one, one-to-many,


and many-to-many

Normalization

use relationships to properly organize data

primary levels are the first, second, and third


normal forms

has a rule or two that must follow

following all the rules helps ensure that database is


well organized and flexible

Summary (cont)

Table-creation command requires three important


information

table name, field name, and field definitions

field definitions are important because a well-designed


table helps speed along the database

MySQL has three different categories of data


types

117

numeric, date and time, and string

INSERT command

to add records to a table, names the table and columns


and defines the values

enclose strings within single or double quotes

Summary (cont)

SELECT SQL command

to retrieve records from specific tables

LIMIT clause extracting slices of results

ORDER BY clause to select the columns to sort

WHERE clauses

118

pick and choose which records want to return

JOIN clauses

selecting records
statement

from

multiple

tables

within

one

requires forethought and planning to produce correct


result

types; INNER JOIN, LEFT JOIN, and RIGHT JOIN

Summary (cont)

119

UPDATE and REPLACE commands

modify existing data

UPDATE - changing values in specific columns and for


changing values in multiple records based on specific
conditions

REPLACE - variation of INSERT that deletes and then


reinserts a record with a matching primary key

DELETE command

removes whole records from tables

specify conditions so that records are removed only if a


particular expression in a WHERE clause is true

Summary (cont)

MySQLs built-in string-related functions

strings in MySQL that want to concatenate

pad or remove padding from strings

RPAD(), LPAD(), TRIM(), LTRIM(), and RTRIM()

find the location of a string within another string,


or return a part of a given string

CONCAT(), CONCAT_WS(), and LENGTH()

LOCATE(), SUBSTRING(), LEFT(), and RIGHT()

return variations of the original strings

LCASE(), UCASE(), REPEAT(), and REPLACE()

120

Summary (cont)

MySQLs built-in date and time functions

produce a custom display string from any sort of


date field

determine dates and times in the past or future

DATE_FORMAT() [formatting options]

DATE_ADD() and DATE_SUB() [available interval


types]

extracting parts of dates for use in WHERE or


ORDER BY clauses

DAY(), WEEK(), MONTH(), and YEAR()

121

You might also like