Sei sulla pagina 1di 70

JANSONS INSTITUTE OF TECHNOLOGY

KARUMATHAMPATTI, COIMBATORE 641 659.


UNIT II

OPEN SOURCE DATABASE (MySQL)


INTRODUCTION
A database is a collection of data organized and classified according to some
criteria.
An electronic database helps to organize the information and provides the tools
necessary to access specific bit quickly and efficiently.
Database can used to organize small and large amount of information.
DBMS can substantially simplify the work.
A RDBMS creating relationships among the tables that makes up a database.
The RDBMS are powerful, flexible, feature-rich software systems.
MySQL: An Open Source, Enterprise-level, multi-threaded, relational database
management system that stores and retrieves data using the Structured Query
Language
Structured Query Language (SQL): A standardized query language for getting
information from a relational database.
Relational Database: A database that stores data in the form of relational tables as
opposed to flat files.
Database Management System (DBMS): A system that manages relational
databases; A collection of programs that enabling the storage, modification,
and extraction of information from a database.
MySQL is a high-performance, multi-threaded, multi-user RDBMS built around
a client-server architecture.
MySQL RDBMS consists of two components.
Server-side tools: Include MySQL databses server, which is responsible for
creating and managing databases,executing queries, returning query results
and maintaining security.
Client-side tools: Include a command-line MySQL client tools to manage user
permissions and utilities to import and export mysql databases.
History and Evolution
MySQL came into being in 1979, when Michael created a database system
names UNIREG for the swedish company TcX.
UNIREG didn't have SQL; one of those alternatives was mySQL.
The system completed and released to a small group in may 1996, was known
1

Prepared By, R.Sangeetha AP/CSE

as MySQL.
MySQL 3.11 was released few months later by solaris.
GPL community take care of the rest.
TcX spun off MySQL AB, today is the sole owner of the MySQL server source
code and trademark and is responsible for maintenance, marketing and further
development.
Features:
Three fundamental principles:
Performance
Reliability
Ease of use
Speed:
The time takes to execute a query and return the results to the caller.
Reliability:
MySQL's large user base assists in rapidly locating and resolving bugs and in
testing the software in a variety of environments.
Ease of use:
Large number of free online tutorials, a knowledgeable developer community and
fair number of books to make easy.
Multi user support:
MySQL is a full multiuser system multiple clients can access and use one or more
databases simultaneously.Powerful and flexible privilege system to protect access
to sensitive data.
Scalability:
MySQL can handle extermely large and complex databases without too much of a
performance drop.
Portability:
MySQL is available for both UNIX and non-UNIX operating systems include
Solaris, FreeBSD, OS/2, MacOs and Windows.
It runs on a range of architectures, including Intel x86, Alpha, SPARC, PowerPC,
and IA64.
Compliance with Existing Standards:
MySQL 4.0 supports most of the important features of the ANSI SQL-99 standard.
MySQL extends the ANSI standard with custom extensions, functions and data
types.
Internationalization: Used by millions in countries across the globe, so MySQL
supports number of important character stes with full unicode support.
Wide application support: MySQL exposes API to many programming
languages, making possible to write database-driven application language of user
choice.
2

Prepared By, R.Sangeetha AP/CSE

Enthusiastic Developer community: MySql is supported by an active developer


community. High volume, well-informed mailing lists and user groups assist in the
rapid resolution of questions and problems.
Open source code: MySQL software is freely available under the GPL. Users are
free to download and modify the source code.
Applications
MySQL is used in more than 4 million systems worldwide.
More than 25,000 copies of the database server downloaded every day.
MySQL has applications in business, education, science and engineering.
MySQL software today powers a variety of applications, including Internet
websites, e-commerce applications, search engines, embedded applications,
mission-critical software systems.
MySQL proven track record generates confidence in its reliability and
longevity.
MySQL Overview
MySQL is a tiered architecture, consisting of primary subsystems and
support components.
Primary Subsystems:
Five primary subsystems that work together to respond made to the MySQL
database server.
TheQuery Engine
The Storage Manager
The Buffer Manager
The Transaction Manager
The Recovery Manager
Query Engine
Contains three interrelated components:
The Syntax Parser: It decomposes the SQL commands it receives from
calling program into a form that can be understood by the MySQL engine.
The Query Optimizer: It checks to see which index should be used to retrive
the data as quickly and efficiently as possible.
The Execution Component: It interprets the execution plan and based on the
information it has received, makes requests of the other components to
retrieve the records.
The Storage manager
The storage manager interfaces with the operating system to write data to the
disk efficiently. The storage functions reside in a seperate subsystem, the
MySQL engine operates at a level of abstraction away from the operating
system.
3

Prepared By, R.Sangeetha AP/CSE

The storage manager writes to disk all of the data in the user tables, indexes
and logs as well as internal systems.
The Query Cache: If a query returns a given set of records, repeating the
same query should return the same set of records unless the underlying data
has somehow changed.
The MySQL engine uses an extremely efficient result set caching
mechanism, known as query cache.
The Buffer Manager
This subsystem handles all memory management issues between requests
for data by the query engine and storage manager.
MySQL makes aggressive use of memory to cache result sets that can be
returned as-is rather than making duplicate requests to the storage manager,
this cache is maintained in the buffer manager.
If any new data is needed, it's requested from the storage manager and
placed in the buffer before then being sent to the query engine.
The Transaction Manager
Transaction manager is to facilitate concurrency in data access.
This subsystem provides a locking facility to ensure the multiple
simultaneous users access the data in a consistent way, without damaging
the data.
Transaction control takes place via the lock manager subcomponent, which
places and release locks on various objects being used in transactions.
The Recovery Manager
The recovery manager's job is to keep copies of data for retrieval later, in
case of loss of data.
Only InnoDB and BDB table handlers provide recovery management.
MyISAM handler doesn't have transactional recovery procedures.
Support Components
In addition to five primary subsystems, the MySQL architecture contains the
following two support components.
The Process manager
Function Libraries
MySQL Engine
MySQL supports small, embedded kiosk-style applications as well as the
occasional five billion-record data warehouse.
Connectivity: MySQL is designed on the assumption that the vast majority
of its applications will be running on a TCP/IP network.
TCP/IP is not only highly secure but also common to unix, Windows and
OS/2.
4

Prepared By, R.Sangeetha AP/CSE

MySQL does allow maned-pipe connections, which were designed mainly


to support network connections in earlier non-TCP/IP networks, such as
LAN manager and NETBEUI.
SQL
The structured query language is an open standard that has been maintained
by ANSI since 1986.
The implementations such as SQL server's T-SQL and Oracle's SQL,
MySQL has its own variations of the SQL standard that add power beyond
what is available within the standard.
Compared to C++, Java and Perl, SQL at first glance seems easy to learn
and hard to obfuscate, which often makes new comers to SQL think that the
learning curve will be much shorter than it actually is.
Data Integrity
MySQL supports engine-level data integrity through the use of primary key
nad foreign key constraints.
Columns can be defined so that explicit NULL values cannot be entered into
them.
To prevent empty columns, MySQL supports the use of default values,
which, whne combined with NOT NULL properties.
Transactions
A transaction-safe database system must pass what is known as the ACID test
to qualify for compliance. An ACID -compliant database must support the
following characterstics:
Atomicity:All the SQL statements must be completed for the database to
maintain the state of data integrity;otherwise none of the statement will be
finalized and commited into disk.
Consistency: Every transaction leaves the system in a consistent stste,
regardless of whether the transaction completes successfully or fails
midway.
Isolation: Every transaction occurs in its own space, isolated from other
transactions that may be occuring in the system, and the results are visible
only once.
Durability: The changes from a committed transaction persist even if the
system crashes, comes into play when a transaction has completed and the
logs have been updated.
Note: For MySQL queries refer DBMS Manual
Datatypes
INT: A numeric type that can accept values in the range of -2147483648 to
5

Prepared By, R.Sangeetha AP/CSE

2147483646.
DECIMAL: A numeric type with support of floating point or decimal numbers.
DOUBLE: A numeric type for double-precisin floating-point numbers
DATE: A data field in the YYYY-MM-DD format.
TIME: A time field in the HH:MM:SS format
DATETIME: A combined date/time type in the YYYY-MM-DD HH:MM:SS
YEAR: A field specifically for year displays the range 1901 to 2155
TIMESTAMP: A timestamp type, in YYYYMMDDHHMMSS format
CHAR: A string type with maximum size of 255 characters
TEXT: A string type with a maximum size of 65,535 characters
BLOB: A binary type of variable data
ENUM: A string type that can accept one value from previous values
SET: A string type can accept zero or more from previous values.
Setting up Account
MySQL database you need to create an account to use for connecting to the
MySQL server running on a given host.
Use the GRANT statement to set up the MySQL user account
User names, as used by MySQL for authentication purposes.
MySQL user names can be up to 16 characters long.
Adding User Accounts
You can create MySQL accounts in two ways:
By using statements intended for creating accounts, such as CREATE USER
or GRANT
By manipulating the MySQL grant tables directly with statements such as
INSERT, UPDATE, or DELETE.
Account Management Statements
Create User
Drop User
Grant
Rename
Revoke
Set Password
Create User
Description:
The CREATE USER statement creates new MySQL accounts.
Syntax:
CREATE USER user [IDENTIFIED BY [PASSWORD] 'password']
Example:

