MySql Glossary

Comments:

# to end of line, or
-- to end of line, or
/* across multiple lines. */

Field and Column

are usually synonymous.

Row and Record

are usually synonymous.

Table

an organized collection of Records.

Primary Key

always unique (NOT NULL).

Normalized

data in a table table, meets certain storage criteria such as a key, and ‘atom’ field
contents.

Indexes

special columns the developer flags so the data engine may sort and may keep
secondary key lists to optimize performance.

Join

combines the common elements of two tables into a single table.
If t1=a,b,c and t2=b,c,d then JOIN=b,c

Left Join

The left table in the Join statement is preserved even if there isn't a match with the right
table.
If t1=a,b,c and t2=b,c,d, then LEFT JOIN=a,b,c

MySql Reference – by Jan Zumwalt

Pg - 1 of 43

NeatInfo.com – February, 06, 2012

Table of Contents
PHP COMMUNICATIONS WITH MYSQL...................................................................................................... 4
SELECT & WHERE SYNTAX........................................................................................................................ 5
MYSQL SIMPLE EXAMPLES ....................................................................................................................... 6
STEP 1: CONNECT.................................................................................................................................................... 6
STEP 2: QUERY......................................................................................................................................................... 6
STEP 3: FETCH RESULTS ........................................................................................................................................ 6
STEP 4: EXTRACT INFORMATION FROM FETCH .................................................................................................. 6
SPECIFIC ROW DATA ............................................................................................................................................... 6
ROW COUNT.............................................................................................................................................................. 6
CLOSE CONNECTION............................................................................................................................................... 7

SIMPLE DATABASE EXAMPLE................................................................................................................... 8
MYSQL DEBUG EXAMPLES...................................................................................................................... 12
EXAMPLE1: Hide mysql array values in html comment section… .................................................................... 12

DATA TYPES.............................................................................................................................................. 13
NUMERIC ...................................................................................................................................................................... 13
GEO SPATIAL............................................................................................................................................................... 13

FUNCTIONS ............................................................................................................................................... 14
TEXT.............................................................................................................................................................................. 14

SYSTEM INFO ............................................................................................................................................ 14
PRIVILEGES ............................................................................................................................................... 16
User Privileges ............................................................................................................................................................. 16
Admin Privileges.......................................................................................................................................................... 16
GRANT .......................................................................................................................................................................... 16
PASSWORD.................................................................................................................................................................. 16

COMMANDS ............................................................................................................................................... 17
AS.................................................................................................................................................................................. 17
CREATE ........................................................................................................................................................................ 17
COUNT .......................................................................................................................................................................... 17
DELETE......................................................................................................................................................................... 17
DISTINCT ...................................................................................................................................................................... 17
INSERT.......................................................................................................................................................................... 17
LIKE............................................................................................................................................................................... 17
ORDER BY .................................................................................................................................................................... 17
PASSWORD.................................................................................................................................................................. 17
SELECT......................................................................................................................................................................... 17
UPDATE ........................................................................................................................................................................ 17
WHERE ......................................................................................................................................................................... 17
ALTER ........................................................................................................................................................................... 17
ADD COLUMN .............................................................................................................................................................. 17
CHANGE COLUMN....................................................................................................................................................... 17
DROPCOLUMN............................................................................................................................................................. 17
ADD INDEX ................................................................................................................................................................... 17
DROP INDEX................................................................................................................................................................. 17
RENAME AS ................................................................................................................................................................. 17

ENGINES .................................................................................................................................................... 17
MyISAM......................................................................................................................................................................... 17
Memory (heap) ............................................................................................................................................................. 17
Merge ............................................................................................................................................................................ 17
InnoDB .......................................................................................................................................................................... 17
Archive.......................................................................................................................................................................... 17
Federated...................................................................................................................................................................... 17
NDBCLUSTER (NDB) ................................................................................................................................................... 17
CSV ............................................................................................................................................................................... 17
Blackhole ...................................................................................................................................................................... 17
Example ........................................................................................................................................................................ 17

MySql Reference – by Jan Zumwalt

Pg - 2 of 43

NeatInfo.com – February, 06, 2012

USER OPERATIONS .................................................................................................................................. 19
DATABASE OPERATIONS ........................................................................................................................ 21
TABLE OPERATIONS ................................................................................................................................ 22
COLUMN OPERATIONS ............................................................................................................................ 23
ROW OPERATIONS (SELECT) .................................................................................................................. 24
Where conditions......................................................................................................................................................... 24

COUNT, SUM, MAX .................................................................................................................................... 26
PHP & REGEX SEARCHS .......................................................................................................................... 27
JOIN – UNION – GROUP ............................................................................................................................ 28
Test db setup: .............................................................................................................................................................. 28
JOIN(default), INNER JOIN, and WHERE ................................................................................................................... 29
LEFT JOIN..................................................................................................................................................................... 30
RIGHT JOIN .................................................................................................................................................................. 31
FULL JOIN, FULL OUTER JOIN, CROSS JOIN .......................................................................................................... 32
UNION ........................................................................................................................................................................... 33
GROUP.......................................................................................................................................................................... 34

DATE & TIME FUNCTIONS ........................................................................................................................ 35
Date Datatypes ........................................................................................................................................................... 36
DATE_FORMAT() ........................................................................................................................................................ 36
Extraction Functions ................................................................................................................................................... 38
Getting the Current Date and Time ......................................................................................................................... 38
Changing Date Values ............................................................................................................................................... 39

USING PHP STATEMENTS ........................................................................................................................ 40
MYSQL FUNCTIONS .................................................................................................................................. 41

MySql Reference – by Jan Zumwalt

Pg - 3 of 43

NeatInfo.com – February, 06, 2012

PHP COMMUNICATIONS WITH MYSQL
What is PHP's mysqli Extension? The mysqli extension, or as it is sometimes known, the
MySQL improved extension, was developed to take advantage of new features found in MySQL
systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and
later.
The mysqli extension has a number of benefits, the key enhancements over the mysql
extension being: Object-oriented interface, Support for Prepared Statements, Support for
Multiple Statements, Support for Transactions, Enhanced debugging capabilities, Embedded
server support.
<?php // new way using object resource
$db = mysqli_connect("host","user","passwd");
mysqli_select_db($db, "test");
$query = "SELECT * FROM t1";
$result = mysqli_query($db, $query) or die(mysql_error());// $result is a object
$rows
= mysqli_fetch_array($result); // $rows is an array of records
$num_rows = mysqli_num_rows($result); // number of rows from a result set
echo $num_rows;
?>
<?php // the old way
mysql_connect("host","user","passwd");
mysql_select_db("test");
$query = "SELECT * FROM t1";
$result = mysql_query($query) or die(mysql_error()); // $result is a object
$rows
= mysql_fetch_assoc($result); // $rows is an array of records
$num_rows = mysql_num_rows($result); // number of rows from a result set
echo $num_rows;
?>

Comments
# comment to end of line
-- comment to end of line
/* This is a multi-line
comment */

To login OS shell use -h only if needed.
mysql/path/mysql -h hostname -u root -p

MySql Reference – by Jan Zumwalt

Pg - 4 of 43

NeatInfo.com – February, 06, 2012

SELECT & WHERE SYNTAX
Syntax
t1, t2 are TABLE names
c1, c2 are COLUMN or FIELD names
$result is a resource OBJECT
$rows is an array of records
$row is a single RECORD
$db is a database object
Simple statement
SELECT * FROM t1
Advanced statement
SELECT <*|c1,c2,...> ALIASE <label1,lable2,...>
FROM <t1,t2,...>
WHERE exp AND|OR exp AND|OR exp...
ORDER BY <c1,c2,...>

MySQL WHERE
The WHERE exp is used to MODIFY, DELETE, SELECT, or UPDATE SQL query operations.

WHERE exp AND|OR exp AND|OR exp...
where exp can be one of the following:
column
column
column
column
column
column
column
column
column
column
column
column
column
column
column

= value
equal
!= value
not equal
> value
more than
>= value
more than or equal to
< value
less than
<= value
less than or equal to
BETWEEN value1 AND value2
IN (value1,value2,...)
NOT IN (value1,value2,...)
NOT LIKE value
LIKE stri_ng
the underscore _ matches 1 char
LIKE %string
string ends with, % is 0 or more char
LIKE string%
string starts with, % is 0 or more char
LIKE %string%
string contains, % is 0 or more char
^string
string starts with, ^ represents start of string

MySql Reference – by Jan Zumwalt

Pg - 5 of 43

NeatInfo.com – February, 06, 2012

MYSQL SIMPLE EXAMPLES
STEP 1: CONNECT

The following examples assume a db connection has been made using the following code…
echo "<h1>Test 1</h1>";
$host = "localhost"; $user = "root"; $pwd = "";
$db = mysqli_connect($host, $user, $pwd);
mysqli_select_db($db, "test");
STEP 2: QUERY

Next, you must query the database for a result set. The result set is unusable until a fetch is used (next
step)…
$query = "SELECT * FROM t1 WHERE fname = ‘Mickey’"; // single row (1d array)
$result = mysqli_query($db, $query) or die(mysqli_error($db));
or multiple rows would be like this
$query = "SELECT * FROM t1";
// multiple rows (2d array)
$result = mysqli_query($db, $query) or die(mysqli_error($db));
STEP 3: FETCH RESULTS

