Sie sind auf Seite 1von 42

Unit-II Notes

UNIT II OPEN SOURCE DATABASE 1


MySQL: Introduction Setting up account Starting, terminating and writing
your ownSQL programs Record selection Technology Working with strings
Date and Time Sorting Query Results Generating Summary Working with
metadata Using sequences MySQL and Web.

Introduction:
MySQL is a relational database management system (RDBMS) that runs as a
server providing multi-user access to a number of databases. It is a popular
choice of database for use in web applications, and is a central component of
the widely used LAMP web application software stackLAMP is an acronym for
"Linux, Apache, MySQL, and Perl/PHP/Python". It is used in some of the most
frequently visited web sites on the Internet, including Flickr, Nokia.com, and
YouTube etc.

MySQL is written in C and C++. Its SQL parser is written in yacc, and a home-
brewed lexical analyzer named sql_lex.cc. It works on many different system
platforms, including Linux, Mac OS X, Microsoft Windows, AIX, BSDi,
FreeBSD, HP-UX, eComStation, i5/OS, IRIX, NetBSD, Novell NetWare,
OpenBSD, OpenSolaris, OS/2 Warp, QNX, Solaris, Symbian, SunOS, SCO
OpenServer, SCO UnixWare, Sanos and Tru64. Many programming languages
with language-specific APIs include libraries for accessing MySQL databases.
These include MySQL Connector/Net for integration with Microsoft's Visual
Studio (languages such as C# and VB are most commonly used) and the ODBC
driver for Java.

Setting up a MySQL new user account


When you try to access MySQL database server from client such as mysql or
even programming language such as php or perl you need a user account.
MySQL has sophisticated user management system that controls who can
access server and from which client system. It uses special tables in mysql
database. In order to create a new user account you need a MySQL root
account password. Next you need to use the GRANT SQL command to set up
the MySQL user account. Finally, use the account's name and password to
make connections to the MySQL server.

Please note that MySQL user accounts are different from UNIX/Linux login
accounts. For example, the MySQL root user and the Linux/Unix root user are
separate and have nothing to do with each other, even though the username is
the same in each case.
Unit-II Notes

Procedure for setting up a MySQL user account 2


Login in as mysql root user (at shell prompt type following command :):
$ mysql -u root -p
OR
$ mysql -u root -h myserver-sever.com -p
Create a new mysql database called demo
mysql> CREATE DATABASE demo;
Create a new user called user1 for database demo
mysql> GRANT ALL ON demo.* TO user1@localhost IDENTIFIED BY
'mypassword';
Note: GRANT ALL means all privileges i.e. user is permitted do anything. She
can read, modify or delete data, but only on tables in the demo database. She
cannot access any other database.
How do I connect to MySQL server using user1 account?
User user1 can connect to mysql server demo database using following
command:
$ mysql -u user1 -p demo
OR
$ mysql -u user1 -h mysql.server.com -p demo
Where,
-u user1: MySQL Username
h : MySQL server name (default is localhost)
-p : Prompt for password
demo: demo is name of mysql database (optional)

Starting and terminating mysql


To start mysql server:
/etc/init.d/mysqld start
To stop mysql server:
/etc/init.d/mysqld stop
To restart mysql server
/etc/init.d/mysqld restart

Tip: Redhat Linux also supports service command, which can be use to start,
restart, stop any service:
# service mysqld start
# service mysqld stop
# service mysqld restart
To start the mysql program, try just typing its name 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.
% mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 18427 to server version: 3.23.51-log
Unit-II Notes

Type 'help;' or '\h' for help. Type '\c' to clear the buffer. 3
mysql>
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.

MySQL: Create a Database in MySQL


This tip walks you through the steps of creating a database in mySQL. The
database created in this tip, is a simple database and table to be used with a
guest book application.
Create the Database File
The first step is to create the database file. Start the mySQL client and type the
following command:
mysql>create database guestdb;
Query OK, 1 row affected (0.00 sec)
mysql>
The command creates the the database, guestdb. If successful, you should
receive a response like the one shown above.
After the database is created, we must select it to continue with our database
building.
mysql> use guestdb;
Database changed
mysql>
Now with our database selected, we are ready for the next step.

MySQL: MySQL Field Types


MySQL supports the following Field Types in version 3.x of MySQL.
String Types
Name Max Size Space Taken
char(x) 255 bytes x bytes
varchar(x) 255 bytes x+1 bytes
tinytext 255 bytes x+1 bytes
tinyblob 255 bytes x+2 bytes
text 64k x+2 bytes
blob 64k x+2 bytes
mediumtext 1.6mb x+3 bytes
mediumblob 1.6mb x+3 bytes
longtext 4.2gb x+4 bytes
longblob 4.2gb x+4 bytes
Examples
Here is an example of a database commands using these field types. SQL
command ends in a semi-colon. The following commands are issued below:
Unit-II Notes

1. Create a temp database 4


2. Make the temp database the current database
3. Create a table using some of the variables listed in the table above.
create database temp;

use database temp;


create table testTable
(testName varchar(30),testDate text,
testGiver char(30));

Integer Types
Type Range Space Taken
tinyint -128 to 127 1 byte
smallint -32768 to 32767 2 bytes
medium int -8388608 to 8388607 3 bytes
int -2147483648 to 2147483647 4 bytes
bigint -9223372036854775808 to 9223372036854775807 8 bytes
float(m,d) varies 4 bytes
double(m,d) varies 8 bytes
decimal varies M + 2 bytes

Date Types
Type Format Zero Value
datetime yyyy-nn-dd hh:mm:ss 0000-00-00 00:00:00
date yyyy-mm-dd 0000-00-00
time hh:mm:ss 00:00:00
year yyyy 0000
timestamp varies 0000000000

The various timestamp formats are:


Type Format
timestamp(14) yyyymmddhhmmss
timestamp(12) yymmddhhmmss
timestamp(10) yymmddhhmm
timestamp(8) yyyymmdd
timestamp(6) yymmdd
timestamp(4) yymm
timestamp(2) yy
Unit-II Notes

Other types 5
In addition to the types mentioned there are two other types worth mentioning.
The enum type defines a set of values, of which, only one may be chosen.
fieldname enum('a','b','c')
In addition to enum, the set field type also lets you define a set of values.
However, with set, more than one value in the list may be selected.

Column Modifiers
Name Applicable Types
auto_increment All int types
binary char, varchar
default all except blob and text
not null all
null all
primary key all
unique all
unsigned Numeric types
zerofill Numeric types
Auto_increment makes the field an automatic counter.
Binary makes the strings stored case sensitive. By default the values stored in
the char, varchar types are not case sensitive when searched.
Default allows you specify a default value for a field
Below is a create statement that uses a number of modifiers:
create table testTable
(testID int not null primary key auto_increment,
testName varchar(30),
testDate datetime,
testGiver varchar(30));

Create a Table
Next, you need to create a database table to hold your data. The SQL here
defines a table. Below is the command and the output from the command. The
database created below will be used in a web guestbook application.
mysql> create table guestTbl
-> (msgID int not null primary key auto_increment,
-> name varchar(30),
-> email varchar(30),
-> msgFrom varchar(30),
-> msgDate timestamp(14),
-> msgBody text);
Query OK, 0 rows affected (0.11 sec)
mysql>
In this example, the create command creates a table named guestTbl. The table
has six fields described below.
Unit-II Notes

msgID - a unique number assigned to each entry. The field hold an integer 6
value that is automatically incremented each time an entry is added.
name - a 30 character field holding the name of the guest.
email - a 30 character field holding the email address of the guest.
msgFrom - a 30 character field holding the location of the guest.
msgDate - the date and time the entry is added to the database.
msgBody - a text field holding a text message entered by the guest.
Our next step is to add data to the table.

Add data to the Table


Now we need to add some sample data to the table, so we can actually run
some queries against it.
mysql> insert into guestTbl
-> (msgID, name, email, msgFrom, msgDate, msgBody) values
-> (NULL, 'Test User1', 'testuser@test.com','Smallville USA',now(),
-> 'This is the body for message 1.');
Query OK, 1 row affected (0.27 sec)
mysql>
The above command adds one row to the database. If we repeat this process for
three other users, we have enough data to perform a query on the table.

MySQL: Updating a MySQL Table Structure


The structure of table can be changed with the alter keyword. Examples in
various situations follow.
Adding Columns/Fields
The syntax for adding a column follows.
alter table tablename add columnname datatype

Tablename, columnname, and datatype are supplied by you. For example:


alter table lists add title varchar(30);

The above command adds the title field/column to the table lists, and sets the
datatype to varchar(30). Modifiers can also be used. The following example
requires the column contains data.
alter table lists add title varchar(30);

Deleting Columns/Fields
The syntax for dropping a column or field from a table is pretty straightforward.
alter table tablename drop columnname;

You supply tablename and columnname. For example, to delete the column
just added above, the syntax would be:
alter table lists drop title;

This drops the title field from the table lists.


Unit-II Notes

MySQL: Updating a MySQL Record 7


The update keyword is used to update individual database records.
Updating a Column
To update a record, the update keyword is used as follows:

update tablename set columnname = "newdata" where columnname = value;


You supply the tablename, columnname, data and the columnname and value
that determine which rows are updated. Here is an example.
update dstore set Title = "New Title" where pagno = 1;
This command would replace the title column with the new data for any row
that meets the requirement in the where clause. The where clause depends on
the type of data in the column. If the column contains a char or text field, then
a string would be used.

Updating Multiple Columns


To update multiple columns, the format looks something like this.
update tablename set columnname = "newdata", columnname = "newdata",
columnname =number where columnname = value;
Each column and its data is merely separated by commas. Here an example of
two columns being updated.
update dstore set Title = "New Title", Category = "PHP" where pagno = 1;

Writing MySQL-Based Programs


MySQL Client Application Programming Interfaces
It shows how to write MySQL-based programs using Perl, PHP, Python
and it's possible to use several other languages as well. MySQL APIs provide a
standard way for you, the application developer, to express database
operations. Each API translates your instructions into something the MySQL
server can understand.

MySQL client APIs provide the following capabilities


Connecting to the MySQL server; selecting a database; disconnecting
from the server.
Every program that uses MySQL must first establish a connection to the
server, and most programs also will specify which database to use. Some APIs
expect the database name to be supplied at connect time (which is why
connecting and selecting are covered in the same section). Others provide an
explicit call for selecting the database. In addition, well-behaved MySQL
programs close the connection to the server when they're done with it.
Checking for errors.
Many people write MySQL programs that perform no error checking at all,
which makes them difficult to debug when things go wrong. Any database
operation can fail and you should know how to find out when that occurs and
why.
Unit-II Notes

Issuing queries and retrieving results. 8


The whole point of connecting to a database server is to run queries. Each API
provides at least one way to issue queries, as well as several functions for
processing the results of queries. Because of the many options available to you.
Using prepared statements and placeholders in queries.
One way to write a query that refers to specific data values is to embed the
values directly in the query string. Most APIs provide another mechanism that
allows you to prepare a query in advance that refers to the data values
symbolically. When you execute the statement, you supply the data values
separately and the API places them into the query string for you.
Including special characters and NULL values in queries.
Some characters such as quotes and backslashes have special meaning in
queries, and you must take certain precautions when constructing queries
containing them. The same is true for NULL values. If you do not handle these
properly, your programs may generate SQL statements that are erroneous or
that yield unexpected results.
Handling NULL values in result sets.
NULL values are special not only when you construct queries, but in results
returned from queries. Each API provides a convention for dealing with them.

Connecting to the MySQL Server, Selecting a Database, and Disconnecting


Each API provides functions for connecting and disconnecting. The connection
routines require that you provide parameters specifying the MySQL user
account you want to use. You can also specify a database to use.
The programs in this section show how to perform three fundamental
operations that are common to the vast
majority of MySQL programs:
Establishing a connection to the MySQL server.
Every program that uses MySQL does this, no matter which API you use. The
details on specifying
connection parameters vary between APIs, and some APIs provide more
flexibility than others. However,
there are many common elements. For example, you must specify the host
where the server is running, as
well as the name and password for the MySQL account that you're using to
access the server.
Selecting a database.
Most MySQL programs select a database, either when they connect to the
server or immediately thereafter.
Disconnecting from the server
Each API provides a means of shutting down an open connection. It's best to
close the connection as soon as you're done with the server so that it can free
up any resources that are allocated to servicing the connection. Otherwise, if
your program performs additional computations after accessing the server, the
connection will be held open longer than necessary. It's also preferable to close
the connection explicitly. If a program simply terminates without closing the
Unit-II Notes

connection, the MySQL server eventually notices, but shutting down the 9
connection explicitly allows the server to perform an orderly close on its end
immediately.

Record Selection Techniques


Specifying Which Columns to Display
To indicate what kind of information you want to see from a table, name a
column or a list of columns and the table to use. The easiest way to select
output columns is to use the * specifier, which is a shortcut for naming all the
columns in a table:
SELECT * FROM `student`
id name clas mar
s k
1 John Four 75
Deo
2 Max Thre 85
Ruin e
That's all to get all the records from the table student. We have not placed any
restriction here and asked for all the fields with all the records. Now if we want
to restrict our results and get only name field from the table.
SELECT name FROM `student`
This will return only name field from the table. We can ask for more fields and
all field names we have to separate by comma. We can include as many field
names we want from a table.
SELECT name, class FROM `student`

Giving Names to Output Columns


Whenever you retrieve a result set, MySQL gives every output column a name.
MySQL assigns default names to output columns, but if the defaults are not
suitable, you can use column aliases to specify your own names.
To give a result set column a name of your own choosing, use AS name to
specify a column alias. The following query retrieves the same result as the
previous one, but renames the first column to date_sent:
mysql> SELECT
-> DATE_FORMAT(t,'%M %e, %Y') AS date_sent,
-> srcuser, size FROM mail;
+--------------+---------+---------+
| date_sent | srcuser | size |
+--------------+---------+---------+
| May 11, 2001 | barb | 58274 |
| May 12, 2001 | tricia | 194925 |
Unit-II Notes

Combining Columns to Construct Composite Values 10


One way to do this is to use CONCAT( ).
Column values may be combined to produce composite output values. For
example, this expression concatenates srcuser and srchost values into email
address format:

CONCAT(srcuser,'@',srchost)

How do I select specific records?


The statement below will select all columns (*) from the tablename you specify,
where the column you specify contains the value you specify.
SELECT * FROM tablename WHERE column = ''
When specifing value, be sure that unless the values are numbers, that you
quote them. You may also want to quote the value so that any quotes within
the value are escaped. Here's two more examples.
SELECT * FROM tablename WHERE age > 40 && age < 50

SELECT * FROM tablename WHERE name = 'John'

mysql> SELECT t, srcuser, srchost FROM mail WHERE srchost LIKE 's%';
+---------------------+---------+---------+
| t | srcuser | srchost |
+---------------------+---------+---------+
| 2001-05-11 10:15:08 | barb | saturn |
| 2001-05-13 13:59:18 | barb | saturn |
| 2001-05-14 17:03:01 | tricia | saturn |

Queries such as the preceding one that test a given column to see if it has any
of several different values often can be written more easily by using the IN( )
operator. IN( ) is true if the column is equal to any value in its argument list:
mysql> SELECT t, srcuser, dstuser FROM mail
-> WHERE srcuser IN ('gene','barb','phil');
+---------------------+---------+---------+
| t | srcuser | dstuser |
+---------------------+---------+---------+
| 2001-05-11 10:15:08 | barb | tricia |
| 2001-05-12 15:02:49 | phil | phil |

Displaying Comparisons to Find Out How Something Works


You're curious about how a comparison in a WHERE clause works.
Solution
Display the result of the comparison to get more information about it. This is a
useful diagnostic or debugging technique.
Sometimes it's desirable to see the result of the comparison itself. To do this,
just put the comparison expression in the output column list, perhaps
including the values that you're comparing as well:
Unit-II Notes

mysql> SELECT srcuser, srcuser < 'c', size, size > 5000 FROM mail; 11
+---------+---------------+---------+-------------+
| srcuser | srcuser < 'c' | size | size > 5000 |
+---------+---------------+---------+-------------+
| barb | 1 | 58274 | 1 |
| tricia | 0 | 194925 | 1 |
| phil | 0 | 1048 | 0 |
| barb | 1 | 271 | 0 |

Reversing or Negating Query Conditions


You know how to write a query to answer a given question; now you want to
ask the opposite question.
Solution
Reverse the conditions in the WHERE clause by using negation operators.
A more complex query using two conditions might ask when people sent mail
to themselves on the same machine:
mysql> SELECT * FROM mail WHERE srcuser = dstuser AND srchost =
dsthost;
+---------------------+---------+---------+---------+---------+-------+
| t | srcuser | srchost | dstuser | dsthost | size |
+---------------------+---------+---------+---------+---------+-------+
| 2001-05-14 14:42:21 | barb | venus | barb | venus | 98151 |
| 2001-05-15 08:50:57 | phil | venus | phil | venus | 978 |
+---------------------+---------+---------+---------+---------+-------+
Reversing the conditions for this query involves not only changing the =
operators to !=, but changing the AND to OR:
mysql> SELECT * FROM mail WHERE srcuser != dstuser OR srchost !=
dsthost;
+---------------------+---------+---------+---------+---------+---------+
| t | srcuser | srchost | dstuser | dsthost | size |
+---------------------+---------+---------+---------+---------+---------+
| 2001-05-11 10:15:08 | barb | saturn | tricia | mars | 58274 |
| 2001-05-12 12:48:13 | tricia | mars | gene | venus | 194925 |
You may find it easier just to put the entire original expression in parentheses
and negate the whole thing with NOT:
mysql> SELECT * FROM mail WHERE NOT (srcuser = dstuser AND srchost
= dsthost);
+---------------------+---------+---------+---------+---------+---------+
| t | srcuser | srchost | dstuser | dsthost | size |
+---------------------+---------+---------+---------+---------+---------+
| 2001-05-11 10:15:08 | barb | saturn | tricia | mars | 58274 |
| 2001-05-12 12:48:13 | tricia | mars | gene | venus | 194925 |
Removing Duplicate Rows
Output from a query contains duplicate records. You want to eliminate them.
Solution
Unit-II Notes

Some queries produce results containing duplicate records. For example, to see 12
who sent mail, you could query the mail table like this:
mysql> SELECT srcuser FROM mail;
+---------+
| srcuser |
+---------+
| barb |
| tricia |
| phil |
| barb |
| gene |
| phil |
| barb |
| tricia |
| gene |

But that result is heavily redundant. Adding DISTINCT to the query removes
the duplicate records, producing a set of unique values:
mysql> SELECT DISTINCT srcuser FROM mail;
+---------+
| srcuser |
+---------+
| barb |
| tricia |
| phil |
| gene |
+---------+

Sorting a Result Set


Your query results aren't sorted the way you want.

Solution

When you select rows, the MySQL server is free to return them in any order,
unless you instruct it otherwise by saying how to sort the result. There are lots
of ways to use sorting techniques. Sort a result set by adding an ORDER BY
clause that names the column or columns you want to sort by:

mysql> SELECT * FROM mail WHERE size > 100000 ORDER BY size;

+---------------------+---------+---------+---------+---------+

| t | srcuser | srchost | dstuser | dsthost | size |

+---------------------+---------+---------+---------+---------+
Unit-II Notes

| 2001-05-12 12:48:13 | tricia | mars | gene | venus | 194925 | 13


| 2001-05-15 10:25:52 | gene | mars | tricia | saturn | 998532 |

To sort a column in reverse (descending) order, add the keyword DESC after its
name in the ORDER BY clause:

mysql> SELECT * FROM mail WHERE size > 50000 ORDER BY size DESC;

+---------------------+---------+---------+---------+-

| t | srcuser | srchost | dstuser | dsthost | size |

+---------------------+---------+---------+---------+------

| 2001-05-14 17:03:01 | tricia | saturn | phil | venus | 2394482 |

| 2001-05-15 10:25:52 | gene | mars | tricia | saturn | 998532 |

Selecting Records from the Beginning or End of a Result Set

You want to see only certain rows from a result set, like the first one or the last
five. MySQL supports a LIMIT clause that tells the server to return only part of
a result set. LIMIT is a MySQL-specific extension to SQL that is extremely
valuable when your result set contains more rows than you want to see at a
time.

To select the first n records of a query result, add LIMIT n to the end of your
SELECT statement:

mysql> SELECT * FROM profile LIMIT 1;

+----+------+------------+-------+----------------------+------+

| id | name | birth | color | foods | cats |

+----+------+------------+-------+----------------------+------+

| 1 | Fred | 1970-04-13 | black | lutefisk,fadge,pizza | 0 |

LIMIT n tells the server to return the first n rows of a result set. LIMIT also has
a two-argument form that allows you to pick out any arbitrary section of rows
from a result. The arguments indicate how many rows to skip and how many to
return.

mysql> SELECT * FROM profile ORDER BY birth LIMIT 2,1;


Unit-II Notes

+----+------+------------+-------+---------------+------+ 14
| id | name | birth | color | foods | cats |

+----+------+------------+-------+---------------+------+

| 10 | Tony | 1960-05-01 | white | burrito,pizza | 0 |

+----+------+------------+-------+---------------+------+

Working with Strings


Like most data types, strings can be compared for equality or inequality or
relative ordering. However, strings have
some additional properties to consider:
Strings can be case sensitive (or not), which can affect the outcome of string
operations.
You can compare entire strings, or just parts of them by extracting
substrings.
You can apply pattern-matching operations to look for strings that have a
certain structure.

Types of Strings
MySQL can operate on regular strings or binary strings. "Binary" in this
context has little to do with the presence of non-ASCII values, so it's useful
right at the outset to make a distinction:
Binary data may contain bytes that lie outside the usual range of printable
ASCII characters.

A binary string in MySQL is one that MySQL treats as case sensitive in


comparisons. For binary strings, the characters A and a are considered
different. For non-binary strings, they're considered the same.

The following table, metal, is used in several sections of this chapter:


mysql> SELECT * FROM metal;
+----------+
| name |
+----------+
| copper |
| gold |
| iron |
| lead |
| mercury |
| platinum |
| silver |
| tin |
+----------+
Unit-II Notes

Writing Strings That Include Quotes or Special Characters 15


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
You can deal with this several ways:
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 |
+------------+
This works in reverse, too; a string containing double quotes can be enclosed
within single quotes:
mysql> SELECT 'He said, "Boo!"';
+-----------------+
| He said, "Boo!" |
+-----------------+
| He said, "Boo!" |
To include a quote character within a string that is quoted by the same kind
of quote, either double the quote or precede it with a backslash. When MySQL
reads the query string, it will strip off the extra quote or the backslash:
mysql> SELECT 'I''m asleep', 'I\'m wide awake';
+------------+----------------+
| I'm asleep | I'm wide awake |
+------------+----------------+
| I'm asleep | I'm wide awake |
+------------+----------------+
1 row in set (0.00 sec)
A backslash turns off the special meaning of the following character. (It causes
a temporary escape from normal string processing rules, so sequences such as
\' and \" are called escape sequences.) This means that backslash itself is
special, so to write a literal backslash within a string, you must double it:
mysql> SELECT 'Install MySQL in C:\\mysql on Windows';
Unit-II Notes

+--------------------------------------+ 16
| Install MySQL in C:\mysql on Windows |
+--------------------------------------+
| Install MySQL in C:\mysql on Windows |
+--------------------------------------+
Other escape sequences recognized by MySQL are \b (backspace), \n (newline,
also called linefeed), \r (carriage return), \t (tab), and \0 (ASCII NUL).

Decomposing or Combining Strings


To obtain a piece of a string, use a substring-extraction function. To combine
strings, use CONCAT( ).
Parts of strings can be extracted and displayed. For example, LEFT( ), MID( ),
and 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;
+----------+--------------+---------------+---------------+
| name | LEFT(name,2) | MID(name,3,1) | RIGHT(name,3) |
+----------+--------------+---------------+---------------+
| copper co p per
| gold go l old
| iron ir o ron
| lead le a ead

For LEFT( ) and RIGHT( ), the second argument indicates how many characters
to return from the left or right end of the string. For MID( ), the second
argument is the starting position of the substring you want (beginning from 1)
and the third argument indicates how many characters to return.
The SUBSTRING( ) function takes a string and a starting position, returning
everything to the right of the position.

mysql> SELECT name, SUBSTRING(name,4), MID(name,4) FROM metal;


+----------+-------------------+-------------+
| name | SUBSTRING(name,4) | MID(name,4) |
+----------+-------------------+-------------+
| copper per per
| gold d d
| iron n n
| lead d d

To return everything to the right or left of a given character, use


SUBSTRING_INDEX(str,c,n). It searches into a string str for the n-th occurrence
of the character c and returns everything to its left. If n is negative, the search
for c starts from the right and returns everything to the right of the character:
mysql> SELECT name,
-> SUBSTRING_INDEX(name,'r',2),
Unit-II Notes

-> SUBSTRING_INDEX(name,'i',-1) 17
-> FROM metal;
+----------+-----------------------------+------------------------------+
| name | SUBSTRING_INDEX(name,'r',2) | SUBSTRING_INDEX(name,'i',-1)
|
+----------+-----------------------------+------------------------------+
| copper copper copper
| gold gold gold
| iron iron ron
| lead lead lead
mercury mercu mercury

To combine strings rather than pull them apart, use the CONCAT( ) function. It
concatenates all its arguments and returns the result:
mysql> SELECT CONCAT('Hello, ',USER( ),', welcome to MySQL!') AS
greeting;
+------------------------------------------+
| greeting |
+------------------------------------------+
| Hello, paul@localhost, welcome to MySQL! |
+------------------------------------------+

Checking Whether a String Contains a Substring


The group of location and position functions is useful for finding parts of
strings within other strings. The LOCATE() function returns the position of the
first occurrence of a given substring within the target string. For example, you
can look for a needle in a haystack:

mysql> select locate('needle', 'haystackneedlehaystack');


+--------------------------------------------+
| LOCATE('needle', 'haystackneedlehaystack') |
+--------------------------------------------+
| 9|
+--------------------------------------------+
1 row in set (0.00 sec)
The substring needle begins at position 9 in the target string. If the substring
cannot be found in the target string, MySQL returns 0 as a result.
An extension of the LOCATE() function is to use a third argument for starting
position. If you start looking for needle in haystack before position 9, you'll
receive a result. Otherwise, because needle starts at position 9, you'll receive a
0 result if you specify a greater starting position:
mysql> select locate('needle', 'haystackneedlehaystack',6);
+----------------------------------------------+
| LOCATE('needle', 'haystackneedlehaystack',9) |
+----------------------------------------------+
| 9
Unit-II Notes

+----------------------------------------------+ 18
1 row in set (0.00 sec)
mysql> select locate('needle', 'haystackneedlehaystack',12);
+-----------------------------------------------+
| LOCATE('needle', 'haystackneedlehaystack',12)
+-----------------------------------------------+
| 0
+-----------------------------------------------+
1 row in set (0.00 sec)

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. Patterns may contain two
special metacharacters: _ matches any single character, and % matches any
sequence of characters, including the empty string. You can use these
characters to create patterns that match a wide variety of values:
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:
mysql> SELECT name FROM metal WHERE name LIKE '%er%';
+---------+
| name |
+---------+
| copper |
| mercury |
| silver |
+---------+
Strings that contain a substring at a specific position (the pattern matches only
if pp occurs at the third position of the name column):
mysql> SELECT name FROM metal where name LIKE '_ _pp%';
+--------+
| name |
+--------+
Unit-II Notes

| copper | 19
To reverse the sense of a pattern match, use NOT LIKE. The following query
finds strings that contain no i characters:
mysql> SELECT name FROM metal WHERE name NOT LIKE '%i%';
+---------+
| name |
+---------+
| copper |
| gold |
| lead |

Using Patterns with Non-String Values


Unlike some other databases, MySQL allows pattern matches to be applied to
numeric or date values, which can sometimes be useful. The following table
shows some ways to test a DATE value d using function calls that extract date
parts and using the equivalent pattern matches. The pairs of expressions
are true for dates occurring in the year 1976, in the month of April, or on the
first day of the month:
Function value test Pattern match test
YEAR(d) = 1976 d LIKE '1976-%'
MONTH(d) = 4 d LIKE '%-04-%'
DAYOFMONTH(d) = 1 d LIKE '%-01'

Pattern Matching with Regular Expressions


SQL patterns are likely to be implemented by other database systems, so
they're reasonably portable beyond MySQL. On the other hand, they're
somewhat limited. For example, you can easily write a SQL pattern %abc% to
find strings that contain abc, but you cannot write a single SQL pattern to
identify strings that contain any of the characters a, b, or c. Nor can you match
string content based on character types such as letters or digits. For such
operations, MySQL supports another type of pattern matching operation based
on regular expressions and the REGEXP operator.
Pattern What the pattern matches
^ Beginning of string
$ End of string
. Any single character
[...] Any character listed between the square
brackets
[^...] Any character not listed between the
square brackets
p1|p2|p3 Alternation; matches any of the patterns
p1, p2, or p3
* Zero or more instances of preceding
element
Unit-II Notes

+ One or more instances of preceding 20


element
{n} n instances of preceding element

Strings that begin with a particular substring:


mysql> SELECT name FROM metal WHERE name REGEXP '^co';
+--------+
| name |
+--------+
| copper |
+--------+
Strings that end with a particular substring:
mysql> SELECT name FROM metal WHERE name REGEXP 'er$';
+--------+
| name |
+--------+
| copper |
| silver |
+--------+
Strings that contain a particular substring at any position:
mysql> SELECT name FROM metal WHERE name REGEXP 'er';
+---------+
| name |
+---------+
| copper |
| mercury |
| silver |
+---------+
Strings that contain a particular substring at a specific position:
mysql> SELECT name FROM metal WHERE name REGEXP '^..pp';
+--------+
| name |
+--------+
| copper |
+--------+
MySQL's regular expression capabilities also support POSIX character classes.
These match specific character
sets, as described in the following table.
POSIX What the class matches
class
[:alnum:] Alphabetic and numeric
characters
[:alpha:] Alphabetic characters
[:digit:] Digits
[:graph:] Graphic (non-blank)
Unit-II Notes

characters 21
[: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)
POSIX classes are intended for use within character classes, so you use them
within square brackets. The
following expression matches values that contain any hexadecimal digit
character:
mysql> SELECT name, name REGEXP '[[:xdigit:]]' FROM metal;
+----------+----------------------------+
| name | name REGEXP '[[:xdigit:]]' |
+----------+----------------------------+
| copper |1
| gold |1
| iron |0

The following alternation matches strings that begin with a vowel or end with
er:
mysql> SELECT name FROM metal WHERE name REGEXP '^[aeiou]|er$';
+--------+
| name |
+--------+
| copper
| iron
| silver
+--------+

Working with Dates and Times


MySQL's Date and Time Formats
MySQL provides DATE and TIME column types for representing date and time
values separately, and a DATETIME type for combined date-and-time values.

These values have the following formats:


DATE values are handled as strings in CCYY-MM-DD format, where CC, YY,
MM, and DD represent the century, year within century, month, and day parts
of the date.
Unit-II Notes

TIME values are represented as strings in hh:mm:ss format, where hh, mm, 22
and ss are the hours, minutes, and seconds parts of the time. TIME values
often can be thought of as time-of-day values, but MySQL actually treats them
as elapsed time. Thus, they may be greater than 23:59:59 or even negative.
(The actual range is -838:59:59 to 838:59:59.)

DATETIME values are represented as combined date-and-time strings in


CCYY-MM-DD hh:mm:ss format.

TIMESTAMP values also include date and time parts, but are represented as
strings in CCYYMMDDhhmmss format.

Date and Time Functions


Name Description
ADDDATE() Add time values (intervals) to a date value
ADDTIME() Add time
CURDATE() Return the current date
CURTIME() Return the current time
DATE_ADD() Add time values (intervals) to a date value
DATE_FORMAT() Format date as specified
DATE_SUB() Subtract a time value (interval) from a date
DATE() Extract the date part of a date or datetime expression
DATEDIFF() Subtract two dates
DAYNAME() Return the name of the weekday
DAYOFMONTH() Return the day of the month (0-31)
DAYOFWEEK() Return the weekday index of the argument
DAYOFYEAR() Return the day of the year (1-366)
EXTRACT() Extract part of a date
FROM_DAYS() Convert a day number to a date
FROM_UNIXTIM
Format UNIX timestamp as a date
E()
GET_FORMAT() Return a date format string
HOUR() Extract the hour
LAST_DAY Return the last day of the month for the argument
MAKEDATE() Create a date from the year and day of year
MAKETIME MAKETIME()
MICROSECOND(
Return the microseconds from argument
)
MINUTE() Return the minute from the argument
MONTH() Return the month from the date passed
MONTHNAME() Return the name of the month
NOW() Return the current date and time
Unit-II Notes

Name Description 23
PERIOD_ADD() Add a period to a year-month
QUARTER() Return the quarter from a date argument
SEC_TO_TIME() Converts seconds to 'HH:MM:SS' format
SECOND() Return the second (0-59)
STR_TO_DATE() Convert a string to a date
SUBTIME() Subtract times
SYSDATE() Return the time at which the function executes
TIME_FORMAT() Format as time
TIME_TO_SEC() Return the argument converted to seconds
TIME() Extract the time portion of the expression passed
TIMEDIFF() Subtract time
With a single argument, this function returns the date or datetime
TIMESTAMP()
expression; with two arguments, the sum of the arguments
TIMESTAMPAD
Add an interval to a datetime expression
D()
TIMESTAMPDIF
Subtract an interval from a datetime expression
F()
TO_DAYS() Return the date argument converted to days
TO_SECONDS() Return the date or datetime argument converted to seconds since Year 0
UNIX_TIMESTA
Return a UNIX timestamp
MP()
WEEK() Return the week number
WEEKDAY() Return the weekday index
WEEKOFYEAR() Return the calendar week of the date (0-53)
YEAR() Return the year
YEARWEEK() Return the year and week
ADDTIME(expr1,expr2)
ADDTIME() adds expr2 to expr1 and returns the result. expr1 is a time or
datetime expression, and expr2 is a time expression.
mysql> SELECT ADDTIME('2007-12-31 23:59:59.999999', '1
1:1:1.000002');
-> '2008-01-02 01:01:01.000001'
mysql> SELECT ADDTIME('01:00:00.999999', '02:00:00.999998');
-> '03:00:01.999997'
-> '2004-01-01 13:00:00'
CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format,
depending on whether the function is used in a string or numeric context.
mysql> SELECT CURDATE();
-> '2008-06-13'
mysql> SELECT CURDATE() + 0;
-> 20080613
Unit-II Notes

CURTIME() 24
Returns the current time as a value in 'HH:MM:SS' or HHMMSS.uuuuuu
format, depending on whether the function is used in a string or numeric
context. The value is expressed in the current time zone.
mysql> SELECT CURTIME();
-> '23:50:26'
mysql> SELECT CURTIME() + 0;
-> 235026.000000
DATE(expr)
Extracts the date part of the date or datetime expression expr.
mysql> SELECT DATE('2003-12-31 01:02:03');
-> '2003-12-31'
DATEDIFF(expr1,expr2)
DATEDIFF() returns expr1 expr2 expressed as a value in days from one date
to the other. expr1 and expr2 are date or date-and-time expressions. Only the
date parts of the values are used in the calculation.
mysql> SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30');
-> 1
mysql> SELECT DATEDIFF('2010-11-30 23:59:59','2010-12-31');
-> -31

DATE_FORMAT(date,format)
Formats the date value according to the format string.
The following specifiers may be used in the format string. The % character is
required before format specifier characters.
Specifi
Description
er
%a Abbreviated weekday name (Sun..Sat)
%b Abbreviated month name (Jan..Dec)
%c Month, numeric (0..12)
%D Day of the month with English suffix (0th, 1st, 2nd, 3rd, )
%d Day of the month, numeric (00..31)
%e Day of the month, numeric (0..31)
%f Microseconds (000000..999999)
%H Hour (00..23)
%h Hour (01..12)
%I Hour (01..12)
%i Minutes, numeric (00..59)
%j Day of year (001..366)
%k Hour (0..23)
%l Hour (1..12)
%M Month name (January..December)
%m Month, numeric (00..12)
Unit-II Notes

Specifi 25
Description
er
%p AM or PM
%r Time, 12-hour (hh:mm:ss followed by AM or PM)
%S Seconds (00..59)
%s Seconds (00..59)
%T Time, 24-hour (hh:mm:ss)
%U Week (00..53), where Sunday is the first day of the week
%u Week (00..53), where Monday is the first day of the week
%V Week (01..53), where Sunday is the first day of the week; used with %X
%v Week (01..53), where Monday is the first day of the week; used with %x
%W Weekday name (Sunday..Saturday)
%w Day of the week (0=Sunday..6=Saturday)
Year for the week where Sunday is the first day of the week, numeric, four
%X
digits; used with %V
Year for the week, where Monday is the first day of the week, numeric, four
%x
digits; used with %v
%Y Year, numeric, four digits
%y Year, numeric (two digits)
%% A literal % character
%x x, for any x not listed above

mysql> SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y');


-> 'Sunday October 2009'
mysql> SELECT DATE_FORMAT('2007-10-04 22:23:00', '%H:%i:%s');
-> '22:23:00'
mysql> SELECT DATE_FORMAT('1900-10-04 22:23:00',
-> '%D %y %a %d %m %b %j');
-> '4th 00 Thu 04 10 Oct 277'
mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00',
-> '%H %k %I %r %T %S %w');
-> '22 22 10 10:23:00 PM 22:23:00 00 6'
mysql> SELECT DATE_FORMAT('1999-01-01', '%X %V');
-> '1998 52'
mysql> SELECT DATE_FORMAT('2006-06-00', '%d');
-> '00'
DAYNAME(date)
Returns the name of the weekday for date. The language used for the name is
controlled by the value of the lc_time_names system variable
mysql> SELECT DAYNAME('2007-02-03');
-> 'Saturday'
Unit-II Notes

DAYOFMONTH(date) 26
Returns the day of the month for date, in the range 1 to 31, or 0 for dates such
as '0000-00-00' or '2008-00-00' that have a zero day part.
mysql> SELECT DAYOFMONTH('2007-02-03');
-> 3
DAYOFWEEK(date)
Returns the weekday index for date (1 = Sunday, 2 = Monday, , 7 = Saturday).
These index values correspond to the ODBC standard.
mysql> SELECT DAYOFWEEK('2007-02-03');
-> 7
DAYOFYEAR(date)
Returns the day of the year for date, in the range 1 to 366.
mysql> SELECT DAYOFYEAR('2007-02-03');
-> 34
EXTRACT(unit FROM date)
The EXTRACT() function uses the same kinds of unit specifiers as DATE_ADD() or
DATE_SUB(), but extracts parts from the date rather than performing date
arithmetic.
mysql> SELECT EXTRACT(YEAR FROM '2009-07-02');
-> 2009
mysql> SELECT EXTRACT(YEAR_MONTH FROM '2009-07-02 01:02:03');
-> 200907
mysql> SELECT EXTRACT(DAY_MINUTE FROM '2009-07-02 01:02:03');
-> 20102
mysql> SELECT EXTRACT(MICROSECOND
-> FROM '2003-01-02 10:30:00.000123');
-> 123
FROM_DAYS(N)
Given a day number N, returns a DATE value.
mysql> SELECT FROM_DAYS(730669);
-> '2007-07-03'
LAST_DAY(date)
Takes a date or datetime value and returns the corresponding value for the last
day of the month. Returns NULL if the argument is invalid.
mysql> SELECT LAST_DAY('2003-02-05');
-> '2003-02-28'
mysql> SELECT LAST_DAY('2004-02-05');
-> '2004-02-29'
mysql> SELECT LAST_DAY('2004-01-01 01:01:01');
-> '2004-01-31'
mysql> SELECT LAST_DAY('2003-03-32');
-> NULL
MAKEDATE(year,dayofyear)
Returns a date, given year and day-of-year values. dayofyear must be greater
than 0 or the result is NULL.
Unit-II Notes

mysql> SELECT MAKEDATE(2011,31), MAKEDATE(2011,32); 27


-> '2011-01-31', '2011-02-01'
mysql> SELECT MAKEDATE(2011,365), MAKEDATE(2014,365);
-> '2011-12-31', '2014-12-31'
mysql> SELECT MAKEDATE(2011,0);
-> NULL
MAKETIME(hour,minute,second)
Returns a time value calculated from the hour, minute, and second arguments.
mysql> SELECT MAKETIME(12,15,30);
-> '12:15:30'
MINUTE(time)
Returns the minute for time, in the range 0 to 59.
mysql> SELECT MINUTE('2008-02-03 10:05:03');
-> 5
MONTH(date)
Returns the month for date, in the range 1 to 12 for January to December, or 0
for dates such as '0000-00-00' or '2008-00-00' that have a zero month part.
mysql> SELECT MONTH('2008-02-03');
-> 2
MONTHNAME(date)
Returns the full name of the month for date. The language used for the name is
controlled by the value of the lc_time_names system variable (Section 9.7,
MySQL Server Locale Support).
mysql> SELECT MONTHNAME('2008-02-03');
-> 'February'
NOW()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is
used in a string or numeric context. The value is expressed in the current time
zone.
mysql> SELECT NOW();
-> '2007-12-15 23:50:26'
mysql> SELECT NOW() + 0;
-> 20071215235026.000000
TIME_FORMAT(time,format)
This is used like the DATE_FORMAT() function, but the format string may
contain format specifiers only for hours, minutes, seconds, and microseconds.
Other specifiers produce a NULL value or 0.
If the time value contains an hour part that is greater than 23, the %H and %k
hour format specifiers produce a value larger than the usual range of 0..23.
The other hour format specifiers produce the hour value modulo 12.
mysql> SELECT TIME_FORMAT('100:00:00', '%H %k %h %I %l');
-> '100 100 04 04 4'
TIME_TO_SEC(time)
Returns the time argument, converted to seconds.
Unit-II Notes

mysql> SELECT TIME_TO_SEC('22:23:00'); 28


-> 80580
mysql> SELECT TIME_TO_SEC('00:39:38');
-> 2378
TO_DAYS(date)
Given a date date, returns a day number (the number of days since year 0).
mysql> SELECT TO_DAYS(950501);
-> 728779
mysql> SELECT TO_DAYS('2007-10-07');
-> 733321
mysql> SELECT TO_DAYS('0000-00-00');
+-----------------------+
| to_days('0000-00-00') |
+-----------------------+
| NULL |
+-----------------------+
1 row in set, 1 warning (0.00 sec)

mysql> SHOW WARNINGS;


+---------+------+----------------------------------------+
| Level | Code | Message |
+---------+------+----------------------------------------+
| Warning | 1292 | Incorrect datetime value: '0000-00-00' |
+---------+------+----------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT TO_DAYS('0000-01-01');


+-----------------------+
| to_days('0000-01-01') |
+-----------------------+
| 1|
+-----------------------+
1 row in set (0.00 sec)
This is true whether or not the ALLOW_INVALID_DATES SQL server mode is
enabled.
TO_SECONDS(expr)
Given a date or datetime expr, returns a the number of seconds since the year
0. If expr is not a valid date or datetime value, returns NULL.
mysql> SELECT TO_SECONDS(950501);
-> 62966505600
mysql> SELECT TO_SECONDS('2009-11-29');
-> 63426672000
mysql> SELECT TO_SECONDS('2009-11-29 13:43:32');
-> 63426721412
mysql> SELECT TO_SECONDS( NOW() );
Unit-II Notes

-> 63426721458 29
WEEK(date[,mode])
This function returns the week number for date. The two-argument form of
WEEK() enables you to specify whether the week starts on Sunday or Monday
and whether the return value should be in the range from 0 to 53 or from 1 to
53. The following table describes how the mode argument works.
Mod First day of Rang Week 1 is the first week
e week e
0 Sunday 0-53 with a Sunday in this year
with more than 3 days
1 Monday 0-53
this year
2 Sunday 1-53 with a Sunday in this year
with more than 3 days
3 Monday 1-53
this year
with more than 3 days
4 Sunday 0-53
this year
5 Monday 0-53 with a Monday in this year
with more than 3 days
6 Sunday 1-53
this year
7 Monday 1-53 with a Monday in this year
mysql> SELECT WEEK('2008-02-20');
-> 7
mysql> SELECT WEEK('2008-02-20',0);
-> 7
mysql> SELECT WEEK('2008-02-20',1);
-> 8
mysql> SELECT WEEK('2008-12-31',1);
-> 53
WEEKDAY(date)
Returns the weekday index for date (0 = Monday, 1 = Tuesday, 6 = Sunday).
mysql> SELECT WEEKDAY('2008-02-03 22:23:00');
-> 6
mysql> SELECT WEEKDAY('2007-11-06');
-> 1
WEEKOFYEAR(date)
Returns the calendar week of the date as a number in the range from 1 to 53.
WEEKOFYEAR() is a compatibility function that is equivalent to WEEK(date,3).
mysql> SELECT WEEKOFYEAR('2008-02-20');
-> 8
YEAR(date)
Returns the year for date, in the range 1000 to 9999, or 0 for the zero date.
mysql> SELECT YEAR('1987-01-01');
-> 1987
YEARWEEK(date), YEARWEEK(date,mode)
Unit-II Notes

Returns year and week for a date. The mode argument works exactly like the 30
mode argument to WEEK(). The year in the result may be different from the
year in the date argument for the first and the last week of the year.
mysql> SELECT YEARWEEK('1987-01-01');
-> 198653

Sorting Query Results


Using ORDER BY to Sort Query Results
ORDER BY has the following general characteristics:
You can sort using a single column of values or multiple columns
You can sort any column in either ascending order (the default) or descending
order
You can refer to sort columns by name, by their position within the output
column list, or by using an alias

Here are animal birthdays, sorted by date:


mysql> SELECT name, birth FROM pet ORDER BY birth;
+----------+------------+
| name | birth |
+----------+------------+
| Buffy | 1989-05-13 |
| Bowser | 1989-08-31 |
| Fang | 1990-08-27 |
| Fluffy | 1993-02-04 |
| Claws | 1994-03-17 |
| Slim | 1996-04-29 |

The default sort order is ascending, with smallest values first. To sort in reverse
(descending) order, add the DESC keyword to the name of the column you are
sorting by:
mysql> SELECT name, birth FROM pet ORDER BY birth DESC;
+----------+------------+
| name | birth |
+----------+------------+
| Puffball | 1999-03-30 |
| Chirpy | 1998-09-11 |
| Whistler | 1997-12-09 |
| Slim | 1996-04-29 |
+----------+------------+
You can sort on multiple columns, and you can sort different columns in
different directions. For example,
mysql> SELECT name, species, birth FROM pet
-> ORDER BY species, birth DESC;
+----------+---------+------------+
| name | species | birth |
Unit-II Notes

+----------+---------+------------+ 31
| Chirpy | bird | 1998-09-11 |
| Whistler | bird | 1997-12-09 |
| Claws | cat | 1994-03-17 |
| Fluffy | cat | 1993-02-04 |
+----------+---------+------------+
The ORDER BY clauses in the queries shown thus far refer to the sorted
columns by name. You can also name the columns by their positions within
the output column list or by using aliases. Positions within the output list
begin with 1. The following query sorts results by the third output column,
miles:
mysql> SELECT name, trav_date, miles FROM driver_log ORDER BY 3;
+-------+------------+-------+
| name | trav_date | miles |
+-------+------------+-------+
| Ben | 2001-12-02 | 79 |
| Henry | 2001-11-27 | 96 |
| Henry | 2001-11-26 | 115 |
If an output column has an alias, you can refer to the alias in the ORDER BY
clause:
mysql> SELECT name, trav_date, miles AS distance FROM driver_log
-> ORDER BY distance;
+-------+------------+----------+
| name | trav_date | distance |
+-------+------------+----------+
| Ben | 2001-12-02 | 79 |
| Henry | 2001-11-27 | 96 |
| Henry | 2001-11-26 | 115 |

Sorting in User-Defined Orders


You want to define the sort order for all values in a column.
Solution
Use FIELD( ) to map column values onto a sequence that places the values in
the desired order.

FIELD( ) compares its first argument to the following arguments and returns a
number indicating which one of them it matches. 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)

The number of comparison values need not be four; FIELD( ) takes a variable-
length argument list. If value is NULL or none of the values match, FIELD( )
returns 0. FIELD( ) can be used to sort an arbitrary set of values into any order
Unit-II Notes

you please. For example, to display driver_log records for Henry, Suzi, and Ben, 32
in that order, do this:
mysql> SELECT * FROM driver_log
-> ORDER BY FIELD(name,'Henry','Suzi','Ben');
+--------+-------+------------+-------+
| rec_id | name | trav_date | miles |
+--------+-------+------------+-------+
| 3 | Henry | 2001-11-29 | 300 |
| 4 | Henry | 2001-11-27 | 96 |
| 2 | Suzi | 2001-11-29 | 391 |
| 7 | Suzi | 2001-12-02 | 502 |
| 1 | Ben | 2001-11-30 | 152 |
| 5 | Ben | 2001-11-29 | 131 |

Sorting ENUM Values


ENUM values don't sort like other string columns.
Solution
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. These numeric values affect how
enumerations are sorted, which can be very useful. Suppose you have a table
named weekday containing an enumeration column day that has weekday
names as its members:
CREATE TABLE weekday
(
day ENUM('Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday')
);
Internally, MySQL defines the enumeration values Sunday through Saturday to
have numeric values from 1 to 7. Make the insertion order differ from sorted
order (so you can see the effect of sorting), add
the days in random order:
mysql> INSERT INTO weekday (day) VALUES('Monday'),('Friday'),
-> ('Tuesday'), ('Sunday'), ('Thursday'), ('Saturday'), ('Wednesday');
Then select the values, both as strings and as the internal numeric value
mysql> SELECT day, day+0 FROM weekday;
+-----------+-------+
| day | day+0 |
+-----------+-------+
| Monday | 2 |
| Friday | 6 |
| Tuesday | 3 |
| Sunday | 1 |
| Thursday | 5 |
| Saturday | 7 |
| Wednesday | 4 |
Unit-II Notes

+-----------+-------+ 33
Notice that because the query includes no ORDER BY clause, the records are
returned in unsorted order. If you add an ORDER BY day clause, it becomes
apparent that MySQL uses the internal numeric values for sorting:
mysql> SELECT day, day+0 FROM weekday ORDER BY day;
+-----------+-------+
| day | day+0 |
+-----------+-------+
| Sunday | 1 |
| Monday | 2 |
| Tuesday | 3 |
| Wednesday | 4 |
| Thursday | 5 |
| Friday | 6 |
| Saturday | 7 |
+-----------+-------+
CONCAT( ) normally takes multiple arguments and concatenates them into a
single string. But it can be used with just a single argument, which is useful
when all you want is its behavior of producing a string result:
mysql> SELECT day, day+0 FROM weekday ORDER BY CONCAT(day);
+-----------+-------+
| day | day+0 |
+-----------+-------+
| Friday | 6 |
| Monday | 2 |
| Saturday | 7 |
| Sunday | 1 |
| Thursday | 5 |
| Tuesday | 3 |
| Wednesday | 4 |
+-----------+-------+

Generating Summaries
GROUP BY (Aggregate) Functions
Aggregate (GROUP BY) Functions
Name Description
Return the average value of the
AVG()
argument
BIT_AND() Return bitwise and
BIT_OR() Return bitwise or
BIT_XOR() Return bitwise xor
COUNT(DISTIN Return the count of a number of
CT) different values
COUNT() Return a count of the number of rows
Unit-II Notes

Name Description 34
returned
GROUP_CONC
Return a concatenated string
AT()
MAX() Return the maximum value
MIN() Return the minimum value
Return the population standard
STDDEV()
deviation
SUM() Return the sum
Return the population standard
VARIANCE()
variance
COUNT(expr)
Returns a count of the number of non-NULL values of expr in the rows
retrieved by a SELECT statement. The result is a BIGINT value.
COUNT() returns 0 if there were no matching rows.
mysql> SELECT student.student_name,COUNT(*)
-> FROM student,course
-> WHERE student.student_id=course.student_id
-> GROUP BY student_name;
COUNT(*) is somewhat different in that it returns a count of the number of
rows retrieved, whether or not they contain NULL values.
COUNT(*) is optimized to return very quickly if the SELECT retrieves from one
table, no other columns are retrieved, and there is no WHERE clause. For
example:
mysql> SELECT COUNT(*) FROM student;
This optimization applies only to MyISAM tables only, because an exact row
count is stored for this storage engine and can be accessed very quickly. For
transactional storage engines such as InnoDB and BDB, storing an exact row
count is more problematic because multiple transactions may be occurring,
each of which may affect the count.
MAX([DISTINCT] expr)
Returns the maximum value of expr. MAX() may take a string argument; in
such cases, it returns the maximum string value. See Section 7.5.3, How
MySQL Uses Indexes. The DISTINCT keyword can be used to find the
maximum of the distinct values of expr, however, this produces the same result
as omitting DISTINCT.
MAX() returns NULL if there were no matching rows.
mysql> SELECT student_name, MIN(test_score), MAX(test_score)
-> FROM student
-> GROUP BY student_name;
For MAX(), MySQL currently compares ENUM and SET columns by their string
value rather than by the string's relative position in the set. This differs from
how ORDER BY compares them. This is expected to be rectified in a future
MySQL release.
Unit-II Notes

MIN([DISTINCT] expr) 35
Returns the minimum value of expr. MIN() may take a string argument; in such
cases, it returns the minimum string value. See Section 7.5.3, How MySQL
Uses Indexes. The DISTINCT keyword can be used to find the minimum of the
distinct values of expr, however, this produces the same result as omitting
DISTINCT.
MIN() returns NULL if there were no matching rows.
mysql> SELECT student_name, MIN(test_score), MAX(test_score)
-> FROM student
-> GROUP BY student_name;
For MIN(), MySQL currently compares ENUM and SET columns by their string
value rather than by the string's relative position in the set. This differs from
how ORDER BY compares them. This is expected to be rectified in a future
MySQL release.

Group By
Now we are going to use the group by statement. The group by statement, as
said before, is especially useful for aggregating, meaning to apply some
function. Let's see an example:

SELECT cust_id, SUM(total_price) FROM shopping GROUP BY cust_id

This query returns the total amount of money spent by each customer during
all their shoppings. The table returned looks like this:

cust_ SUM(total_pric
id e)
1 30
2 3
3 1

The way you have to understand the query is that we compute the sum of all
amounts for each customer. This is expressed by the GROUP BY cust_id. Now,
if we would try to do this for each product. This would correspond to the total
money gained per product. The query looks like this:

SELECT item, SUM(total_price) FROM shopping GROUP BY item

This query returns the following table:


Unit-II Notes

SUM(total_pric 36
item
e)
apple 7
balloon 1
pillow 25
plastic
1
bag

Generating and Using Sequences


Using AUTO_INCREMENT To Set Up a Sequence Column

You want to include a sequence column in a table.

Solution

Use an AUTO_INCREMENT column. Unique IDs would be helpful to make the


records distinct and to provide values that make each record easy to refer to.
An AUTO_INCREMENT column is good for this purpose, so a better insect table
has a structure like this:

CREATE TABLE insect

id INT UNSIGNED NOT NULL AUTO_INCREMENT,

PRIMARY KEY (id),

name VARCHAR(30) NOT NULL, # type of insect

date DATE NOT NULL, # date collected

origin VARCHAR(30) NOT NULL # where collected

);