Prepared By, R.Sangeetha AP/CSE

Drop User
Description:
The DROP USER statement removes one or more MySQL accounts and their
privileges.
Syntax:
DROP USER user [, user] ...
Example:

Privileges can be granted at several levels:


Global level
Global level privileges are applied to all databases on a given server. These type
of privileges are stored in the user table of mysql database. Ex ? GRANT ALL
ON *.* and REVOKE ALL ON *.*;
Database level
Database level privileges are applied to all objects in a given database. These
type of privileges are stored in the db and host tables of the mysql databases. Ex
? GRANT ALL ON database_ name.* and REVOKE ALL ON
database_name.*
7

Prepared By, R.Sangeetha AP/CSE

Table level
Table level privileges are applied to all columns on a given table. These type of
privileges are stored in the table_priv table of the mysql database. EX ?
GRANT ALL ON database_name.table_name and REVOKE ALL ON
database_name.table_name.
Column level
Column level privileges are applied to single column on a given table. These
type of privileges are stored in columns_priv table of mysql database. And at
the time of using REVOKE statement you have to specify the same column
name that were granted.
Routine level
Routine level privileges like CREATE ROUTINE, EXECUTE, ALTER
ROUTING and GRANT privileges are applied to stored routines. These type of
privileges can be granted at global and database level. Except CREATE
ROUTINE, rest of these privileges can be granted at routine level for particular
routines and they are stored in the procs_priv table of mysql database.
Privilege
ALL [PRIVILEGES]
ALTER
ALTER ROUTINE
CREATE
CREATE ROUTINE
CREATE TEMPORARY TABLES
CREATE USER
CREATE VIEW
DELETE
DROP
EXECUTE
FILE
INDEX
INSERT
LOCK TABLES
PROCESS
REFERENCES
RELOAD
REPLICATION CLIENT
REPLICATION SLAVE
8

Meaning
Sets all simple privileges except GRANT OPTION
Enables use of ALTER TABLE
Enables stored routines to be altered or dropped
Enables use of CREATE TABLE
Enables creation of stored routines
Enables use of CREATE TEMPORARY TABLE
Enables use of CREATE USER, DROP USER,
RENAME USER, and REVOKE ALL PRIVILEGES.
Enables use of CREATE VIEW
Enables use of DELETE
Enables use of DROP TABLE
Enables the user to run stored routines
Enables use of SELECT ... INTO OUTFILE and
LOAD DATA INFILE
Enables use of CREATE INDEX and DROP INDEX
Enables use of INSERT
Enables use of LOCK TABLES on tables for which
you have the SELECT privilege
Enables use of SHOW FULL PROCESSLIST
Not implemented
Enables use of FLUSH
Enables the user to ask where slave or master servers
are
Needed for replication slaves (to read binary log
events from the master)
Prepared By, R.Sangeetha AP/CSE

SELECT
SHOW DATABASES
SHOW VIEW
SHUTDOWN
SUPER
UPDATE
USAGE
GRANT OPTION

Enables use of SELECT


SHOW DATABASES shows all databases
Enables use of SHOW CREATE VIEW
Enables use of mysqladmin shutdown
Enables use of CHANGE MASTER, KILL, PURGE
MASTER LOGS, and SET GLOBAL statements,
themysqladmin debug command; allows you to
connect (once) even if max_connections is reached
Enables use of UPDATE
Synonym for ?no privileges?
Enables privileges to be granted

Grant
Description:
The GRANT statement enables system administrators to grant privileges to
MySQL user accounts.
Example:
GRANT SELECT,INSERT,UPDATE,DELETE ON my_db.* TO 'michael'@'localhost';

GRANT ALL ON my_db.* TO 'michael'@'localhost';


GRANT ALL ON *.* TO raj@localhost;
Rename User
Description:
The RENAME USER statement renames existing MySQL accounts.
Syntax:
RENAME USER old_user TO new_user [, old_user TO new_user] ...
Example:

Prepared By, R.Sangeetha AP/CSE

Revoke
Description:
The REVOKE statement enables system administrators to revoke privileges
from MySQL accounts.
Example:
mysql> REVOKE ALL PRIVILEGES, GRANT OPTION FROM chand;
Query OK, 0 rows affected (0.01 sec)
Set Password
Description:
The SET PASSWORD statement assigns a password to an existing MySQL
user.
Syntax:
SET PASSWORD [FOR user] = PASSWORD('some password')
Example:

Starting, terminating and writing your Own SQL programs


Starting MySQL
Login
10

Prepared By, R.Sangeetha AP/CSE

Stopping MySQL
Logout
Starting MySQL
The MySQL server can be started manually from the command line.
To start the mysqld server from the command line, you should start a
console window (or DOS window) and enter this command:
shell> "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqld"
The path to mysqld may vary depending on the install location of MySQL
on your system.
Login
To start the mysql program, type myql at your command-line prompt.
If mysql starts up correctly, you'll see a short message, followed by a mysql>
prompt that indicates the program is ready to accept queries.
To illustrate, here's what the welcome message looks like % mysql
Stopping MySQL
You can stop the MySQL server by executing this command:
shell> "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqladmin" u
root shutdown
Logout
To terminate a mysql session, issue a QUIT statement:
mysql> QUIT
You can also terminate the session by issuing an EXIT statement or (under
Unix) by typing Ctrl-D.
RECORD SELECTION TECHNIQUES
Sample Table

11

Prepared By, R.Sangeetha AP/CSE

Specifying Which Columns to Display

Combining Columns to Construct Composite Values


CONCAT( )
Column values may be combined to produce composite output values.
Using Column Aliases
AS keyword is used.
Give the column an alias, you can refer to it a lot more easily using the
name.

Specifying Which Rows to Select


A WHERE clause to the query that indicates to the server which rows to
return.

12

Prepared By, R.Sangeetha AP/CSE

Removing Duplicate Rows


DISTINCT
removes the duplicate records, producing a set of unique values.

Working with NULL Values


NULL are special.
You cannot use = NULL or != NULL
Use IS NULL or IS NOT NULL.
NULL ID indicates that the value is unknown

13

Prepared By, R.Sangeetha AP/CSE

Sorting Result Sets

Selecting Records from the Beginning or End of a Result Set


LIMIT clause that tells the server to return only part of a result set
Splitting a result set into sections so that you can process

14

Prepared By, R.Sangeetha AP/CSE

Pulling a Section from the Middle of a Result Set


LIMIT n tells the server to return the first n rows of a result set.
The arguments indicate how many rows to skip and how many to return.

Calculating LIMIT Values from Expressions


Arguments to LIMIT must be literal integers, not expressions.
Statements such as the following are illegal:
SELECT * FROM profile LIMIT 5+5;
Creating a Destination Table on the Fly from a Result Set
you can create it first with a CREATE TABLE statement, then copy rows.

Creating Temporary Tables


Table only for a short time, disappear automatically.
Use CREATE TEMPORARY TABLE.
Temporaray table gets deleted after we logout.

15

Prepared By, R.Sangeetha AP/CSE

During the next login

To count the number of rows

Moving Records Between Tables Safely


Moving records by copying them from one table to another.
Then deleting them from the original table.

16

Prepared By, R.Sangeetha AP/CSE

17

Prepared By, R.Sangeetha AP/CSE

STRINGS
Eight basic string types
It can be used to store string data ranging from simple one character strings to
large blocks of text or binary data. BLOB Binary Large Object
18

Prepared By, R.Sangeetha AP/CSE

CHAR type
Simplest type.
CHAR type is used for fixedlength
strings must be declared with size specifier in parenthesis.
The declaration CHAR(10) specifies a value 10 characters in length.
The value smaller than the specified length will be right padded with spaces.
The value larger than the specified length will be automatically truncated.
Example
mysql> CREATE TABLE data (alphabet CHAR(10));
mysql> INSERT INTO data VALUES ('abcdefghijklmno');
mysql> INSERT INTO data VALUES ('abc');
The output is
mysql> SELECT alphabet from data;
adcdefghij
abc
VARCHAR
A varient of the CHAR type is the VARCHAR type, which is useful for
variablelength strings;it, too, must be accompanied with a size specifier in
the range of 0 to 255.
CHAR type treat as the exact size for values, while VARCHAR type treats
this as a maximum size for values and uses only the number of bytes
actually needed to store the string.
The TEXT and BLOB types
For the strings greater than 255 characters in length MySQL provides both
BLOB and TEXT types, each with different subtypes depending on the size
19

Prepared By, R.Sangeetha AP/CSE

of the data to be stored.