There are four ways to fetch the results...
$row
$rows
$rows
$rows

=
=
=
=

mysqli_fetch_row($result))
mysqli_fetch_array($result))
mysqli_fetch_assoc($result))
mysqli_fetch_object($result))

//
//
//
//

indexed single row
(both) index and/or assoc array
assoc array
result array as object

STEP 4: EXTRACT INFORMATION FROM FETCH

There are two ways to extract the information. If the information was fetched as an index than array numbers
will be used to access field values. If the information was fetched as an assoc, than field names may be used.
echo “First name is “ . $row[2];
// indexed row: “Mickey”
echo “First name is “ . $rows[2];
// indexed array: “Mickey” or current row name
echo “First name is “ . $rows[‘fname’]; // assoc array: “Mickey” or current row name
SPECIFIC ROW DATA
When an assoc or indexed array is being accessed, each row of information is incremented by each FETCH call. A chosen row of
information may be accessed by using

SELECT * FROM t1 LIMIT 2, 1
-- use query to return 1 row after 2nd row
or
mysqli_data_seek($result, 2); -- use seek before fetch to return desired row
$row = mysqli_fetch_row($result);
ROW COUNT

$result =
$row_cnt =
or
$result =
$row_cnt =
or
$result =
$row_cnt =
or
$result =
$row_count

mysql_query(“SELECT * FROM t1”);
$result->num_rows;
mysql_query(“SELECT * FROM t1”);
mysql_num_rows($result);
mysql_query(“SELECT * FROM t1”);
mysqli_num_rows($result);
mysql_query(“SELECT count(*) as num_rows FROM t1”);
= mysql_fetch_array($result);

MySql Reference – by Jan Zumwalt

Pg - 6 of 43

NeatInfo.com – February, 06, 2012

or
$result

= mysql_query(“SELECT count(distinct c1) as distinct_items FROM t1”);

CLOSE CONNECTION

mysql_close($db);

MySql Reference – by Jan Zumwalt

Pg - 7 of 43

NeatInfo.com – February, 06, 2012

SIMPLE DATABASE EXAMPLE
<?php

/*
+-------------------------------------------------------------------+
|
|
|
File:
php_mysql_test.php
Version:
2012-02-04
|
|
|
|
Purpose:
shows syntax for most common mysql operations
|
|
using improved mysql"i"
|
|
|
+-------------------------------------------------------------------+
//

<----------

maintenance support

*/

---------->

$debug = 'false';
if(file_exists($_SERVER['DOCUMENT_ROOT'] . '/include/debug.php')) {
include($_SERVER['DOCUMENT_ROOT'] . '/include/debug.php');
}
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', 'on');

//

<----------

start html

// detect all errors
// display all errors

---------->

if(file_exists($_SERVER['DOCUMENT_ROOT'] . '/css/admin.css')) {
echo '<html><head>';
include($_SERVER['DOCUMENT_ROOT'] . '/css/admin.css');
echo '</head><body>';
}else{
echo '<html>
<head>
<style>
body {
font-family: courier;
/* background-color: #500; /* dark red */
background-color: #002;
/* midnight blue */
color: #ddd;
margin-left:
100;
margin-right: 100;
margin-top:
50;
margin-bottom: 50;
}
</style>
</head>
<body>';
}

//

<----------

db connect

---------->

$db = mysqli_connect("localhost","root","") or die(mysqli_error());

//

<----------

delete db

---------->

$sql_delete_db = 'DROP DATABASE IF EXISTS `test_db` ';
$result = mysqli_query($db, $sql_delete_db) or die(mysqli_error());

//

<----------

create db

---------->

$sql_create_db = 'CREATE DATABASE IF NOT EXISTS `test_db`';
mysqli_query($db, $sql_create_db) or die(mysqli_error());

//

<----------

connect to db

---------->

$result = mysqli_select_db($db,"test_db") or die(mysqli_error());

//

<----------

delete table

---------->

$sql_delete_db = 'DROP TABLE IF EXISTS `people` ';
$result = mysqli_query($db, $sql_delete_db) or die(mysqli_error());

//

<----------

create table

---------->

$sql_maketbl = "CREATE TABLE `test_db`.`people`(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY
KEY(id),
name
VARCHAR(25) COMMENT 'first name',
age
INT(3)
COMMENT 'yrs',
updated
TIMESTAMP
COMMENT 'last update',

MySql Reference – by Jan Zumwalt

Pg - 8 of 43

NeatInfo.com – February, 06, 2012

update_by VARCHAR(25) NOT NULL DEFAULT 'unknown' COMMENT 'user name',
note
VARCHAR(255) DEFAULT 'na' )";
$result = mysqli_query($db, $sql_maketbl) or die(mysqli_error());

//

<----------

add record

---------->

$sql_add_data = "INSERT INTO `test_db`.`people`
(`id`, `name`, `age`, `updated`, `update_by`, `note`)
VALUES
(NULL, 'Mickey Mouse', '50', CURRENT_TIMESTAMP, 'janz'
, 'na'),
(NULL, 'Mini Mouse' , '50', CURRENT_TIMESTAMP, 'janz'
, 'na'),
(NULL, 'Daffy'
, '51', CURRENT_TIMESTAMP, 'unknown', 'na')";
$result = mysqli_query($db, $sql_add_data) or die(mysqli_error());

//

<----------

count result rows

---------->

$sql_update = "SELECT * FROM `test_db`.`people`
WHERE name LIKE 'M%' ";
$result = mysqli_query($db, $sql_update) or die(mysqli_error());
$cnt = mysqli_num_rows($result);
echo "There are $cnt records with names starting with 'M'.";

//

<----------

update record

---------->

$sql_update = "UPDATE `test_db`.`people`
SET `age` = '36'
WHERE `name` LIKE '%Mini%' ";
$result = mysqli_query($db, $sql_update) or die(mysqli_error());

//

<----------

delete record

---------->

$sql_update = "DELETE FROM `test_db`.`people`
WHERE `name` LIKE '%Daffy%' ";
$result = mysqli_query($db, $sql_update) or die(mysqli_error());

//

<----------

show table data

---------->

$sql_update = "SELECT * FROM `test_db`.`people` ";
$result = mysqli_query($db, $sql_update) or die(mysqli_error());
echo "<pre>";
while($row = mysqli_fetch_assoc($result)) {
echo print_r($row);
}
echo "</pre>";

//

<----------

table structure (html)

--------->

$database = "test_db";
$result = mysqli_select_db($db,$database) or die(mysqli_error());
$loop = mysqli_query($db, "SHOW TABLES FROM $database") or die('SHOW TABLES: cannot select tables');

// $tborder = '#bb4400'; $strip1 = '#994400'; $strip2 = '#aa6622'; // orange table theme
$tborder = '#334499'; $strip1 = '#3388bb'; $strip2 = '#2266aa'; // blue table theme
while($table = mysqli_fetch_array( $loop)) {
echo "<br>
<table cellpadding='2' cellspacing='2' border='0' width='75%'>
<tr bgcolor=$tborder>
<td colspan='6' align='center'><b><font size='+3' color='#FFFFFF'>" . $table[0] . "
</font><br/></b>table structure</td>
</tr>
<tr bgcolor=$tborder>
<td ALIGN='center'>Field</td>
<td ALIGN='center'>Type : Length</td>
<td ALIGN='center'>Key</td>
<td ALIGN='center'>Index</td>
<td ALIGN='center'>Default</td>
<td ALIGN='center'>Extra</td>
</tr>";
$i = 0; //row counter
$row = mysqli_query($db, "SHOW columns FROM " . $table[0])
or die ('cannot select table fields');
while ($col = mysqli_fetch_array($row)) {
echo "<tr";
if ($i % 2 == 0) { echo " bgcolor=$strip1 "; }else{ echo " bgcolor=$strip2 "; }
echo ">
<td bgcolor=$tborder>" . $col[0] . "</td>
<td>" . $col[1] . "</td>

MySql Reference – by Jan Zumwalt

Pg - 9 of 43

NeatInfo.com – February, 06, 2012

<td>"
<td>"
<td>"
<td>"
</tr>";

.
.
.
.

$col[2]
$col[3]
$col[4]
$col[5]

.
.
.
.

"</td>
"</td>
"</td>
"</td>

$i++;
} //end row loop
echo "</table><br/>";
} //end table loop
echo "<br/>";

//

<----------

table structure (text)

--------->

$sql_list_tables = "DESCRIBE `people` ";
$result = mysqli_query($db, $sql_list_tables) or die(mysqli_error());
while($row = mysqli_fetch_assoc($result)) {
$str = implode(",",$row);
echo $str . "<br>";
}
echo "<br>";

//

<----------

show table syntax

--------->

$sql_list_tables = "SHOW CREATE TABLE `people` ";
$result = mysqli_query($db, $sql_list_tables) or die(mysqli_error());
echo "<br/><pre>";
while($row = mysqli_fetch_assoc($result)) {
echo print_r($row) . "<br>";
}
echo "</pre><br/>";

//

<----------

close mysql connection

--------->

mysqli_close($db);
echo 'Mysql connection closed, end of program.';
echo "
</BODY>
</HTML>";
?>