To generate a new sequence value, insert NULL into the column, or just omit it
from your INSERT statement. Either way, MySQL will create a new sequence
number for you.

mysql> INSERT INTO insect (id,name,date,origin) VALUES


Unit-II Notes

-> (NULL,'housefly','2001-09-10','kitchen'), 37
-> (NULL,'millipede','2001-09-10','driveway'),

-> (NULL,'grasshopper','2001-09-10','front yard'),

-> (NULL,'stink bug','2001-09-10','front yard');

mysql> SELECT * FROM insect ORDER BY id;

+----+-------------------+------------+------------+

| id | name | date | origin |

+----+-------------------+------------+------------+

| 1 | housefly | 2001-09-10 | kitchen |

| 2 | millipede | 2001-09-10 | driveway |

| 3 | grasshopper | 2001-09-10 | front yard |

| 4 | stink bug | 2001-09-10 | front yard |

If the value is already present in the table, an error occurs:

mysql> INSERT INTO insect (id,name,date,origin) VALUES

-> (3,'cricket','2001-09-11','basement');

ERROR 1062 at line 1: Duplicate entry '3' for key 1

The AUTO_INCREMENT keyword informs MySQL that it should generate


successive sequence numbers for the column's values, but the other
information is important, too:

INT is the column's basic type. You need not necessarily use INT, but the
column must be one of the integer types: TINYINT, SMALLINT, MEDIUMINT,
INT, or BIGINT. It's important to remember that AUTO_INCREMENT is a
column attribute that should be applied only to integer types. Older versions of
MySQL will allow you to create an AUTO_INCREMENT column using non-
integer types such as CHAR, but bad things will happen if you do that. (Even if
the initial sequence numbers appear to be generated normally, sooner or later
the column will fail. A typical error is "duplicate key" after inserting a few
records, even when you know the column should be able to hold more
Unit-II Notes

numbers.) Save yourself some troublealways use an integer type for 38