These large sized types are useful for storing large blocks of text or binary
data such as image or audio files.
BLOB and TEXT types differ from each other in the manner in which they
are sorted and compared: Case sensitive for BLOB type values and case
insensitive for TEXT type values.
Size specifiers are not used with the various BLOB and TEXT types.
Values that are larger than the maximum size supported by the specified type
will be autmatically truncated.
Writing Strings That Include Quotes or Special Characters
To write a string in a SQL statement, surround it with quote characters:
mysql> SELECT 'hello, world';
+--------------+
| hello, world |
+--------------+
| hello, world |
+--------------+
But sometimes you need to write a string that includes a quote character, and
if you just put the quote into the string as is, a syntax error results:
mysql> SELECT 'I'm asleep';
ERROR 1064 at line 1: You have an error in your SQL syntax near
'asleep' at line 1
1. MySQL, unlike some SQL engines, allows you to quote strings with either
single quotes or double quotes, so you can enclose a string containing single
quotes within double quotes:
mysql> SELECT "I'm asleep";
+------------+
| I'm asleep |
+------------+
| I'm asleep |
+------------+
2. This works in reverse, too; a string containing double quotes can be
enclosed within single quotes:

20

Prepared By, R.Sangeetha AP/CSE

mysql> SELECT 'He said, "Boo!"';


+-----------------+
| He said, "Boo!" |
+-----------------+
| He said, "Boo!" |
+-----------------+
3. To include a quote character within a string either double the quote or precede it
with a backslash.
mysql> SELECT 'I''m asleep', 'I\'m wide awake';
+------------+----------------+
| I'm asleep | I'm wide awake |
+------------+----------------+
| I'm asleep | I'm wide awake |
+------------+----------------+
Pattern Matching with SQL Patterns
SQL pattern matching uses the LIKE and NOT LIKE operators rather than =
and != ,to perform matching against a pattern string and Strings that begin
with a particular substring:
mysql> SELECT name FROM metal WHERE name LIKE 'co%';
+--------+
| name |
+--------+
| copper |
+--------+
Strings that end with a particular substring:
mysql> SELECT name FROM metal WHERE name LIKE '%er';
+--------+
| name |
+--------+
| copper |
| silver |
+--------+
Strings that contain a particular substring anywhere:

21

Prepared By, R.Sangeetha AP/CSE

Strings that contain a substring at a specific position (the pattern matches


only if ppoccurs at the third position of the name column):

To reverse the sense of a pattern match, use NOT LIKE.


The following query finds strings that contain no i (character):

Pattern Matching with Regular Expressions


MySQL supports another type of pattern matching operation based on
regular expressions using the REGEXP operator (or NOT REGEXP to
reverse the sense of the match).
REGEXP matching uses a different set of pattern elements than %.
Pattern Matching Elements:
1.^ Beginning of string
2.$ End of string
3.. Any single character
4.[...] Any character listed between the square brackets
[^...] Any character not listed between the square brackets
5.* Zero or more instances of preceding element
6.+ One or more instances of preceding element
7.{n} n instances of preceding element
{m,n} m through n instances of preceding element
Strings that begin with a particular substring:

22

Prepared By, R.Sangeetha AP/CSE


Strings that contain a particular substring at any position:

Strings that contain a particular substring at a specific position:

1.MySQL's regular expression capabilities satisfies POSIX standards.


2. These match specific character sets are described in the following table.
[:alnum:] Alphabetic and numeric characters
[:alpha:] Alphabetic characters
[:blank:] Whitespace (space or tab characters)
[:cntrl:] Control characters
[:digit:] Digits
[:graph:] Graphic (non-blank) characters
[:lower:] Lowercase alphabetic characters
[:print:] Graphic or space characters
[:punct:] Punctuation characters
[:space:] Space, tab, newline, carriage return
[:upper:] Uppercase alphabetic characters
[:xdigit:] Hexadecimal digits (0-9, a-f, A-F)
The following expression matches values that contain any hexadecimal digit
character:
mysql> SELECT name, name REGEXP '[[:xdigit:]]' FROM metal;
For example, the following alternation matches strings that begin with a
vowel or end with er:
23

Prepared By, R.Sangeetha AP/CSE

mysql> SELECT name FROM metal WHERE name REGEXP '^[aeiou]|er$';


DECOMPOSING OR COMBINING STRINGS
1.Parts of strings can be extracted and displayed
2.For example, LEFT( ), MID( ), and 3.RIGHT() extract substrings from the left,
middle, or right part of a string:
mysql> SELECT name, LEFT(name,2), MID(name,3,1), RIGHT(name,3) FROM metal;

STRING COMPARISON FUNCTION


Like ----Simple Pattern Matching
Not Like ---Negation of simple pattern matching
Any Expression in a string comparison is case sensitive
Pattern matching using simple SQL regular expression returns 1(TRUE) or
0(FALSE).
If either expr or pattern is NULL, the result is NULL.
Like performs matching on a per character basis, thus it can produce results
different from = comparison operator.
Testing String equality or Relative Ordering
Strings are subject to the usual equality and inequality comparisons:
mysql> SELECT name, name = 'lead', name != 'lead' FROM metal;

You can also use relational operators such as <, <=, >=, and > to compare
strings in lexical order:
24

Prepared By, R.Sangeetha AP/CSE

mysql> SELECT name, name < 'lead', name > 'lead' FROM metal;

Dates and Times


Date and Time Formats
DATE values are handled as strings in CCYY-MM-DD format.
mysql> SELECT d FROM date_val;
+--------------+
|d
|
+--------------+
| 1864-02-28 |
| 1900-01-15 |
| 1987-03-05 |
| 1999-12-31 |
| 2000-06-04 |
+--------------+
TIME values are represented as strings in hh:mm:ss format.
mysql> SELECT t1, t2 FROM time_val;
+----------+------------+
| t1
| t2
|
+----------+------------+
| 15:00:00 | 15:00:00 |
| 05:01:30 | 02:30:20 |
| 12:30:20 | 17:30:45 |
+----------+------------+
DATETIME values are represented as combined date-and-time strings in CCYYMM-DD hh:mm:ss format.
mysql> SELECT dt FROM datetime_val;
+--------------------------+
25

Prepared By, R.Sangeetha AP/CSE

| dt
|
+--------------------------+
| 1970-01-01 00:00:00 |
| 1987-03-05 12:30:15 |
| 1999-12-31 09:00:00 |
| 2000-06-04 15:45:30 |
+--------------------------+
TIMESTAMP values include date and time parts, but are represented as strings in
CCYYMMDDhhmmss format.
mysql> SELECT ts FROM timestamp_val;
+---------------------+
| ts
|
+---------------------+
| 19700101000000 |
| 19870305123015 |
| 19991231090000 |
| 20000604154530 |
+----------------------+
How to Display Dates or Times
MySQL displays dates in ISO format if you have not specified the format.
To rewrite datevalues into other formats, use the DATE_FORMAT( ) function,
which takes two arguments: a DATE, DATETIME, or TIMESTAMP value
mysql> SELECT d, DATE_FORMAT(d,'%M%d, %Y') FROM date_val;
+----------------+-----------------------------------------+
|d
| DATE_FORMAT(d,'%M%d, %Y') |
+----------------+-----------------------------------------+
| 1864-02-28 | February 28, 1864
|
| 1900-01-15 | January 15, 1900
|
| 1987-03-05 | March 05, 1987
|
| 1999-12-31 | December 31, 1999
|
| 2000-06-04 | June 04, 2000
|
+------------+-------------------------------------------+

26

Prepared By, R.Sangeetha AP/CSE

TIME_FORMAT( ) is similar to DATE_FORMAT( ).


TIME_FORMAT( ) works with TIME, DATETIME, or TIMESTAMP
values.
mysql> SELECT dt,TIME_FORMAT(dt, '%r') AS '12-hour time',
TIME_FORMAT(dt, '%T') AS '24-hour time FROM datetime_val;
+--------------------------+-----------------+-----------------+
| dt
| 12-hour time | 24-hour time |
+--------------------------+-----------------+-----------------+
| 1970-01-01 00:00:00 | 12:00:00 AM | 00:00:00 |
| 1987-03-05 12:30:15 | 12:30:15 PM | 12:30:15 |
| 1999-12-31 09:00:00 | 09:00:00 AM | 09:00:00 |
| 2000-06-04 15:45:30 | 03:45:30 PM | 15:45:30 |
+---------------------------+----------------+-----------------+
Determining the Current Date or Time
Use the NOW( ), CURDATE( ), or CURTIME( ) functions.
CURRENT_TIMESTAMP and SYSDATE( ) are synonyms for NOW( ).
CURRENT_DATE and CURRENT_TIME are synonyms for CURDATE( )
and CURTIME( ).
mysql> SELECT NOW( ), CURDATE( ), CURTIME( );

27

Prepared By, R.Sangeetha AP/CSE

+--------------------------+-----------------+----------------+
| NOW( )
| CURDATE( ) | CURTIME( ) |
+--------------------------+-----------------+-----------------+
| 2002-07-15 10:59:30 | 2002-07-15 | 10:59:30
|
+--------------------------+------------------+----------------+
Decomposing Dates and Times Using Formatting Functions
Use a formatting function such as DATE_FORMAT( ) or TIME_FORMAT(
) with a format string.
mysql> SELECT dt,
-> DATE_FORMAT(dt,'%Y') AS year,
-> DATE_FORMAT(dt,'%d') AS day,
-> TIME_FORMAT(dt,'%H') AS hour,
-> TIME_FORMAT(dt,'%s') AS second
-> FROM datetime_val;