MySql Reference – by Jan Zumwalt

Pg - 10 of 43

NeatInfo.com – February, 06, 2012

Output
There are 2 records with names starting with 'M'.
Array
(
[id] => 1
[name] => Mickey Mouse
[age] => 50
[updated] => 2012-02-06 22:09:52
[update_by] => janz
[note] => na
)
1Array
(
[id] => 2
[name] => Mini Mouse
[age] => 36
[updated] => 2012-02-06 22:09:52
[update_by] => janz
[note] => na
)
1
people
table structure
Field

Type :
Length

Key Index

Default

id

int(11)

NO

name

varchar(25)

YES

age

int(3)

YES

updated

timestamp

NO

CURRENT_TIMESTAMP

NO

unknown

update_by varchar(25)
note

PRI

varchar(255) YES

Extra
auto_increment

on update
CURRENT_TIMESTAMP

na

id,int(11),NO,PRI,,auto_increment
name,varchar(25),YES,,,
age,int(3),YES,,,
updated,timestamp,NO,,CURRENT_TIMESTAMP,on update CURRENT_TIMESTAMP
update_by,varchar(25),NO,,unknown,
note,varchar(255),YES,,na,
Array
(
[Table] => people
[Create Table] => CREATE TABLE `people` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(25) DEFAULT NULL COMMENT 'first name',
`age` int(3) DEFAULT NULL COMMENT 'yrs',
`updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
COMMENT 'last update',
`update_by` varchar(25) NOT NULL DEFAULT 'unknown' COMMENT 'user name',
`note` varchar(255) DEFAULT 'na',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
)
1
Mysql connection closed, end of program.

MySql Reference – by Jan Zumwalt

Pg - 11 of 43

NeatInfo.com – February, 06, 2012

MYSQL DEBUG EXAMPLES
EXAMPLE1: Hide mysql array values in html comment section…

'<!--TEST';print_r(implode(',', $my_array));echo '-->';

MySql Reference – by Jan Zumwalt

Pg - 12 of 43

NeatInfo.com – February, 06, 2012

DATA TYPES
NUMERIC

COMMON DATA TYPES
Stores up to 255 characters. You have to specify the maximum amount of characters that you will be putting
here when you create your column.

CHAR
LONG VARCHAR
BIT
FLOAT
INT
SMALLINT
DATE
DATETIME
More...

Up to 2 GB of characters.
Holds a value of 0 or 1 (Boolean). It is primarily used for yes/no and true/false issues.
This type holds decimal numbers. It is primarily used for mathematical purposes.
This stores whole numbers between -2,147,483,648 and 2,147,483,648.
As above except you are limited to numbers between -32,768 and 32,768.
This will store a date.
This will store a date and time (timestamp). It is primarily used to Time Stamp entries or updates to a row or
table.
There are at least 5 date, 15 text, 8 numeric, 20 accounting data types.

GEO SPATIAL
GEOMETRY
GEOMETRYCOLLECTION
LINESTRING
MULTILINESTRING
MULTIPOINT
MULTIPOLYGON
POINT
POLYGON

COMMON DATA TYPES
GEOMETRY can store geometry values of any type
.
particular geometry type.

particular geometry type.
particular geometry type.

OPERATOR
=
<>
<
<=
>
>=
IS NULL
NOT NULL
OR
AND
%
_
[ ]

Comparison
Compares the data to your criteria to see if it is equal
Compares the data to your criteria to see if it is not equal
Compares the data to your criteria to see if the data is less than your criteria
Compares the data to your criteria to see if the data is less than or equal to your criteria
Compares the data to your criteria to see if the data is greater than your criteria
Compares the data to your criteria to see if the data is greater than or equal to your criteria
Checks the data to make sure that there is no data in the column
Requires a value in the column, often used for key fields.
Connects multiple condition tests
Connects multiple condition tests
Wildcard, match all characters before
Wildcard
Wildcard

OPERATOR
ASC
DESC

Sorting
Sort by scending order A to Z
Sort by descending order Z to A

MySql Reference – by Jan Zumwalt

Pg - 13 of 43

NeatInfo.com – February, 06, 2012

FUNCTIONS
NUMERIC
ABS()
ACOS()
ASIN()
ATAN()

SYNTAX

EXAMPLE

SELECT ABS(-2);
return: 2
Returns the arccosine of numeric expression. Returns SELECT ACOS(1);
return: 0.000000
NULL if the value is not in the range -1 to 1.
SELECT ASIN(1);
Returns the arcsine of numeric expression. Returns
return: 1.5707963267949
NULL if value is not in the range -1 to 1
SELECT ATAN(1);
Returns the arctangent of numeric expression.
return: 0.78539816339745
Returns the absolute value of numeric expression.

ATAN2()

Returns the arctangent of the two variables passed to SELECT ATAN2(3,6);
it.
return: 0.46364760900081

BIT_AND()

Returns the bitwise AND all the bits in expression.

BIT_COUNT()

Returns the string representation of the binary value
passed to it.

BIT_OR()

Returns the bitwise OR of all the bits in the passed
expression.

CEIL()
CEILING()

Returns the smallest integer value that is not less than SELECT CEILING(3.46);
passed numeric expression
return: 4

CONV(N,from_base,
to_base)

Convert numeric expression from one base to
another.

COS()

Returns the cosine of passed numeric expression.
SELECT COS(90);
The numeric expression should be expressed in
return: -0.44807361612917
radians.
Returns the cotangent of passed numeric expression. SELECT COT(1);
return: 0.64209261593433

COT()

SELECT
MAKER, BIT_AND(PRICE) BITS
FROM CARS GROUP BY MAKER
return:
MAKER
BITS
-------------CHRYSLER
512
FORD
12488
HONDA
2144
SELECT
BIT_COUNT(2) AS TWO,
BIT_COUNT(4) AS FOUR,
BIT_COUNT(7) AS SEVEN
return:
| TWO | FOUR | SEVEN |
|
1 |
1 |
3 |
SELECT
MAKER, BIT_OR(PRICE) BITS
FROM CARS GROUP BY MAKER
return:
MAKER
BITS
-------------CHRYSLER 62293
FORD
16127
HONDA
32766

SELECT CONV(5,16,2);
return: 101

DEGREES()

Returns numeric expression converted from radians to SELECT DEGREES(PI());
degrees.
return: 180.000000

EXP()

Returns the base of the natural logarithm (e) raised to SELECT EXP(3);
the power of passed numeric expression.
return: 20.085537

FLOOR()

Returns the largest integer value that is not greater
than passed numeric expression.

FORMAT()

Returns a numeric expression rounded to a number of SELECT FORMAT(423423234.65434453,2);
decimal places.
return: 423,423,234.65

GREATEST()

Returns the largest value of the input expressions.

SELECT GREATEST(33,99,34,55,67);
return: 99

INTERVAL()

Takes multiple expressions exp1, exp2 and exp3 so
on.. and returns 0 if exp1 is less than exp2, returns 1 if
exp1 is less than exp3 and so on.
Returns the minimum-valued input when given two or
more.

SELECT INTERVAL(6,1,2,3,4,5,6,7,8,9,10);
return: 6
SELECT LEAST(3,5,1,8,33,99,34,55,67,43);
return: 1

LOG()

Returns the natural logarithm of the passed numeric
expression.

SELECT LOG(45);
return: 3.806662

LOG(B,X)

returns the logarithm of X for an arbitrary base B

SELECT LOG(2,65536);

LEAST()

MySql Reference – by Jan Zumwalt

Pg - 14 of 43

SELECT FLOOR(7.55);
return: 7

NeatInfo.com – February, 06, 2012

return: 16.000000
LOG10()

Returns the base-10 logarithm of the passed numeric SELECT LOG10(100);
expression.
return: 2.000000

MOD()

Returns the remainder of one expression by diving by SELECT MOD(29,3);
another expression.
return: 2

OCT()

Returns the string representation of the octal value of SELECT OCT(12);
the passed numeric expression. Returns NULL if
return: 14
passed value is NULL.
SELECT PI();
Returns the value of pi
return: 3.141593

PI()
POW()
POWER()

Returns the value of one expression raised to the
power of another expression

SELECT POWER(3,3);
return: 27

RADIANS()

Returns the value of passed expression converted
from degrees to radians.

SELECT RADIANS(90);
return: 1.570796

ROUND()

Returns numeric expression rounded to an integer.
Can be used to round an expression to a number of
decimal points
Returns numeric expression rounded to an integer.
Can be used to round an expression to a number of
decimal points
This function returns the sign of X (negative, zero, or
positive) as .1, 0, or 1.

SELECT ROUND(5.693893);
return: 6

SELECT SIGN(-4.65);
return: -1

SIN()

Returns the sine of numeric expression given in
radians.

SELECT SIN(90);
return: 0.893997

SQRT()

Returns the non-negative square root of numeric
expression.

SELECT SQRT(49);
return: 7

STD()
STDDEV()

Returns the standard deviation of the numeric
expression.

SELECT STD(PRICE) STD_DEVIATION FROM
CARS;
return:
STD_DEVIATION
+------------+
7650.2146

TAN()

Returns the tangent of numeric expression expressed SELECT TAN(45);
in radians.
return: 1.619775

TRUNCATE()

Returns numeric exp1 truncated to exp2 decimal
places. If exp2 is 0, then the result will have no
decimal point.

ROUND()

SIGN()

ROUND(5.693893,2)
return: 5.69

SELECT TRUNCATE(7.536432,2);
return: 7.53

TEXT

GROUP
(Aggregate)
MAX( )

This returns a selected column's highest value

MIN( )

This returns a selected column's lowest value

SUM( )

This returns the sum of a selected column

AVG( )

This returns the average value of a selected column

COUNT( )

This counts the number of rows in a selected column

CONCAT

CONCAT(col1,col2)

SYSTEM INFO
SHOW DATABASES;

Shows all databases

SHOW ENGINES;

This returns a selected column's lowest value

SHOW CHARACTER SET;

This returns the sum of a selected column

SHOW CREATE DATABASE <db>;

This returns the average value of a selected column

SHOW DATABASES;

This counts the number of rows in a selected column

MySql Reference – by Jan Zumwalt

Pg - 15 of 43

NeatInfo.com – February, 06, 2012

PRIVILEGES
User Privileges
ALTER

Modify the structure or properties of a table

ALTER ROUTINE

Modify a stored routine

CREATE

Create new tables or databases

CREATE ROUTINE

Create routine

CREATE TEMPORARY TABLE
CREATE VIEW
DELETE

Create temporary table(s)
Create a view
Delete existing data from table (row or col)

DROP

Delete existing table

EXECUTE

Run a stored routine

INDEX

Create and delete indexes in tables

INSERT

Create new row (record) in existing table

LOCK TABLES
REPLICATION CLIENT
REPLICATION SLAVE
SELECT
SHOW DATABASE
SHOW VIEW
UPDATE

Global privilege. Prevent access during maintenance or update.
Show replication status
Perform replication
Read row(s) (records)
Global privilege. View available databases
Use a view
Alter existing row or col data

Admin Privileges
CREATE USER
DROP USER
FILE
GRANT OPTION
PROCESS

Create new users
Delete a user
Import data from file(s) Global privilege that gives query rights.
Create new users with same permission as current user
View current processes that are running

RELOAD

Global privilege. Reload grant tables, enact rules.

REVOKE

Remove specific privileges of a user

SHUTDOWN
SUPER

OPERATOR

Stop SQL server
Terminate running processes

ADMIN PRIVILEGES

EXAMPLE

GRANT <privlege>, <privlege>
ON <table name>
TO ‘user’;

GRANT SELECT, INSERT, UPDATE
ON contacts
TO ‘john_doe’;
GRANT SELECT, INSERT, UPDATE
ON sales.*
TO ‘mary_doe’;

GRANT

PASSWORD
(your password)
PASSWORD
(user password)

SET PASSWORD = PASSWORD(‘newpassword’)

SET PASSWORD FOR ‘user’ =
PASSWORD(‘newpassword’)

MySql Reference – by Jan Zumwalt

GRANT SELECT, INSERT, UPDATE
ON sales.*
TO ‘mary_doe’
IDENTIFIED BY ‘password’;
WHERE first_name='John' AND
(last_name='Lennon' OR
last_name='Mellencamp');
SELECT fname, email
FROM contacts
WHERE contact_id = 6;

Pg - 16 of 43

NeatInfo.com – February, 06, 2012

COMMANDS
Command
AS
(aliase)

CREATE

COUNT

Syntax

Example

CONCAT(col1,col2) AS alias FROM tbl
SELECT col AS col_aliase FROM tbl AS tbl_aliase
CREATE TABLE <table name> (
<unique_id> INT IDENTITY (start, increment) NOT
NULL,
<field2> <type> (<length>) NULL ,
<field2> <type> (<length>) NULL
);
SELECT COUNT(*) AS <col>
FROM <table>;
SELECT company_col,
COUNT(*) AS co_sales_col
FROM sales_tbl
GROUP BY company_col;

SELECT company_col,
COUNT(*) AS co_sales_total_col
FROM sales_tbl
GROUP BY company_col
ORDER BY company_col ASC;

DELETE
DISTINCT
(No duplicates)
INSERT
new info or
copy table

LIKE
(case insensitive
or wildcards)

SELECT MAX(amount_col)
FROM receipts_tbl
WHERE date_col = '01/01/2002'
SELECT AVG(sales_col)
FROM receipts_table
WHERE date_col = '01/01/2002';
SELECT COUNT(msg_col) AS count_col
FROM msg_tbl
WHERE category = 'SQL';
SELECT COUNT(DISTINCT job_type_col)
FROM jobs_tbl;
DELETE FROM <table>
WHERE <condition>;
SELECT DISTINCT <col>
FROM <table>;
INSERT INTO <table> (<col>, <col>, <col>)
VALUES (‘value’, ‘value’, 'value');
INSERT INTO <table> (<col>, <col>, <col>)
SELECT col1, col2, col3 FROM other_tbl;
INSERT INTO <table> (<col>, <col>, <col>)
VALUES (‘value’, ‘value’, 'value');
SELECT <col>, <col> # or SELECT *
FROM <table>
WHERE <condition>
<col> LIKE <condition>

SELECT *
FROM <table>
ORDER BY <col>; ascending is default
ASC = ascending
or
DESC = descend
ORDER BY <col> <direction>;
ORDER BY

PASSWORD
(your password)
PASSWORD
(user password)

SELECT

UPDATE

SET PASSWORD = PASSWORD(‘newpassword’)

SET PASSWORD FOR ‘user’ =
PASSWORD(‘newpassword’)
SELECT *
# select all
or
SELECT <col>, <col> # select specific col(s)
FROM <table>
WHERE <condition>;
UPDATE <table>

MySql Reference – by Jan Zumwalt

CONCAT(lname,’,’,fnamecol2)
AS fullname FROM contacts;
CREATE TABLE contacts (
contact_id INT IDENTITY (1, 1) NOT NULL,
first_name CHAR (30) NULL ,
last_name CHAR (50) NULL ,
email
VARCHAR (75) NULL
);
SELECT COUNT(*) AS sales_total
FROM sales;
company_name
---------------Amazon.com
Sears
CompUSA
Dollar General Stores

company_sales
------------------------478
222
512
6

company_name
---------------Amazon.com
CompUSA
Dollar General Stores
Sears

company_sales
------------------------478
512
6
222

MAXimum sale from column "sale_total" in table "sales_log"
for sales on 1/1/2002
Get the average sale for a given day.
An example of using COUNT to get the number of
messages posted to a discussion group:
This will give you the total number of unique job types in
your job group.
DELETE FROM contacts
WHERE contact_id = 3;
SELECT DISTINCT job_type_col
FROM jobs_tbl;
Gives unique list of job types in your job group.
INSERT INTO contacts (fname, lname, email)
VALUES ('John', NULL, 'mail@hi.com');
INSERT INTO contacts (fname, lname, email)
VALUES ('John', NULL, 'mail@hi.com');
WHERE last_name LIKE '%camp%'
or combinations
WHERE first_name='John' AND
last_name LIKE '%camp'
SELECT *
FROM contacts
ORDER BY lname;
or
direction specific
ORDER BY lname DESC;
or
multiple columns
ORDER BY last_name, first_name ASC;
WHERE first_name='John' AND
(last_name='Lennon' OR
last_name='Mellencamp');
SELECT fname, email
FROM contacts
WHERE contact_id = 6;
SELECT fname, email
FROM contacts
WHERE contact_id = 6;
UPDATE contacts

Pg - 17 of 43

NeatInfo.com – February, 06, 2012

WHERE
(case sensitive)

ALTER
ADD COLUMN
CHANGE
COLUMN
DROPCOLUMN
ADD INDEX

SET <col> = 'value'
WHERE <condition>;
WHERE <condition>;
or
WHERE <col> LIKE <condition>;

SET email = 'brain@hi.com'
WHERE contact_id = 6;
WHERE first_name='John' AND
(last_name='Lennon' OR
last_name='Mellencamp');

SYNTAX

EXAMPLE

ALTER TABLE tbl
ADD COLUMN new_col col_type;
ALTER TABLE tbl
CHANGE COLUMN old_col new_name new_type;
ALTER TABLE tbl
DROP COLUMN col;
ALTER TABLE tbl
ADD INDEX index_name col;

DROP INDEX

ALTER TABLE tbl
DROP INDEX index_name;

RENAME AS

ALTER TABLE tbl
RENAME AS new_tbl_name;

ALTER TABLE contacs
ADD COLUMN ssn_num INT;
INSERT INTO contacts (fname, lname, email)
VALUES ('John', NULL, 'mail@hi.com');
DELETE FROM contacts
WHERE contact_id = 3;
UPDATE contacts
SET email = 'brain@hi.com'
WHERE contact_id = 6;
SELECT fname, email
FROM contacts
WHERE contact_id = 6;
WHERE first_name='John' AND
(last_name='Lennon' OR
last_name='Mellencamp');

ENGINES
Name
MyISAM
Memory
(heap)
Merge
InnoDB
Archive
Federated
NDBCLUSTER
(NDB)
CSV

Blackhole
Example

DESCRIPTION
The default MySQL storage engine and the one that is used the most in Web, data warehousing, and other
application environments. MyISAM is supported in all MySQL configurations, and is the default storage engine
unless you have configured MySQL to use a different one by default.
Stores all data in RAM for extremely fast access in environments that require quick lookups of reference and other
like data.
Allows a MySQL DBA or developer to logically group a series of identical MyISAM tables and reference them as
one object. Good for VLDB environments such as data warehousing.
Used for transaction processing applications, and sports a number of features including ACID transaction support
and foreign keys.
Provides the perfect solution for storing and retrieving large amounts of seldom-referenced historical, archived, or
security audit information.
Offers the ability to link separate MySQL servers to create one logical database from many physical servers. Very
good for distributed or data mart environments.
This clustered database engine is particularly suited for applications that require the highest possible degree of
uptime and availability.
The CSV storage engine stores data in text files using comma-separated values format. You can use the CSV
engine to easily exchange data between other software and applications that can import and export in CSV
format.
The Blackhole storage engine accepts but does not store data. Retrievals always return an empty set. The
functionality can be used in distributed database design where data is automatically replicated, but not stored
locally.
Tables can be created, but no data can be stored or retrieved. This engine serves as an example in MySQL
source code. It illustrates how to begin writing new storage engines but does nothing.

MySql Reference – by Jan Zumwalt

Pg - 18 of 43

NeatInfo.com – February, 06, 2012

USER OPERATIONS
Update database permissions / privileges.
flush privileges;
Creating a new user. Login as root. Switch to the MySQL db. Make the user. Update privs.
# mysql -u root -p
use mysql;
INSERT INTO user (Host,User,Password)
VALUES('%','username',PASSWORD('password'));
flush privileges;
Change a users password FROM unix shell.
mysql/path/mysqladmin -u username -h hostname.blah.org -p password 'newpassword'
Change a users password FROM MySQL prompt. Login as root. Set the password. Update privs.
# mysql -u root -p
SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');
flush privileges;
Recover a MySQL root password.
Stop the MySQL server process.
Start again with no grant TABLEs.
Login to MySQL as root.
Set new password.
Exit MySQL and restart MySQL server.
# /etc/init.d/mysql stop
# mysqld_safe --skip-grant-TABLEs &
# mysql -u root
use mysql;
update user set password=PASSWORD("newrootpassword") WHERE User='root';
flush privileges;
quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start
Set a root password if there is no root password.
# mysqladmin -u root password newpassword
Update a root password.
# mysqladmin -u root -p oldpassword newpassword
Allow the user "bob" to connect to the server FROM localhost using the password "passwd".
Login as root. Switch to the MySQL db. Give privileges. Update privileges.
# mysql -u root -p
use mysql;
grant usage on *.* to bob@localhost identified by 'passwd';
flush privileges;
Give user privileges for a db.
Login as root.
Switch to the MySQL db.

MySql Reference – by Jan Zumwalt

Pg - 19 of 43

NeatInfo.com – February, 06, 2012

Grant privileges. Update privs.
# mysql -u root -p
use mysql;
INSERT INTO db
(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,DROP_p
riv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');
flush privileges;
or
grant all privileges on databasename.* to username@localhost;
flush privileges;

MySql Reference – by Jan Zumwalt

Pg - 20 of 43

NeatInfo.com – February, 06, 2012

DATABASE OPERATIONS
Create a database.
mysql_query("CREATE DATABASE dbName",$db);
To delete a db.
mysql_query("DROP DATABASE dbName",$db);
List all databases on the sql server.
mysql_query("SHOW DATABASES",$db);;
Switch to or select a database.
USE dbName;
BACKUP all databases. Backup file is sql commands to recreate all db's.
mysql/path/mysqldump -u username –p password --opt > /path/all_db.sql
or
mysql/path/mysqldump -u username –p password –all-databases > /path/all_db.sql
BACKUP one database.
mysql/path/mysqldump -u username –p password --databases dbName >
/path/dbName.sql
Restore database (or database TABLE) FROM backup.
mysql/path/mysql -u username –p password databasename < /tmp/databasename.sql
Batch or script.
mysql/path/mysql -u username –p password < /path/script.txt
# use -t for nice TABLE layout and -vvv for command echoing.
mysql/path/mysql > /path/script.txt
Load CSV COMMA DELIMITED file into a TABLE.
LOAD DATA LOCAL INFILE '/path/filename.csv'
replace INTO TABLE t1
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n' (field1,field2,field3);
Load TAB DELIMITED file into a TABLE.
LOAD DATA LOCAL INFILE '/path/filename.tab' into table dbNAME.t1 fields
terminated by 't' enclosed by '"' lines terminated by 'rn';
# rn mean new lines. r means carriage return. n means new line.

MySql Reference – by Jan Zumwalt

Pg - 21 of 43

NeatInfo.com – February, 06, 2012

TABLE OPERATIONS
Show all TABLES in current db.
SHOW TABLES;
Show database column format.
DESCRIBE t1;
DELETE a TABLE.
DROP TABLE t1;
TRUNCATE a TABLE. (deletes TABLE, then recreate with same fields, the reset the AUTO INCREMENT counter to '0')
DROP TABLE t1;
Clear and reset a table. Deletes, re-creates, set auto-inc to 0
truncate table t1;
SHOW all data in a TABLE.
SELECT * FROM t1;
UPDATE an existing row in TABLE.
UPDATE t1 SET c1 = 'something' WHERE c2 = 'somewhere';
Delete a row(s) FROM a TABLE.
DELETE FROM t1 WHERE c1 = 'whatever';
Rename TABLE.
ALTER TABLE IF EXISTS `my_orig_table` RENAME `my_new_name`;
Returns the COLUMNS and COLUMN information pertaining to the designated TABLE.
SHOW COLUMNS FROM t1;
Dump a TABLE FROM a database.
mysql/path/mysqldump -c -u username -ppassword databasename TABLEname >
/tmp/databasename.TABLEname.sql
Copy table structure
CREATE TABLE t1 SELECT * FROM t2
Create TABLE Example 1.
CREATE TABLE t1 (
id INT PRIMARY KEY,
c1 VARCHAR(35),
datestamp DATE,
timestamp time
); # end of table
Create TABLE Example 2.
create TABLE t1 (
id int(50) NOT NULL AUTO_INCREMENT PRIMARY KEY,
c1 varchar(35),
c2 varchar(50) DEFAULT 'hello')
; # end of table

MySql Reference – by Jan Zumwalt

Pg - 22 of 43

NeatInfo.com – February, 06, 2012

COLUMN OPERATIONS
Delete a COLUMN.
ALTER TABLE t1 DROP COLUMN c1;
Add a new COLUMN to TABLE.
ALTER TABLE t1 ADD COLUMN newName varchar(20);
Rename COLUMN name.
ALTER TABLE t1 change oldName newName varchar(50);
Make a UNIQUE COLUMN so you get no dupes.
ALTER TABLE t1 ADD UNIQUE c1;
Make a COLUMN bigger.
ALTER TABLE t1 MODIFY c1 VARCHAR(3);
Delete UNIQUE FROM TABLE.
ALTER TABLE t1 DROP INDEX c1;
Returns the COLUMNS and COLUMN information pertaining to the designated TABLE.
SHOW COLUMNS FROM t1;
Selecting column.
SELECT c1 FROM t1;
SELECT c1, c2 FROM t1 WHERE c2 = "smith" ORDER BY c2;
Sorting.
SELECT c1, c2 FROM t1 ORDER BY c2;
SELECT c1, c2 FROM t1 ORDER BY c2 DESC; # reverse

MySql Reference – by Jan Zumwalt

Pg - 23 of 43

NeatInfo.com – February, 06, 2012

ROW OPERATIONS (SELECT)
DELETE row.
DELETE from t1 where c1 = 'whatever';
UPDATE row.
UPDATE t1 SET c1=value, c2=value2,... WHERE c3=value
SHOW selected rows with the value "whatever".
SELECT * FROM t1 WHERE c1 = "whatever";
SHOW rows containing the name "Bob" AND the ph number '123-4567'.
SELECT * FROM t1 WHERE c1 = "Bob" AND c2 = '123-4567';
SHOW rows not containing "Bob" AND the ph number '123-4567', order ph_number.
SELECT * FROM t1 WHERE c1 != "Bob" AND c2 = '123-4567' order by c2;
SHOW all rows starting with the letters 'bob' AND the ph number '123-4567'.
SELECT * FROM t1 WHERE c1 LIKE "Bob%" AND c2 = '123-4567';
SHOW all rows starting with the letters 'bob' AND the ph number '123-4567' LIMIT to rows 1 through 5.
SELECT * FROM t1 WHERE c1 LIKE "Bob%" AND c2 = '123-4567' LIMIT 1,5;
Use regex to find rows.
Use "REGEXP BINARY" to force case-sensitivity.
This finds any record beginning with “a”.
SELECT * FROM t1 WHERE REC RLIKE "^a";
SELECT * FROM t1 WHERE REC RLIKE "text%";
SHOW UNIQUE rows.
SELECT DISTINCT c1 FROM t1;
SHOW rows sorted in an ascending (asc) or descending (desc).
SELECT c1, c2 FROM t1 ORDER BY c2 DESC;
INSERT one or more rows from one table to another table.
INSERT INTO t1(c1, c2) SELECT (b1, b2) from t2 where 1;

Where conditions
The WHERE exp is used to modify a DELETE, SELECT, or UPDATE SQL query.
Syntax
t1, t2 are TABLE names
c1, c2 are COLUMN or FIELD names
$result is a resource OBJECT
$rows is an array of records
$row is a single RECORD
$db is a database object
Simple statement

MySql Reference – by Jan Zumwalt

Pg - 24 of 43

NeatInfo.com – February, 06, 2012

SELECT * FROM t1
Advanced statement using WHERE
SELECT <*|c1,c2,...> ALIASE <label1,lable2,...>
FROM <t1,t2,...>
WHERE exp AND|OR exp AND|OR exp...
ORDER BY <c1,c2,...>
This list shows the format you can use when writing a WHERE exp (expression). The where exp can be one
of the following:
column
column
column
column
column
column
column
column
column
column
column
column
column
column
column

= value
equal
!= value
not equal
> value
more than
>= value
more than or equal to
< value
less than
<= value
less than or equal to
BETWEEN value1 AND value2
IN (value1,value2,...)
NOT IN (value1,value2,...)
NOT LIKE value
LIKE stri_ng
the underscore _ matches 1 char
LIKE %string
string ends with, % is 0 or more char
LIKE string%
string starts with, % is 0 or more char
LIKE %string%
string contains, % is 0 or more char
^string
string starts with, ^ represents start of string

MySql Reference – by Jan Zumwalt

Pg - 25 of 43

NeatInfo.com – February, 06, 2012

COUNT, SUM, MAX
Return number of rows.
$result = mysql_query("SELECT * FROM tablename");
$num_rows = mysql_num_rows($result);
or
$num_rows = mysqli_num_rows($result);

Distinct counts.
SELECT c1, COUNT(*) FROM t1 GROUP BY c1; # distinct count
or
SELECT count(distinct c1) as distinct_items FROM t1”);
Sum COLUMN.
SELECT SUM(c1) FROM t1;
MAXIMUM value.
SELECT MAX(c1) AS label FROM t1;

MySql Reference – by Jan Zumwalt

Pg - 26 of 43

NeatInfo.com – February, 06, 2012

PHP & REGEX SEARCHS
Regular PHP expressions use patterns to test whether the input users submit when using online forms are in
the correct format. This table shows characters you can use in patterns.

Character

Meaning

Example

Match

Not a Match

^

Beginning of line

^c

cat

my cat

$

End of line

c$

tic

stick

.

Any single character

..

me, go

a

?

Preceding item is optional

mea?n

mean, men

moan

()

Groups literal characters

m(ea)n

mean

men,mn

[]

Any character in set

abc[1-3]

abc1,abc2

abc4

[! ]

Any character not in set

m[!ea]n

min, mon

men, man

+

One or more

door[1-3]+

door111, door131 door, door55

*

Zero or more

door[1-3]*

door, door311

door4, door445

{,}

Range of repetitions

a{2,5}

aa,aaaaa

a, xx3

\

Escapes character

m\*n

m*n

men, mean

(||)

Alternate strings

(Tom|Tommy) Tom, Tommy

MySql Reference – by Jan Zumwalt

Pg - 27 of 43

Thomas, To

NeatInfo.com – February, 06, 2012

JOIN – UNION – GROUP
JOIN or INNER JOIN: Return rows when there is at least one match in both tables
LEFT JOIN:

Return all rows from the left table, even if there are no matches in the right table

RIGHT JOIN:

Return all rows from the right table, even if there are no matches in the left table. A
right join is identical to a left join if the position of the tables is swapped.

FULL JOIN:

Merges the tables (including unmatched rows) as if a LEFT and RIGHT JOIN where
used at the same time.

UNION:

Adds returned rows of one table to the returned rows of another table.

GROUP:

Adds returned rows of one table to the returned rows of another table.

Test db setup:

To demonstrate joins consider a database named “test” with two tables with a
customer ID in common, when with credit limits, and the other with phone numbers.
The each have customer id rows that are unique and two rows that are in common.
We delibertly have different column names for the ID to show that the key field does
not have to be named the same.
Table “t1”
cust_id
credit
1
50
2
75
3
100
4
150

Table “t2”
cust_num
phone
3
123-4567
4
234-5678
5
345-6789
6
456-7890

They can be created by using the following sql statements:
DROP DATABASE IF EXISTS `test` ;
CREATE DATABASE `test` ;
CREATE TABLE `test`.`t1` (
`cust_id` INT( 4 ) NOT NULL,
`credit` DECIMAL( 6,2 ) NOT NULL ,
PRIMARY KEY ( `cust_id` )
) ENGINE = InnoDB;
INSERT INTO `test`.`t1` (`cust_id` ,`credit` )
VALUES
('1', '50')
, ('2', '75')
, ('3', '100')
, ('4', '150')
;
CREATE TABLE `test`.`t2` (
`cust_num` INT( 4 ) NOT NULL ,
`phone` VARCHAR( 15 ) NOT NULL ,
PRIMARY KEY ( `cust_num` )
) ENGINE = InnoDB;
INSERT INTO `test`.`t2` (`cust_num` ,`phone` )
VALUES
('3', '123-4567')
, ('4', '234-5678')
, ('5', '345-6789')
, ('6', '456-7890')
;

MySql Reference – by Jan Zumwalt

Pg - 28 of 43

NeatInfo.com – February, 06, 2012

JOIN(default), INNER JOIN, and WHERE: Return rows when there is a match in both tables. Note, that a
WHERE is often used as a shortcut to this type of JOIN. An
INNER JOIN is the same as a JOIN.
SELECT *
FROM t1, t2
WHERE t1.cust_id = t2.cust_num
or
SELECT *
FROM t1
JOIN t2
WHERE t1.cust_id = t2.cust_num
or
SELECT *
FROM t1
INNER JOIN t2 ON t1.cust_id = t2.cust_num

Table “t1”
cust_id
credit
1
50
2
75
3
100
4
150

Table “t2”
cust_num
phone
3
123-4567
4
234-5678
5
345-6789
6
456-7890

Result:
cust_id

credit

cust_num

phone

3

100.00

3

123-4567

4

150.00

4

234-5678

MySql Reference – by Jan Zumwalt

Pg - 29 of 43

NeatInfo.com – February, 06, 2012

LEFT JOIN: Return all rows from the left table, even when no match is found in the right table.
The word OUTER may be added after the word LEFT or RIGHT - it's provided for ODBC compatibility and
doesn't add any extra capabilities.
SELECT *
FROM t1
LEFT JOIN t2 ON t1.cust_id = t2.cust_num
Table “t1”
cust_id
credit
1
50
2
75
3
100
4
150

Table “t2”
cust_num
phone
3
123-4567
4
234-5678
5
345-6789
6
456-7890

Result:
cust_id

credit

cust_num

phone

1

50.00

NULL

NULL

2

75.00

NULL

NULL

3

100.00

3

123-4567

4

150.00

4

234-5678

MySql Reference – by Jan Zumwalt

Pg - 30 of 43

NeatInfo.com – February, 06, 2012

RIGHT JOIN: Return all rows from the right table, even when no match is found in the left table. Note that a
RIGHT JOIN can be duplicated by swapping table positions and using a LEFT JOIN.
The word OUTER may be added after the word LEFT or RIGHT - it's provided for ODBC compatibility and
doesn't add any extra capabilities.
SELECT *
FROM t1
RIGHT JOIN t2 ON t1.cust_id = t2.cust_num
or
SELECT *
FROM t2
LEFT JOIN t1 ON t1.cust_id = t2.cust_num
Table “t1”
cust_id
credit
1
50
2
75
3
100
4
150

Table “t2”
cust_num
phone
3
123-4567
4
234-5678
5
345-6789
6
456-7890

Result:
cust_id

credit

cust_num

phone

3

100.00

3

123-4567

4

150.00

4

234-5678

NULL

NULL

5

345-6789

NULL

NULL

6

456-7890

MySql Reference – by Jan Zumwalt

Pg - 31 of 43

NeatInfo.com – February, 06, 2012

FULL JOIN, FULL OUTER JOIN, CROSS JOIN:
This JOIN combines both tables (as if a LEFT and RIGHT JOIN where
used together). MySql does not provide a FULL JOIN because it is rarely
needed. You can create one by using a union statement.
A “STRAIGHT” JOIN is a full JOIN except that the JOIN occurs in the
order given in the command line. Otherwise, the database engine is free
to display things in the order in which is most convenient.

SELECT t1.*, t2.* FROM t1,t2 WHERE t1.cust_id = t2.cust_num
or
SELECT * FROM t1
LEFT JOIN t2
ON t1.cust_id = t2.cust_num
UNION
SELECT * FROM t1
RIGHT JOIN t2
ON t1.cust_id = t2.cust_num

Table “t1”
cust_id
credit
1
50
2
75
3
100
4
150

Table “t2”
cust_num
phone
3
123-4567
4
234-5678
5
345-6789
6
456-7890

Result:
cust_id

credit

cust_num

phone

1

50.00

NULL

NULL

2

75.00

NULL

NULL

3

100.00

3

123-4567

4

150.00

4

234-5678

NULL

NULL

5

345-6789

NULL

NULL

6

456-7890

To do this with three tables…
-- three tables t1, t2, t3:
SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
LEFT JOIN t3 ON t2.id = t3.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
LEFT JOIN t3 ON t2.id = t3.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
RIGHT JOIN t3 ON t2.id = t3.id

MySql Reference – by Jan Zumwalt

Pg - 32 of 43

NeatInfo.com – February, 06, 2012

UNION: returns a table with column positions merged to the first table’s field names.
SELECT * FROM t1
UNION
SELECT * FROM t2
Table “t1”
cust_id
credit
1
50
2
75
3
100
4
150

Table “t2”
cust_num
phone
3
123-4567
4
234-5678
5
345-6789
6
456-7890

Result:
cust_id

credit

1

50.00

2

75.00

3

100.00

4

150.00

3

123-4567

4

234-5678

5

345-6789

6

456-7890

MySql Reference – by Jan Zumwalt

Pg - 33 of 43

NeatInfo.com – February, 06, 2012

GROUP: returns a table with unique row data.
Suppose we would like to know what types of credit we offer our customers.
SELECT credit FROM t1 GROUP BY credit
Table “t1”
cust_id
credit
1
75
2
75
3
100
4
100
5
150
Result:
credit
75.00
100.00
150.00

MySql Reference – by Jan Zumwalt

Pg - 34 of 43

NeatInfo.com – February, 06, 2012

DATE & TIME FUNCTIONS
SELECT
SELECT
SELECT
SELECT
SELECT

NOW(); // current data & time i.e 2003-03-31 00:32:21
CURRENT_DATE(); // current date i.e 2003-03-31
YEAR('2003-03-31');
YEAR('2003-03-31')+5;
// five years from the date
YEAR(CURRENT_DATE)-YEAR('1971-01-01'); // 32, checks only year part
// may be wrong in some cases

SELECT YEAR(CURRENT_DATE()) - YEAR('1971-12-31')
- (RIGHT(CURRENT_DATE(),5)<'12-31') AS age; // 31,

a better way, always right

SELECT DAYNAME('2000-01-01'); // Saturday
SELECT DAYOFWEEK('2000-01-01'); // 7
SELECT DAYOFYEAR('2000-12-31'); // 366
SELECT
SELECT
SELECT
SELECT
SELECT

MONTH(NOW()) AS m;
DAYOFMONTH(NOW()) AS d;
HOUR(NOW()) AS h;
MINUTE(NOW()) AS m;
SECOND(NOW()) AS s;

// search through your dates for a particular age or age range:
SELECT * FROM table
WHERE DATE_FORMAT(NOW(), '%Y') –
DATE_FORMAT(birthdate, '%Y') –
DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(birthdate, '00-%m-%d')) ) = age
// difference between two dates (date1 - date2)
select datediff(date1, date2) from t1
TO_DAYS() - calculates the day number corresponding to a specific date i.e zero
SELECT TO_DAYS('2003-04-06');
SELECT TO_DAYS(NOW());

// 731676, use

("YYYY-MM-DD") or numeric (YYYYMMDD)

FROM_DAYS() - calculates the date corresponding to a day number
Some examples below use “periodType”
--------------------------------------------SECONDS SECOND
MINUTES MINUTE
HOURS HOUR
DAYS DAY
MONTHS MONTH
YEARS YEAR
"MINUTES:SECONDS" MINUTE_SECOND
"HOURS:MINUTES" HOUR_MINUTE
"DAYS HOURS" DAY_HOUR
"YEARS-MONTHS" YEAR_MONTH
"HOURS:MINUTES:SECONDS" HOUR_SECOND
"DAYS HOURS:MINUTES" DAY_MINUTE
"DAYS HOURS:MINUTES:SECONDS" DAY_SECOND

// adds a specified interval to a date and returns a new date
DATE_ADD(startDate, INTERVAL period periodType)
DATE_ADD('2003-04-15', INTERVAL 1 YEAR) // 2004-04-15
// add 7 days, 1 hour, 55 minutes and 10 seconds to December 25 2000:
SELECT DATE_ADD('2000-12-25 12:00:00', INTERVAL "7 01:55:10" DAY_SECOND);

// subtracts a specified interval from a date and returns a new date
DATE_SUB(startDate, INTERVAL period periodType)
PERIOD_DIFF() - calculates the difference (in months) between two dates
SELECT CURRENT_DATE, (YEAR(CURRENT_DATE)-YEAR(date_col)) AS time_diff t1;
// MONTH(some_date) extracts the month value and DAYOFMONTH() extracts day.

MySql Reference – by Jan Zumwalt

Pg - 35 of 43

NeatInfo.com – February, 06, 2012

PERIOD_ADD() - adds an interval (in months) to a date and returns a new date

Date Datatypes
There are 5 MySQL date datatypes these are:
Datatype

Format

Info

DATETIME

YYYY-MM-DD HH:MM:SS

This stores both date and time.

DATE

YYYY-MM-DD

This only stores the date

TIMESTAMP(length)

Varies

See Below

TIME

HH:MM:SS

This stores only the time

YEAR

YYYY

Stores only the year

The timestamp datatype is somewhat different as it stores the time that a row was last changed. The format
also varies according to the length. For example to store the same information as DATETIME, you would specify
a length of 14 whereas to store the DATE you would specify a length of 8.
Timestamp Definition

Format

TIMESTAMP(2)

YY

TIMESTAMP(4)

YYYY

TIMESTAMP(6)

YYMMDD

TIMESTAMP(8)

YYYYMMDD

TIMESTAMP(10)

YYMMDDHHMM

TIMESTAMP(12)

YYMMDDHHMMSS

TIMESTAMP(14)

YYYYMMDDHHMMSS

In the 'cds' table we have used the DATE for the 'bought' field.
mysql> SELECT cds.title, cds.bought
-> FROM cds;
+------------------------------+------------+
| title
| bought
|
+------------------------------+------------+
| A Funk Odyssey
| 2001-10-10 |
| Now 49
| 2001-10-15 |
| Eurovision Song contest 2001 | 2000-09-08 |
| Abbas Greatest Hits
| 2000-11-05 |
| Space Cowboy
| 2001-10-10 |
| Sign of the times
| 1987-11-07 |
| The White Album
| 1994-07-20 |
| The Hits
| 1993-10-07 |
| westlife
| 2000-06-09 |
+------------------------------+------------+

9 rows in set (0.02 sec)

So to begin with let's look at how we can manipulate these dates using MySQL's date functions.

DATE_FORMAT()
This function allows the developer to format the date anyway that they wish by specifying a sequence of format
strings. A string is composed of the percentage symbol '%' followed by a letter that signifies how you wish to
display part of the date. These are some of the more common strings to use:

MySql Reference – by Jan Zumwalt

Pg - 36 of 43

NeatInfo.com – February, 06, 2012

String

Displays

Example

%d

The numeric day of the month

01....10....17....24 etc

%D

The day of the month with a suffix

1st, 2nd, 3rd.... etc

%m

The numeric month

01....04....08....11 etc

%M

The Month name

January....April....August etc

%b

The Abbreviated Month Name

Jan....Apr....Aug....Nov etc

%y

Two digit year

98, 99, 00, 01, 02, 03 etc

%Y

Four digit year

1998, 2000, 2002, 2003 etc

%W

Weekday name

Monday.... Wednesday....Friday etc

%a

Abbreviated Weekday name

Mon....Wed....Fri etc

%H

Hour (24 hour clock)

07....11....16....23 etc

%h

Hour (12 hour clock)

07....11....04....11 etc

%p

AM or PM

AM....PM

%i

Minutes

01....16....36....49 etc

%s

Seconds

01....16....36....49 etc

There are more, but that should be enough for now. There are a couple of things to note. Upper and Lowercase
letters in the string make a difference and also that when arranging these strings into a sequence you can
intersperse 'normal' characters. For example:
The sequence '%d/%m/%y', with forward slashes separating the strings, would be displayed as 01/06/03.
The next stage is to use the function DATE_FORMAT() to convert a stored time to a format we want.
Syntax:

DATE_FORMAT(date, sequence)
Thus to change the format of the cds.bought field to DD-MM-YYYY we specify the field as the date and the
sequence as '%d-%m-%Y'.

DATE_FORMAT(cds.bought, '%d-%m-%Y')
This function is then incorporated into our SQL statement in place of the exiting cds.bought field.

mysql> SELECT cds.title, DATE_FORMAT(cds.bought, '%d-%m-%Y') FROM cds;
+------------------------------+-------------------------------------+
| title
| DATE_FORMAT(cds.bought, '%d-%m-%Y') |
+------------------------------+-------------------------------------+
| A Funk Odyssey
| 10-10-2001
|
| Now 49
| 15-10-2001
|
| Eurovision Song contest 2001 | 08-09-2000
|
| Abbas Greatest Hits
| 05-11-2000
|
| Space Cowboy
| 10-10-2001
|
| Sign of the times
| 07-11-1987
|
| The White Album
| 20-07-1994
|
| The Hits
| 07-10-1993
|
| westlife
| 09-06-2000
|
+------------------------------+-------------------------------------+
9 rows in set (0.00 sec)
Dates can also be formatted in 'plain english'.
mysql> SELECT cds.title, DATE_FORMAT(cds.bought, '%W the %D of %M %Y')
-> FROM cds;
+------------------------------+-----------------------------------------------+
| title
| DATE_FORMAT(cds.bought, '%W the %D of %M %Y') |
+------------------------------+-----------------------------------------------+
| A Funk Odyssey
| Wednesday the 10th of October 2001
|
| Now 49
| Monday the 15th of October 2001
|

MySql Reference – by Jan Zumwalt

Pg - 37 of 43

NeatInfo.com – February, 06, 2012

| Eurovision Song contest 2001 | Friday the 8th of September 2000
|
| Abbas Greatest Hits
| Sunday the 5th of November 2000
|
| Space Cowboy
| Wednesday the 10th of October 2001
|
| Sign of the times
| Saturday the 7th of November 1987
|
| The White Album
| Wednesday the 20th of July 1994
|
| The Hits
| Thursday the 7th of October 1993
|
| westlife
| Friday the 9th of June 2000
|
+------------------------------+-----------------------------------------------+
9 rows in set (0.01 sec)
Note: DATE_FORMAT() only works with datatypes that include the date. This means DATE, DATETIME and
TIMESTAMP. There is a similar function called TIME_FORMAT() that works with TIME as well as DATETIME and
TIMESTAMP.

Extraction Functions
As well as using DATE_FORMAT() there are other functions that allow you to extract specific information about a
date (year, month, day etc). These include:
Function

Displays

Example

DAYOFMONTH(date)

The numeric day of the month

01....10....17....24 etc

DAYNAME(date)

The Name of the day

Monday.... Wednesday....Friday etc

MONTH(date)

The numeric month

01....04....08....11 etc

MONTHNAME(date)

The Month name

January....April....August etc

YEAR(date)

Four digit year

1998, 2000, 2002, 2003 etc

HOUR(time)

Hour (24 hour clock)

07....11....16....23 etc

MINUTE(time)

Minutes

01....16....36....49 etc

SECOND(time)

Seconds

01....16....36....49 etc

DAYOFYEAR(date)

Numeric day of the year

1.....366

To give an example of one of these you can use DAYNAME() to work out which day you were born on. To do this
you can specify the date directly to the function without referring to any tables or field. So for my birthday (20th
July 1973):

mysql> SELECT DAYNAME('1973-07-20');

+-----------------------+
| DAYNAME('1973-07-20') |
+-----------------------+
| Friday
|
+-----------------------+
1 row in set (0.00 sec)
Or you could even SELECT two or three date items.
mysql> SELECT DAYNAME('1973-07-20'), MONTHNAME('1973-07-20'), YEAR('1973-07-20');
+-----------------------+-------------------------+--------------------+
| DAYNAME('1973-07-20') | MONTHNAME('1973-07-20') | YEAR('1973-07-20') |
+-----------------------+-------------------------+--------------------+
| Friday
| July
|
1973 |
+-----------------------+-------------------------+--------------------+
1 row in set (0.02 sec)

Getting the Current Date and Time
There are three functions that you can use to get the current date and time. NOW() - which gets both date and
time, CURDATE() which works with only the date and CURTIME() for the time.

mysql> SELECT NOW(), CURTIME(), CURDATE();

MySql Reference – by Jan Zumwalt

Pg - 38 of 43

NeatInfo.com – February, 06, 2012

+---------------------+-----------+------------+
| NOW()
| CURTIME() | CURDATE() |
+---------------------+-----------+------------+
| 2003-06-02 19:44:51 | 19:44:51 | 2003-06-02 |
+---------------------+-----------+------------+
1 row in set (0.01 sec)

Changing Date Values
There are two functions that allow you to add and subtract time to a date. These are DATE_ADD() and
DATE_SUB().
Syntax:

DATE_ADD(date,INTERVAL expr type)
DATE_SUB(date,INTERVAL expr type)
The date - is a standard DATE or DATETIME value, next come the command INTERVAL followed by the time
period (expr) and finally what type period it is (Month, Day, Year etc). Therefore to work out the date 60 days
in the future:

mysql> SELECT DATE_ADD(CURDATE(), INTERVAL 60 DAY);
+--------------------------------------+
| DATE_ADD(CURDATE(), INTERVAL 60 DAY) |
+--------------------------------------+
| 2003-08-01
|
+--------------------------------------+
1 row in set (0.00 sec)

Or 6 months in the past:
mysql> SELECT DATE_SUB(CURDATE(), INTERVAL 6 MONTH);
+---------------------------------------+
| DATE_SUB(CURDATE(), INTERVAL 6 MONTH) |
+---------------------------------------+
| 2002-12-02
|
+---------------------------------------+
1 row in set (0.00 sec)

We can also format this result as well using DATE_FORMAT() and using an alias to
tidy up the title:

mysql> SELECT
-> DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 6 MONTH), '%W the %D of %M %Y')
-> AS 'Six Months Ago';
+---------------------------------+
| Six Months Ago
|
+---------------------------------+
| Monday the 2nd of December 2002 |
+---------------------------------+
1 row in set (0.01 sec)

MySql Reference – by Jan Zumwalt

Pg - 39 of 43

NeatInfo.com – February, 06, 2012

USING PHP STATEMENTS
Here is a list of the most common PHP statements that are used with MySql programs:
Common single statements
array ( "key" => "value", ... );
die
("message");
echo “string and or $var”;
echo “string and or “ . $var;
header("Location: URL");
number_format(number,decimals);
session_start();
session_destroy();
unset();
extract($array);
for
for(startingval; endingval;incremnt) {
code block...
}
foreach
foreach($array as $key => $value) {
code block...
}
function
function fname(value,value,...) {
code block...
}
if, ifelse, else
if (condition) {
code block...
}elseif (condition) {
code block...
}else{
code block...
}
while
while (condition) {
code block...
}
switch
switch var {
case value1
statements;
break;
case value2
statements;
break;
...
}
do
MySql Reference – by Jan Zumwalt

Pg - 40 of 43

NeatInfo.com – February, 06, 2012

do {
code block...
}
while (condition);

MYSQL FUNCTIONS
mysql_affected_rows ..............
mysql_client_encoding ............
mysql_close ..........................
mysql_connect ......................
mysql_create_db ...................
mysql_data_seek ...................
mysql_db_name ....................
mysql_db_query ....................
mysql_drop_db .....................
mysql_errno .........................
mysql_error ..........................
mysql_escape_string ..............
mysql_fetch_array .................
mysql_fetch_assoc .................
mysql_fetch_field ..................
mysql_fetch_lengths ..............
mysql_fetch_object ................
mysql_fetch_row ...................
mysql_field_flags ...................
mysql_field_len .....................
mysql_field_name ..................
mysql_field_seek ...................
mysql_field_table ...................
mysql_field_type ...................
mysql_free_result ..................
mysql_get_client_info .............
mysql_get_host_info ..............
mysql_get_proto_info .............
mysql_get_server_info ...........
mysql_info ............................
mysql_insert_id .....................
mysql_list_dbs ......................
mysql_list_fields ....................
mysql_list_processes ..............
mysql_list_tables ...................
mysql_num_fields ..................
mysql_num_rows ...................
mysql_pconnect ....................
mysql_ping ...........................
mysql_query .........................
mysql_real_escape_string .......
mysql_result .........................
mysql_select_db ....................
mysql_set_charset .................
mysql_stat ...........................
mysql_tablename ..................
mysql_thread_id ....................
mysql_unbuffered_query .........

MySql Reference – by Jan Zumwalt

Get number of affected rows in previous MySQL operation
Returns the name of the character set
Close MySQL connection
Open a connection to a MySQL Server
Create a MySQL database
Move internal result pointer
Get result data
Send a MySQL query
Drop (delete) a MySQL database
Returns numerical value of previous MySQL error message
Returns text error message from previous MySQL operation
Escapes a string for use in a mysql_query
Fetch a result row as an associative array, a numeric array, or both
Fetch a result row as an associative array
Get column information from a result and return as an object
Get the length of each output in a result
Fetch a result row as an object
Get a result row as an enumerated array
Get the flags associated with the specified field in a result
Returns the length of the specified field
Get the name of the specified field in a result
Set result pointer to a specified field offset
Get name of the table the specified field is in
Get the type of the specified field in a result
Free result memory
Get MySQL client info
Get MySQL host info
Get MySQL protocol info
Get MySQL server info
Get information about the most recent query
Get the ID generated in the last query
List databases available on a MySQL server
List MySQL table fields
List MySQL processes
List tables in a MySQL database
Get number of fields in result
Get number of rows in result
Open a persistent connection to a MySQL server
Ping a server connection or reconnect if there is no connection
Send a MySQL query
Escapes special characters in a string for use in an SQL statement
Get result data
Select a MySQL database
Sets the client character set
Get current system status
Get table name of field
Return the current thread ID
Send SQL query to MySQL w/o fetching or buffering the result rows.

Pg - 41 of 43

NeatInfo.com – February, 06, 2012

MySql Reference – by Jan Zumwalt

Pg - 42 of 43

NeatInfo.com – February, 06, 2012

Notes: _______________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________

MySql Reference – by Jan Zumwalt

Pg - 43 of 43

NeatInfo.com – February, 06, 2012

Sign up to vote on this title
UsefulNot useful