AUTO_INCREMENT columns.

The column is declared as UNSIGNED. There's no need to allow negative


values, because AUTO_INCREMENT sequences consist only of positive integers
(normally beginning at 1). Furthermore, not declaring the column to be
UNSIGNED cuts the range of your sequence in half. For example, TINYINT has
a range of -128 to 127. Sequences include only positive values, so the range of
a TINYINT sequence would be 1 to 127. The range of an unsigned TINYINT
column is 0 to 255, which increases the upper end of the sequence to 255.

The maximum sequence value is determined by the specific integer type used,
so you should choose a type that is big enough to hold the largest value you'll
need. The maximum unsigned value of each integer type is shown in the
following table, which you can use to select an appropriate type.

Column Maximum unsigned


type value

TINYINT 255

SMALLINT 65,535

MEDIUMINT 16,777,215

INT 4,294,967,295

BIGINT 18,446,744,073,709,55
1,615

Sometimes people omit UNSIGNED so that they can create records that
contain negative numbers in the sequence column. (Using -1 to signify "has no
ID" would be an instance of this.) MySQL makes no guarantees about how
negative numbers will be treated, so you're playing with fire if you try to use
them in an AUTO_INCREMENT column. For example, if you resequence the
column, you'll find that all your negative values get turned into regular
(positive) sequence numbers.

AUTO_INCREMENT columns cannot contain NULL values, so id is declared


as NOT NULL. Current versions of MySQL automatically define
AUTO_INCREMENT columns as NOT NULL if you forget to. However, it's best to
indicate NOT NULL in the CREATE TABLE statement explicitly if there is a
possibility that you might use it with an older version of MySQL sometime.
Unit-II Notes

The column is declared as a PRIMARY KEY to ensure that its values are 39
unique. Tables can have only one PRIMARY KEY, so if the table already has
some other PRIMARY KEY column, you can declare an AUTO_INCREMENT
column to have a UNIQUE index instead:

id INT UNSIGNED NOT NULL AUTO_INCREMENT,UNIQUE (id)

Using LAST_INSERT_ID( ) to Obtain AUTO_INCREMENT Values

MySQL provides a LAST_INSERT_ID( ) function as a simpler way to obtain the


proper value. It returns the most recent AUTO_INCREMENT value that you
generated during the time you've been connected to the server. For example,
you can insert a record into the insect table, then retrieve its id value like this:

mysql> INSERT INTO insect (name,date,origin)

-> VALUES('cricket','2001-09-11','basement');

mysql> SELECT LAST_INSERT_ID( );

+------------------+

| last_insert_id( ) |

+------------------+

|9|

+------------------+

Reasons to Avoid Resequencing

Before deciding to resequence an AUTO_INCREMENT column, consider


whether you really want or need to do so. It's unnecessary in most cases. In
fact, renumbering a sequence sometimes can cause you real problems. For
example, you 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 properly
relate records in the two tables to each other.
Unit-II Notes

Reasons that people have for resequencing include the following: 40


Aesthetics.

Sometimes the desire to renumber a column is for aesthetic reasons. People


seem to prefer unbroken sequences to sequences with holes in them. If this is
why you want to resequence, there's probably not much I can say to convince
you otherwise. Nevertheless, it's not a particularly good reason.

Performance.

The impetus for resequencing may stem from the notion that doing so
"compacts" a sequence column by removing gaps and allows MySQL to run
queries more quickly. This is not true. MySQL doesn't care whether or not
there are holes, and there is no performance gain to be had by renumbering an

AUTO_INCREMENT column. In fact, resequencing affects performance


negatively in the sense that the table remains locked while MySQL performs
the operationwhich may take a non-trivial amount of time for a large table.
Other clients can read from the table while this is happening, but clients that
are trying to insert new rows must wait until the operation is complete.

Running out of numbers.

The upper limit of a sequence column is determined by the column's data type.
If an AUTO_INCREMENT sequence is approaching the upper limit of its column
type, renumbering packs the sequence and frees up more values at the top.
This may be a legitimate reason to resequence a column, but it is still
unnecessary in many cases to do so. You may be able to expand the column's
range to increase its upper limit, without changing the values stored in the
column.

Starting a Sequence at a Particular Value

Sequences start at 1, but you want to use a different starting value.

Solution

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.

By default, AUTO_INCREMENT sequences start at one:

mysql> CREATE TABLE t


Unit-II Notes

-> (id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id)); 41
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;

+----+

| id |

+----+

|1|

|2|

|3|

+----+

For MyISAM tables, you can begin the sequence at a specific initial value n by
including an AUTO_INCREMENT = n clause at the end of the CREATE TABLE
statement:

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);


Unit-II Notes

mysql> SELECT id FROM t ORDER BY id; 42


+-----+

| id |

+-----+

| 100 |

| 101 |

| 102 |

+-----+

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

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;

+-----+

| id |

+-----+

| 100 |

| 101 |

Das könnte Ihnen auch gefallen