mysql> SELECT ts,DATE_FORMAT(ts,'%M%e, %Y') AS 'descriptive


date', TIME_FORMAT(ts,'%H:%i') AS 'hours/minutes' FROM
timestamp_val;

Decomposing Dates or Times Using Component-Extraction Functions

28

Prepared By, R.Sangeetha AP/CSE

mysql> SELECT d, DAYOFYEAR(d) FROM date_val;

DAYNAME( ) returns the complete day name.


DAYOFWEEK( ) returns values from 1 to 7, corresponding to Sunday
through Saturday.
WEEKDAY( ) returns values from 0 to 6, corresponding to Monday through
Sunday.
To obtain individual parts of temporal values we have to use the
EXTRACT( ) function.
mysql> SELECT d, DAYNAME(d), DAYOFWEEK(d), WEEKDAY(d) FROM
date_val;

29

Prepared By, R.Sangeetha AP/CSE

Combining a Date and a Time into a Date-and-Time Value


Combining a date value and a time value to produce a date-and-time value is
just a matter of concatenating them with a space in between.
mysql> SET @d = '2002-02-28';
mysql> SET @t = '13:10:05';
mysql> SELECT @d, @t, CONCAT(@d,' ',@t);

Converting Between Times and Seconds


TIME_TO_SEC( ) converts a TIME value to the equivalent number of
seconds.
SEC_TO_TIME( ) does the opposite.
mysql> SELECT t1,
-> TIME_TO_SEC(t1) AS 'TIME to seconds',
-> SEC_TO_TIME(TIME_TO_SEC(t1)) AS 'TIME to seconds to TIME'
-> FROM time_val;

Converting Between Dates and Days


DATE values can be converted to and from days with TO_DAYS( ) and
FROM_DAYS( ).
Date and time values can also be converted to days.
mysql> SELECT d,
-> TO_DAYS(d) AS 'DATE to days',
-> FROM_DAYS(TO_DAYS(d)) AS 'DATE to days to DATE'
-> FROM date_val;

30

Prepared By, R.Sangeetha AP/CSE

Conversion Between Date-and-Time Values and Seconds


UNIX_TIMESTAMP( ) converts date-and-time values to the number of
seconds elapsed since the beginning of 1970.
FROM_UNIXTIME( ) does the opposite.
mysql> SELECT dt,
-> UNIX_TIMESTAMP(dt) AS seconds,
-> FROM_UNIXTIME(UNIX_TIMESTAMP(dt)) AS timestamp
-> FROM datetime_val;

Adding a Temporal Interval to a Time


performing arithmetic operations on time
TIME_TO_SEC( ) and SEC_TO_TIME( )
mysql> SELECT t1,
-> SEC_TO_TIME(TIME_TO_SEC(t1) + 7200) AS 't1 plus 2 hours'
-> FROM time_val;

Calculating Intervals Between Times


mysql> SELECT t1, t2,
-> TIME_TO_SEC(t2) -TIME_TO_SEC(t1) AS 'interval in seconds',
-> SEC_TO_TIME(TIME_TO_SEC(t2) -TIME_TO_SEC(t1)) AS 'interval as TIME'
31

Prepared By, R.Sangeetha AP/CSE

-> FROM time_val;

Adding a Temporal Interval to a Date


DATE_ADD( ) and DATE_SUB( )
adding or subtracting intervals to or from dates.
DATE_ADD(d , INTERVAL valunit)
DATE_SUB(d , INTERVAL valunit)
mysql> SELECT CURDATE( ), DATE_ADD(CURDATE( ),INTERVAL 3 DAY);

Calculating Intervals Between Dates


To calculate an interval in days between date or date-and-time values,
convert them to days using TO_DAYS( ), then take the difference.
mysql> SELECT TO_DAYS('1884-01-01') -TO_DAYS('1883-06-05') AS days;

Finding the Day of the Week for a Date


To determine the name of the day of the week for a given date, use
DAYNAME( )
mysql> SELECT CURDATE( ), DAYNAME(CURDATE( ));

32

Prepared By, R.Sangeetha AP/CSE

SORTING QUERY RESULTS


1.Introduction:
MySQL displays results by using SELECT statements.
Sorting is performed by adding an ORDER BY clause to a query.
2.Using ORDER BY to Sort Query Results:
ORDER BY has the following general characteristics:
we can sort as per the single column of values or multiple columns
we can sort as per any column either in ascending order (the default) or in
descending order
We can refer to sorted columns by name, by their position within the output
column list, or by using an alias name.
Naming the Sort Columns and Specifying Sorting Direction:
Example: mysql> SELECT * FROM driver_log;

This query produces a single-column sort using the driver name:


mysql> SELECT * FROM driver_log ORDER BY name;

33

Prepared By, R.Sangeetha AP/CSE

The default sort direction is ascending.


SELECT * FROM driver_log ORDER BY name ASC;
mysql> SELECT * FROM driver_log ORDER BY name DESC;

Multiple column sorts:


mysql> SELECT * FROM driver_log ORDER BY name, trav_date;

34

Prepared By, R.Sangeetha AP/CSE

mysql> SELECT * FROM driver_log ORDER BY name DESC, trav_date


DESC;

Mixed-order sorting:
mysql> SELECT * FROM driver_log ORDER BY name DESC,
trav_date;

35

Prepared By, R.Sangeetha AP/CSE

More Ways to Refer to Sort Columns


mysql> SELECT name, trav_date, miles FROM driver_log ORDER BY 3;

Here 3 represents 3rdcolumn

mysql> SELECT name, trav_date, miles AS distance FROM driver_log


-> ORDER BY distance;

36

Prepared By, R.Sangeetha AP/CSE

mysql> SELECT name, trav_date, miles FROM driver_log ORDER BY 3


DESC;

3. Sorting Subsets of a Table:


To sort part of a table, add a WHERE clause that selects only the records we
want.
mysql> SELECT trav_date, miles FROM driver_log WHERE name =
'Henry'-> ORDER BY trav_date;

37

Prepared By, R.Sangeetha AP/CSE

4. Sorting Expression Results:


To sort a query result based on values calculated from a column, rather than
using the values actually stored in the column.
Example:
mysql> SELECT * FROM mail;

mysql> SELECT t, srcuser, FLOOR((size+1023)/1024)


-> FROM mail WHERE size > 50000
-> ORDER BY 3;

38

Prepared By, R.Sangeetha AP/CSE

mysql> SELECT t, srcuser, FLOOR((size+1023)/1024)


-> FROM mail WHERE size > 50000
-> ORDER BY FLOOR((size+1023)/1024);

mysql> SELECT t, srcuser, FLOOR((size+1023)/1024) AS kilobytes


-> FROM mail WHERE size > 50000
-> ORDER BY kilobytes;

Reasons you might still want to use an alias:


It's easier to write the ORDER BY clause using the alias than by repeating
the (rather cumbersome) expression.
The alias may be useful for display purposes, to provide a more meaningful
column label.
5. Displaying One Set of Values While Sorting by Another:
To sort a result set using values that we're not selecting.
Example:

39

Prepared By, R.Sangeetha AP/CSE

CREATE TABLE roster(name CHAR(30), # player name


jersey_numCHAR(3) # jersey number);
mysql> SELECT name, jersey_num FROM roster;

mysql> SELECT name, jersey_num FROM roster ORDER BY jersey_num;

Using CONCAT( ):
mysql> SELECT last_name, first_name FROM name
-> ORDER BY last_name, first_name;
40

Prepared By, R.Sangeetha AP/CSE

mysql> SELECT CONCAT(first_name,' ',last_name) AS full_name


-> FROM name
-> ORDER BY last_name, first_name;

mysql> SELECT CONCAT(first_name,' ',last_name) AS name


-> FROM names
-> ORDER BY LENGTH(CONCAT(first_name,' ',last_name)) DESC;

6. Sorting and NULL Values:


To sort a column that may contain NULL values.
mysql> SELECT val FROM t;

Normally, sorting puts the NULL values at the beginning


mysql> SELECT val FROM t ORDER BY val;
41

Prepared By, R.Sangeetha AP/CSE

To put them at the end instead, introduce an extra ORDER BY column that
maps NULL values to a higher value than non-NULL values:
mysql> SELECT val FROM t ORDER BY IF(val IS NULL,1,0), val;

It works for DESC sorts as well


7. Controlling Case Sensitivity of String Sorts:
String sorts are case sensitive when you don't want them to be, or vice versa.
mysql> SELECT * FROM textblob_val;

mysql> SELECT tstr FROM textblob_val ORDER BY tstr;

mysql> SELECT bstr FROM textblob_val ORDER BY bstr;

42

Prepared By, R.Sangeetha AP/CSE

To perform a case-sensitive sort for strings that are not case sensitive (such
as those in the tstr column) cast the sort column to binary-string form using
the BINARY keyword:
mysql> SELECT tstr FROM textblob_val ORDER BY BINARY tstr;

Another possibility is to convert the output column to binary and sort that:
mysql> SELECT BINARY tstr FROM textblob_val ORDER BY 1;

Using CAST( ):
You can also use the CAST( ) function that is available as of MySQL 4.0.2:
mysql> SELECT tstr FROM textblob_val ORDER BY CAST(tstr AS BINARY);

The complementary operation is to sort binary strings in non-case-sensitive


fashion. To do this, convert the values to uppercase or lowercase with
UPPER( ) or LOWER( ):
mysql> SELECT bstr FROM textblob_val ORDER BY UPPER(bstr);
43

Prepared By, R.Sangeetha AP/CSE

8. Date-Based Sorting:
Sort using a date or time column type, ignoring parts of the values that
are irrelevant if necessary.
mysql> SELECT * FROM temporal_val;

mysql> SELECT * FROM temporal_val ORDER BY d;

mysql> SELECT * FROM temporal_val ORDER BY dt;


mysql> SELECT * FROM temporal_val ORDER BY t;
mysql> SELECT * FROM temporal_val ORDER BY ts;
9. Sorting by Calendar Day:
Sort using the month and day of a date, ignoring the year.
mysql> SELECT date, description FROM event ORDER BY date;

To put these items in calendar order, sort them by month, then by day within
month:
44

Prepared By, R.Sangeetha AP/CSE

mysql> SELECT date, description FROM event


-> ORDER BY MONTH(date), DAYOFMONTH(date);

Using DAYOFYEAR( ) function


mysql> SELECT date, description FROM event ORDER BY DAYOFYEAR(date);

NOTE: If a table represents dates using separate year, month, and day
columns, calendar sorting requires no date-part extraction. Just sort the
relevant columns directly.
10. Sorting by Day of Week:
To sort in day-of-week order.
Use DAYOFWEEK( ) to convert a date column to its numeric day of
week value.
mysql> SELECT DAYNAME(date) AS day, date, description
-> FROM event
-> ORDER BY DAYOFWEEK(date);

If you want to sort in day-of-week order, but treat Monday as the first day of the
week and Sunday as the last, you can use a the MOD( ) function to map Monday to
0, Tuesday to 1, ...,Sunday to 6:
mysql> SELECT DAYNAME(date), date, description
-> FROM event
-> ORDER BY MOD(DAYOFWEEK(date) + 5, 7);

11. Sorting by Time of Day:


If we want to sort in time-of-day order, pull out the hour, minute, and second
from the column that contains the time, and uses them for sorting.
45

Prepared By, R.Sangeetha AP/CSE

mysql> SELECT * FROM mail ORDER BY HOUR(t), MINUTE(t), SECOND(t);

Using TIME_TO_SEC( ):
mysql> SELECT * FROM mail ORDER BY TIME_TO_SEC(t);
12. Sorting Using Substrings of Column Values:
To sort a set of values using one or more substrings of each value.
Extract the hunks you want and sort them separately.
This is an application of sorting by expression value.
13. Sorting by Fixed-Length Substrings:
To sort using parts of a column that occurs at a given position within the
column.
Pull out the parts you need with LEFT( ), MID( ), or RIGHT( ) and sort
them.
mysql> SELECT * FROM housewares;

mysql> SELECT * FROM housewares ORDER BY id;

46

Prepared By, R.Sangeetha AP/CSE

mysql> SELECT id,


-> LEFT(id,3) AS category,
-> MID(id,4,5) AS serial,
-> RIGHT(id,2) AS country
-> FROM housewares;

mysql> SELECT * FROM housewares ORDER BY LEFT(id,3);

mysql> SELECT * FROM housewares ORDER BY MID(id,4,5);

mysql> SELECT * FROM housewares ORDER BY RIGHT(id,2);


47

Prepared By, R.Sangeetha AP/CSE

mysql> SELECT * FROM housewares ORDER BY RIGHT(id,2), MID(id,4,5);

14. Sorting by Variable-Length Substrings:


To sort using parts of a column that does not occur at a given position within
the column.
mysql> SELECT * FROM housewares2;

mysql> SELECT id, SUBSTRING(id,4) FROM housewares2;

mysql> SELECT id, LEFT(SUBSTRING(id,4),LENGTH(SUBSTRING(id,4)-2))


-> FROM housewares2;
48

Prepared By, R.Sangeetha AP/CSE

mysql> SELECT id, SUBSTRING(id,4), SUBSTRING(id,4,LENGTH(id)-5)


-> FROM housewares2;

mysql> SELECT * FROM housewares3;

using SUBSTRING_INDEX(str,c,n):
It searches into a string str for the n-th occurrence of a given character c
and returns everything to the left of that character.
For example, the following call returns 13-478:
SUBSTRING_INDEX('13-478-92-2','-',2)
If n is negative, the search for c proceeds from the right and returns the
rightmost string.
This call returns 478-92-2:
SUBSTRING_INDEX('13-478-92-2','-',-3)
mysql> SELECT
-> id,
-> SUBSTRING_INDEX(SUBSTRING_INDEX(id,'-',2),'-',-1) AS segment2,
-> SUBSTRING_INDEX(SUBSTRING_INDEX(id,'-',4),'-',-1) AS segment4
-> FROM housewares3;
49

Prepared By, R.Sangeetha AP/CSE

15. Sorting Hostnames in Domain Order:


To sort hostnames in domain order, with the rightmost parts of the names
more significant than the leftmost parts.
Break apart the names and sort the pieces from right to left.

16. Sorting Dotted-Quad IP Values in Numeric Order:


To sort strings that represent IP numbers in numeric order.
Break apart the strings and sort the pieces numerically. Or just use
INET_ATON( ).
mysql> SELECT ip FROM hostip ORDER BY ip;

mysql> SELECT ip FROM hostip


-> ORDER BY
-> SUBSTRING_INDEX(ip,'.',1)+0,
-> SUBSTRING_INDEX(SUBSTRING_INDEX(ip,'.',-3),'.',1)+0,
-> SUBSTRING_INDEX(SUBSTRING_INDEX(ip,'.',-2),'.',1)+0,
-> SUBSTRING_INDEX(ip,'.',-1)+0;

50

Prepared By, R.Sangeetha AP/CSE

Using the INET_ATON( )function, which converts a network address


directly to its underlying numeric form:
mysql> SELECT ip FROM hostip ORDER BY INET_ATON(ip);
17. Floating Specific Values to the Head or Tail of the Sort Order:
To sort the way it normally does, except for a few values that you want at a
specific spot.
Add another sort column to the ORDER BY clause that places those few
values where you want them. The remaining sort columns will have their
usual effect for the other values.
18. Sorting in User-Defined Orders:
To define the sort order for all values in a column.
Use FIELD( ) to map column values onto a sequence that places the values
in the desired order.
The following FIELD( ) call compares value to str1, str2, str3,and str4, and
returns 1, 2, 3, or 4, depending on which one of them value is equal
to:FIELD(value,str1,str2,str3,str4)
mysql> SELECT id, description FROM housewares-> ORDER BY
FIELD(RIGHT(id,2),'US','UK','JP','SG');

19. Sorting ENUM Values:


ENUM values don't sort like other string columns.
ENUM is considered a string column type, but ENUM values have the
special property that they are stored numerically with values ordered the
same way they are listed in the table definition.
Example:
CREATE TABLE weekday
(
day ENUM('Sunday','Monday','Tuesday','Wednesday',
51

Prepared By, R.Sangeetha AP/CSE

'Thursday','Friday','Saturday')
);
mysql> INSERT INTO weekday (day) VALUES('Monday'),('Friday'),
-> ('Tuesday'), ('Sunday'), ('Thursday'), ('Saturday'), ('Wednesday');
mysql> SELECT day, day+0 FROM weekday;

GENARATING SUMMARY USING FUNCTIONS


SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a
column.
Useful aggregate functions:
* AVG() - Returns the average value
* COUNT() - Returns the number of rows
* FIRST() - Returnsthe first value
* LAST() - Returnsthe last value
* MAX() - Returnsthe largest value
* MIN() - Returnsthe smallest value
* SUM() - Returns the sum

SQL AVG() Function


The AVG() function returns the average value of a numeric column.
SQL AVG() Syntax
SELECT AVG(column_name) FROM table_name;
SQL AVG() Example
We have the following "Orders" table:

52

Prepared By, R.Sangeetha AP/CSE

Now we want to find the average value of the "OrderPrice" fields.


We use the following SQL statement:
SELECT AVG(OrderPrice) AS OrderAverage FROM Orders;
The result-set will look like this:

Now we want to find the customers that have an OrderPrice value higher
than the average OrderPrice value.
We use the following SQL statement:
SELECT Customer FROM Orders
WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders);
The result-set will look like this:

SQL COUNT() Function


The COUNT() function returns the number of rows that matches a specified
criteria.
SQL COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values (NULL values
will not be
counted) of the specified column:
SELECT COUNT(column_name) FROM table_name;
SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table:
SELECT COUNT(*) FROM table_name;
SQL COUNT(DISTINCT column_name) Syntax
The COUNT(DISTINCT column_name) function returns the number of distinct
values of the specified column:
SELECT COUNT(DISTINCT column_name) FROM table_name;
Now we want to count the number of orders from "Customer Nilsen".
We use the following SQL statement:
SELECT COUNT(Customer) AS CustomerNilsen FROM Orders
WHERE Customer='Nilsen';
The result of the SQL statement above will be 2, because the customer Nilsen has
made 2 orders in total:

53

Prepared By, R.Sangeetha AP/CSE

SQL COUNT(*) Example


If we omit the WHERE clause, like this:
SELECT COUNT(*) AS NumberOfOrders FROM Orders;
The result-set will look like this:

which is the total number of rows in the table.


SQL COUNT(DISTINCT column_name) Example
Now we want to count the number of unique customers in the "Orders"
table.
We use the following SQL statement:
SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM
Orders;
The result-set will look like this:

which is the number of unique customers (Hansen, Nilsen, and Jensen) in the
"Orders" table.
The FIRST() Function
The FIRST() function returns the first value of the selected column.
SQL FIRST() Syntax
SELECT FIRST(column_name) FROM table_name;
SQL FIRST() Example
Now we want to find the first value of the "OrderPrice" column.
We use the following SQL statement:
SELECT FIRST(OrderPrice) AS FirstOrderPrice FROM Orders;
Tip: Workaround if FIRST() function is not supported:
SELECT OrderPrice FROM Orders ORDER BY O_Id LIMIT 1;
The result-set will look like this:

The LAST() Function


The LAST() function returns the last value of the selected column.
SQL LAST() Syntax
54

Prepared By, R.Sangeetha AP/CSE

SELECT LAST(column_name) FROM table_name;


SQL LAST() Example
Now we want to find the last value of the "OrderPrice" column.
We use the following SQL statement:
SELECT LAST(OrderPrice) AS LastOrderPrice FROM Orders;
Tip: Workaround if LAST() function is not supported:
SELECT OrderPrice FROM Orders ORDER BY O_Id DESC LIMIT 1;
The result-set will look like this:

The SQL MAX() Function


The MAX() function returns the largest value of the selected column.
SQL MAX() Syntax
SELECT MAX(column_name) FROM table_name;
SQL MAX() Example
Now we want to find the largest value of the "OrderPrice" column.
We use the following SQL statement:
SELECT MAX(OrderPrice) AS LargestOrderPrice FROM Orders;
The result-set will look like this:

The MIN() Function


The MIN() function returns the smallest value of the selected column.
SQL MIN() Syntax
SELECT MIN(column_name) FROM table_name;
SQL MIN() Example
Now we want to find the smallest value of the "OrderPrice" column.
We use the following SQL statement:
SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Orders;
The result-set will look like this:

The SUM() Function


The SUM() function returns the total sum of a numeric column.
SQL SUM() Syntax
SELECT SUM(column_name) FROM table_name;
SQL SUM() Example
55

Prepared By, R.Sangeetha AP/CSE

Now we want to find the sum of all "OrderPrice" fields".


We use the following SQL statement:
SELECT SUM(OrderPrice) AS OrderTotal FROM Orders;
The result-set will look like this:

USING SEQUENCES
INTRODUCTION
A sequence is a set of integers 1, 2, 3 ... that are generated in order on
demand. Sequences are frequently used in databases because many applications
require each row in a table to contain a unique value, and sequences provide an
easy way to generate them.

MySQL Sequences
Using AUTO_INCREMENT To Set Up a SequenceColumn
One of the useful properties of an AUTO_INCREMENT column is that you
don't have to assign its value by yourselfMySQL does for you.
CREATE TABLE insect
(name VARCHAR(30) NOT NULL,
date DATE NOT NULL,
origin VARCHAR(30) NOT NULL );

CREATE TABLE insect


(id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id),
name VARCHAR(30) NOT NULL,
date DATE NOT NULL,
origin VARCHAR(30) NOT NULL );
There are two ways to generate new AUTO_INCREMENT values,
First, you can explicitly set the id column to NULL.
mysql> INSERT INTO insect (id,name,date,origin) VALUES
-> (NULL,'housefly','2001-09-10','kitchen'),
-> (NULL,'millipede','2001-09-10','driveway'),
-> (NULL,'grasshopper','2001-09-10','front yard'),
-> (NULL,'stinkbug','2001-09-10','front yard');
56

Prepared By, R.Sangeetha AP/CSE

Second, you can omit the id column from the INSERT statement entirely
mysql> INSERT INTO insect (name,date,origin) VALUES
-> ('butterfly','2001-09-10','garden'),
-> ('ant','2001-09-10','back yard'),
-> ('ant','2001-09-10','back yard'),
-> ('millbug','2001-09-10','under rock');
mysql> SELECT * FROM insect ORDER BY id;

Choosing the Type for a Sequence Column


Guidelines to be followed when creating an AUTO_INCREMENT column.
e.g
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
1. INT is the column's basic type. It is not necessarily use INT, but the column
must be one of the integer types: TINYINT, SMALLINT, MEDIUMINT, INT, or
BIGINT.
2. The column is declared as UNSIGNED. There's no need to allow negative
values, because AUTO_INCREMENT sequences consist only of positive integers
(normally begins at 1).
3. AUTO_INCREMENT columns cannot contain NULL values, so id is declared
as NOT NULL.
4. The column is declared as a PRIMARY KEY to ensure that its values are
unique. If the table already has some other PRIMARY KEY column, use UNIQUE
index instead
e.g
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
UNIQUE (id)
The Effect of Record Deletions on Sequence Generation
You want to know what happens to a sequence when you delete records
from a table that contains an AUTO_INCREMENT column.
57

Prepared By, R.Sangeetha AP/CSE

mysql> DELETE FROM insect WHERE id IN (2,8,7);


the resulting table contents become:
mysql> SELECT * FROM insect ORDER BY id;

Retrieving Sequence Values


After creating a record that includes a new sequence number, you want to
find out what that number is.
To do this in a SQL statement, you can use the LAST_INSERT_ID( )
function.
mysql> INSERT INTO insect (name,date,origin)
-> VALUES('cricket','2001-09-11','basement');
mysql> SELECT LAST_INSERT_ID( );

Determining Whether to Resequencea Column


You have gaps in a sequence column and you're wondering whether to
resequence it.

58

Prepared By, R.Sangeetha AP/CSE

Reasons to Avoid Resequencing


We should not resequence a column containing values that are referenced by
another table. Renumbering the values destroys their correspondence to values in
the other table, making it impossible to relate records in the two tables.
Reusing Values at the Top of a Sequence
You've deleted rows at the top end of your sequence, to avoid resequencing
the column,but still to reuse the values that have been deleted, use ALTER TABLE
to reset the sequence counter
For MyISAM or InnoDB tables, issue the following statement:
ALTER TABLE tbl_name AUTO_INCREMENT = 1
This causes MySQL to reset the sequence counter down as far as it can for
creating new records in the future.
Starting a Sequence at a Particular Value
Sequences start at 1, to use a different starting value, add an
AUTO_INCREMENT clause to your CREATE TABLE statement when you
create the table. If the table has already been created, use an ALTER TABLE
statement to set the starting value.
mysql> CREATE TABLE t
-> (id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id))

-> AUTO_INCREMENT = 100;


mysql> INSERT INTO t (id) VALUES(NULL);
mysql> INSERT INTO t (id) VALUES(NULL);
mysql> INSERT INTO t (id) VALUES(NULL);
mysql> SELECT id FROM t ORDER BY id;

Alternatively, you can create the table and then set the initial sequence value
with ALTER TABLE:
59

Prepared By, R.Sangeetha AP/CSE

mysql> CREATE TABLE t


-> (id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY(id));

mysql> ALTER TABLE t AUTO_INCREMENT = 100;


mysql> INSERT INTO t (id) VALUES(NULL);
mysql> INSERT INTO t (id) VALUES(NULL);
mysql> INSERT INTO t (id) VALUES(NULL);
mysql> SELECT id FROM t ORDER BY id;

MYSQL AND WEB


On the Web today, content is king. After you've mastered HTML and
learned a few neat tricks in JavaScript and Dynamic HTML, you can probably
build a pretty impressive-looking Web site design. But then comes the time to fill
that fancy page layout with some real information. Any site that successfully
attracts repeat visitors has to have fresh and constantly updated content. In the
world of traditional site building, that means HTML files--and lots of 'em.
The problem is that, more often than not, the people providing the content
for a site are not the same people handling its design. Oftentimes, the content
provider doesn't even know HTML. How, then, is the content to get from the
provider onto the Web site? Not every company can afford to staff a full-time
Webmaster, and most Webmasters have better things to do than copying Word
files into HTML templates anyway.
Maintenance of a content-driven site can be a real pain, too. Many sites
(perhaps yours?) feel locked into a dry, outdated design because rewriting those
hundreds of HTML files to reflect a new design would take forever. Server-side
includes (SSI's) can help alleviate the burden a little, but you still end up with
hundreds of files that need to be maintained should you wish to make a
fundamental change to your site.
The solution to these headaches is database-driven site design. By achieving
complete separation between your site's design and the content you are looking to
present, you can work with each without disturbing the other. Instead of writing an
HTML file for every page of your site, you only need to write a page for each kind
of information you want to be able to present. Instead of endlessly pasting new
content into your tired page layouts, create a simple content management system
that allows the writers to post new content themselves without a lick of HTML!

60

Prepared By, R.Sangeetha AP/CSE

In this 10-part weekly series of articles, I'll provide a hands-on look at what's
involved in building a database-driven Web site. We'll be using two new tools for
this: the PHP scripting language and the MySQL relational database. If your Web
host provides PHP/MySQL support, you're in great shape. If not, we'll be looking
at the set-up procedures under Unix and Windows, so don't sweat it.
These articles are aimed at intermediate or advanced Web designers looking
to make the leap into server-side programming. You'll be expected to be
comfortable with HTML, as I'll be making use of it without explanation. A teensy
bit of JavaScript may serve us well at some point, but I'll be sure to keep it simple
for the uninitiated.
By the end of this series, you can expect to have a grasp of what's involved
in setting up and building a database-driven Web site. If you follow along with the
examples, you'll also learn the basics of PHP (a server-side scripting language that
allows you to do a lot more than access a database easily) and Structured Query
Language (SQL -- the standard language for interacting with relational databases).
Most importantly, you'll come away with everything you need to get started on
your very own database-driven site in no time!
Part 1: Installation
Hi there, and welcome to the first in SitePoint.com's ten-part series on
building a database-driven Web site! For the next few months, it will be my job to
guide you as you take your first steps beyond the HTML-and-JavaScript world of
client-side site design. Together we'll learn everything that's needed to build the
kind of large, content-driven sites that are so successful today, but which can be a
real headache to maintain if they aren't done right.
Before we get started, we need to gather together the tools we'll need for the
job. In this first article, we'll download and set up the two software packages we'll
be using: PHP and MySQL.
PHP is a server-side scripting language. You can think of it as a "plug-in"
for your Web server that will allow it to do more than just send plain Web pages
when browsers request them. With PHP installed, your Web server will be able to
read a new kind of file (called a "PHP script") that can do things like retrieve upto-the-minute information from a database and insert it into a Web page before
sending it to the browser that requested it. PHP is completely free to download and
use.
To retrieve information from a database, you first need to have a database.
That's where MySQL comes in. MySQL is a relational database management
system, or RDBMS. Exactly what role it plays and how it works we'll get into
later, but basically it's a software package that is very good at organizing and
managing large amounts of information. MySQL also makes that information
really easy to get at using server-side scripting languages like PHP. MySQL is free
61

Prepared By, R.Sangeetha AP/CSE

for non-commercial use on most Unix-based platforms, like Linux. MySQL for
Windows 9x/NT/2000 costs about US$200 to buy, but you can download an older
version for free if you just want to try it out. For our purposes, the older version
will serve just fine, but if you find MySQL for Windows useful and you decide to
use it on one of your own sites, you should pay for it.
If you're lucky, your current Web host may already have installed MySQL
and PHP on your Web server for you. If that's the case, much of this article will not
apply to you, and you can skip straight to If Your Web Host Provides PHP and
MySQL to make sure everything is ship shape.
Everything we'll discuss in this article series may be done on a Windows- or
Unix-based server. Depending on which type of server you'll be using, the
installation procedure will be different. The next section deals with installation on
a Windows-based Web server. The section after that deals with installation under
Linux (and other Unix-based platforms). Unless you're especially curious, you
should only need to read the section that applies to you.
Part 2: Getting Started with MySQL
Hi there, and welcome back! Last week, we went through the process of
installing and setting up two software programs: PHP and MySQL. This week,
we'll be concentrating on the latter by learning how to work with MySQL
databases using Structured Query Language (SQL).
An Introduction to Databases
As I explained briefly last week, PHP is a server-side scripting language that
lets you insert instructions into your Web pages that your Web server software (be
it Apache, Personal Web Server, or whatever) will execute before sending those
pages to a browser that requests them. In a brief example, I showed how it was
possible to insert the current date into a Web page every time it was requested.
Now thats all well and good, but things really get interesting when a
database is added to the mix. A database server (in our case, MySQL) is a program
that can store large amounts of information in an organized format that is easily
accessible from scripting languages like PHP. For example, you could tell PHP to
look in the database for a list of jokes that you'd like to appear on your Web site.
In this example, the jokes would be stored entirely in the database. The
advantage of this would be twofold. First, instead of having to write an HTML file
for each of your jokes, you could write a single PHP file designed to fetch any joke
out of the database and display it. Second, to add a joke to your Web site would
just be a matter of adding the joke to the database. The PHP code would take care
of the rest by automatically displaying the new joke along with the rest when it
fetched the list of jokes from the database.
Lets run with this example as we look at how data is stored in a database. A
database is composed of one or more 'tables', each of which contains a list of
62

Prepared By, R.Sangeetha AP/CSE

'things'. For our joke database, we would probably start with a table called "jokes"
which would contain a list of jokes. Each table in a database has one or more
columns, or fields. Each column holds a certain piece of information about each
"thing" in the database. Returning to our example, our "jokes" table might have
columns for the text of the jokes and the dates the jokes were added to the
database. Each joke that we stored in this table would then be said to be a 'row' in
the table. To see where all this terminology comes from, have a look at what this
table actually looks like:
Notice that, in addition to columns for the joke text ("JokeText") and the
date of the joke ("JokeDate"), I included a column named "ID". The function of
this column is to assign a unique number to each joke so we have an easy way to
refer to them and to keep track of which joke is which.
So to review, the above is a three-column table with two rows (or entries).
Each row in the table contains a joke's ID, its text, and the date of the joke. With
this basic terminology under our belts, we're ready to get started using MySQL.
Part 3: Publishing MySQL Data on the Web
This is it -- the stuff you signed up for! This is the week we take information stored
in a database and display it on a Web page for all to see. So far we've installed and
learned the basics of MySQL, a relational database engine, and PHP, a server-side
scripting language. In this week's installment, we see how to use these two new
tools together to create a true database-driven Web site!
A Look Back at First Principles
Before we leap forward, it's worth a brief look back to remind ourselves of
the goal we are working toward. We have two powerful, new tools at our disposal:
the PHP scripting language, and the MySQL database engine. It's important to
understand how these two are going to fit together.
The whole idea of a database-driven Web site is to allow the content of the
site to reside in a database, and for that content to be dynamically pulled from the
database to create Web pages featuring it for people using a regular Web browser
to view. So on one end of the system you have a visitor to your site using a Web
browser, loading http://www.yoursite.com/, and expecting to view a standard
HTML Web page. On the other end you have the content of your site sitting in one
or more tables in a MySQL database that only understands how to respond to SQL
queries (commands).
The PHP scripting language is the go-between that speaks both languages.
Using PHP, you can write the presentation aspects of your site (the fancy graphics
and page layouts) as "templates" in regular HTML. Where the content belongs in
those templates, you use some PHP code to connect to the MySQL database and -using SQL queries just like those you used to create a table of jokes in Part Two -retrieve and display some content in its place.
63

Prepared By, R.Sangeetha AP/CSE

Just so it's clear and fresh in your mind, this is what will happen when
someone visits a page on our database-driven Web site:
The visitor's Web browser asks for the Web page using a standard URL.
The Web server software (Apache, IIS, or whatever) recognizes that the
requested file is a PHP script, and so interprets it using its PHP plug-in
before responding to the page request.
Some PHP commands (which we have yet to learn) connect to the MySQL
database and request the content that belongs in the Web page.
The MySQL database responds by sending the requested content to the
PHP script.
The PHP script stores the content into one or more PHP variables, then
uses the now familiar echo function to output it as part of the Web page.
The PHP plug-in finishes up by handing a copy of the HTML it has created
to the Web server.
The Web server sends the HTML to the Web browser as it would a plain
HTML file, except instead of coming directly from an HTML file, the page
is the output provided by the PHP plug-in.
Connecting to MySQL with PHP
Before we can get content out of our MySQL database for inclusion in our
Web page, we must first know how to establish a connection to MySQL. Back in
Part Two, we used a program called mysql that allowed us to make such a
connection. PHP has no need of any special program, however; support for
connecting to MySQL is built right into the language. The following PHP function
call establishes the connection:
mysql_connect(<address>, <username>, <password>);
Where <address> is the IP address or hostname of the computer on which
the MySQL server software is running ("localhost" if running on the same
computer as the Web server software), and <username> and <password> are the
same MySQL user name and password you used to connect to the MySQL server
in Part Two.
You may or may not remember that functions in PHP usually return (output)
a value when they are called. Don't worry if this doesn't ring any bells for you -- it's
a detail that we glossed over when originally discussing functions. In addition to
doing something useful when they are called, most functions output a value, and
that value may be stored in a variable for later use. The mysql_connect function
shown above, for example, returns a number that identifies the connection that has
been established. Since we intend to make use of the connection, we should hold
onto this value. Here's an example of how we might connect to our MySQL server.
$dbcnx = mysql_connect("localhost", "root", "mypasswd");
64

Prepared By, R.Sangeetha AP/CSE

As described above, the values of the three function parameters may differ
for your MySQL server. What's important to see here is that the value returned by
mysql_connect (which we'll call a connection identifier) is stored in a variable
named $dbcnx.
Since the MySQL server is a completely separate piece of software, we must
consider the possibility that the server is unavailable, or inaccessible due to a
network outage, or because the username/password combination you provided is
not accepted by the server. In such cases, the mysql_connect function doesn't
return a connection identifier (since no connection is established). Instead, it
returns false. This allows us to react to such failures using an if statement:
$dbcnx = @mysql_connect("localhost", "root", "mypasswd");
if (!$dbcnx) {
echo( "<P>Unable to connect to the " .
"database server at this time.</P>" );
exit();
}
There are three new tricks in the above code fragment. First, we have placed
a @ symbol in front ofthe mysql_connect function. Many functions, including
mysql_connect, automatically display ugly error messages when they fail. Placing
a @ symbol in front of the function name tells the function to fail silently, allowing
us to display our own, friendlier error message.
Next, we put an exclamation point in front of the $dbcnx variable in the
condition of the if statement. The exclamation point is the PHP "negation
operator", which basically flips a false value to true, or a true value to false. Thus,
if the connection fails and mysql_connect returns false, ! $dbcnx will evaluate to
true, and cause the statements in our if statement to be executed. Alternatively, if a
connection was made, the connection identifier stored in $dbcnx will evaluate to
true (any number other than zero is considered "true" in PHP), so !$dbcnx will
evaluate to false, and the statements in the if statement will not be executed.
The last new trick is the exit function, which is the first example of a
function that takes no parameters that we have encountered. All this function does
is cause PHP to stop reading the page at this point. This is a good response to a
failed database connection, since in most cases the page will be unable to display
any useful information without that connection.
As in Part Two, the next step once a connection is established is to select the
database you want to work with. Let's say we want to work with the joke database
we created in Part Two. The database we created was called jokes. Selecting that
database in PHP is just a matter of another function call:
mysql_select_db("jokes", $dbcnx);
65

Prepared By, R.Sangeetha AP/CSE

Notice we use the $dbcnx variable containing the database connection


identifier to tell the function what database connection to use. This parameter is
actually optional. When it is omitted, the function will automatically use the link
identifier for the last connection opened. This function returns true when
successful and false if an error occurs. Once again, it is prudent to use an if
statement to handle errors:
if (! @mysql_select_db("jokes") ) {
echo( "<P>Unable to locate the joke " .
"database at this time.</P>" );
exit();
}
With a connection established and a database selected, we are now ready to
begin using the data stored in the database.

WORKING WITH META DATA


DEFINITION:
The information that characterizes the database values is called query
metadata.
It is most often used in relation to processing result sets.
We use the following types of metadata:
1.Information about the result of queries.
When you delete or update a set of rows, you can determine the number of rows
that were changed. For a SELECT query, you can find out the number of columns
in the result set, as well as information about each column in the result set, such as
the column name and its display width. Such information often is essential for
processing the results.
2.Information about tables and databases.
Information pertaining to the structure of tables and databases is useful for
applications that need to enumerate a list of tables in a database or databases
hosted on a server
3.Information about the MySQLserver.
Some APIs provide information about the database server or about the status of
your current connection with the server. Knowing the server version can be useful
for determining whether it supports a given feature, which helps you build adaptive
applications. Information about the connection includes such items as the current
user and the current database.
Lists of tables and databases in MySQL are available by issuing SHOW
statements.
The following show command is similar to DESCRIBE $tbl_name;
66

Prepared By, R.Sangeetha AP/CSE

$Query= "SHOW COLUMNS FROM $tbl_name";


If the server is running in ANSI mode, table name quoting should be done with
double quotes.
$Query = "SHOW COLUMNS FROM \"$tbl_name\"";
Listing Tables and Databases:
Use SHOW TABLES or SHOW DATABASES.
e.g: SHOW TABLES FROM db_name;
Testing Whether a Table Exists:
Use SHOW TABLES to check whether the table is listed.
Testing Whether a Database Exists:
Use SHOW DATABASES to to check whether the table is listed.
IN PHP
mysql_affected_rows( )
In PHP, invoke the mysql_affected_rows( ) function to find out how many
rows a query changed:
$result_id = mysql_query ($query, $conn_id);
# report 0 rows if the query failed
$count = ($result_id ? mysql_affected_rows ($conn_id) : 0);

print ("$count rows were affected\n");


The argument to mysql_affected_rows( ) is a connection identifier. If you
omit the argument, the current connection is used.
The mysql_query( ) function executes a query on a MySQL database.
The mysql_free_result() function frees memory used by a result handle.
The mysql_num_fields() function returns the number of fields in a recordset.
The mysql_num_rows() function returns the number of rows in a recordset.
The mysql_fetch_field() function returns an object containing information of a
field from a recordset.
Getting Server Metadata:
Several SELECT and SHOW statements return information about the server.
SELECT VERSION( ) -Server version string
SHOW STATUS() -Server status indicators
SHOW VARIABLES() -Server configuration variables
In Python
To get the row count for a result set, access the cursor's rowcount attribute. The
column count is not available directly, but after calling fetchone( ) or fetchall( ),
you can determine the count as the length of any result set row tuple. It's also
possible to determine the column count without fetching any rows by using
cursor.description.
67

Prepared By, R.Sangeetha AP/CSE

Example:
query = "SELECT name, foods FROM profile"
print "Query: ", query
cursor = conn.cursor ( )
cursor.execute (query)
# metadata information becomes available at this point ...
print "Number of rows:", cursor.rowcount
if cursor.description == None: # no result set
ncols = 0
else:
ncols = len (cursor.description)
print "Number of columns:", ncols
if ncols == 0:
print "Note: query has no result set"
for i in range (ncols):
col_info = cursor.description[i]
# print name, then other information
print "--- Column %d (%s) ---" % (i, col_info[0])
print "Type: ", col_info[1]
print "Display size: ", col_info[2]
print "Internal size:", col_info[3]
print "Precision: ", col_info[4]
print "Scale: ", col_info[5]
print "Nullable: ", col_info[6]
cursor.close
Output:
Query: SELECT name, foods FROM profile
Number of rows: 10L
Number of columns: 2
--- Column 0 (name) --Type: 254
Display size: 7
Internal size: 20
Precision: 20
Scale: 0
Nullable: 0
--- Column 1 (foods) --Type: 254
Display size: 21
Internal size: 42
Precision: 42
68

Prepared By, R.Sangeetha AP/CSE

Scale: 0
Nullable: 1

In JAVA
Example:
String query = "SELECT name, foods FROM profile";
System.out.println ("Query: " + query);
Statement s = conn.createStatement ( );
s.executeQuery (query);
ResultSet rs = s.getResultSet ( );
ResultSetMetaData md = rs.getMetaData ( );
// metadata information becomes available at this point ...
int ncols = md.getColumnCount ( );
System.out.println ("Number of columns: " + ncols);
if (ncols == 0)
System.out.println ("Note: query has no result set");
for (int i = 1; i <= ncols; i++) // column index values are 1-based
{
System.out.println ("--- Column " + i
+ " (" + md.getColumnName (i) + ") ---");
System.out.println ("getColumnDisplaySize: " +
md.getColumnDisplaySize(i));
System.out.println ("getColumnLabel: " + md.getColumnLabel (i));
System.out.println ("getColumnType: " + md.getColumnType (i));
System.out.println ("getColumnTypeName: " + md.getColumnTypeName(i));

System.out.println ("getPrecision: " + md.getPrecision (i));


System.out.println ("getScale: " + md.getScale (i));
System.out.println ("getTableName: " + md.getTableName (i));
System.out.println ("isAutoIncrement: " + md.isAutoIncrement (i));
System.out.println ("isNullable: " + md.isNullable (i));
System.out.println ("isCaseSensitive: " + md.isCaseSensitive (i));
System.out.println ("isSigned: " + md.isSigned (i));
}
rs.close ( );
s.close ( );
Output:
Query: SELECT name, foods FROM profile
Number of columns: 2
--- Column 1 (name) --getColumnDisplaySize: 20
getColumnLabel: name
69

Prepared By, R.Sangeetha AP/CSE

getColumnType: 1
getColumnTypeName: CHAR
getPrecision: 0
getScale: 0
getTableName: profile
isAutoIncrement: false
isNullable: 0
isCaseSensitive: true
isSigned: false
--- Column 2 (foods) --getColumnDisplaySize: 42
getColumnLabel: foods
getColumnType: 1
getColumnTypeName: CHAR
getPrecision: 0
getScale: 0
getTableName: profile
isAutoIncrement: false
isNullable: 1
isCaseSensitive: true
isSigned: false
In Perl
In DBI scripts, the affected-rows count is returned by do( ) or by execute( ),
depending on how you execute the query:
# execute $query using do( )
my $count = $dbh->do ($query);
# report 0 rows if an error occurred
printf "%d rows were affected\n", (defined ($count) ? $count : 0);
# execute query using prepare( ) plus execute( )
my $sth = $dbh->prepare ($query);
my $count = $sth->execute ( );
printf "%d rows were affected\n", (defined ($count) ? $count : 0);

Writing your own SQL programs (Refer the Corresponding Notes)


PHP+MySQL
Perl +MySQL
Python+MySQL
JAVA+MySQL
70

Prepared By, R.Sangeetha AP/CSE

Potrebbero piacerti anche