Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Date and Time Functions

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 16
At a glance
Powered by AI
The key takeaways from the document are that MySQL has various functions for manipulating text, dates, times and performing calculations. It also discusses different types of joins and grouping records.

The different types of joins discussed in MySQL are inner joins, outer joins and full outer joins.

An inner join returns records that match between both tables while an outer join returns all records of the left table even if they don't match the right table. Outer joins can return unmatched records.

Text functions

The first group of functions to demonstrate are those meant for manipulating text.

CONCAT(), perhaps the most useful of the text functions, deserves special attention.
The CONCAT() function accomplishes concatenation, for which PHP uses the period.
The syntax for concatenation requires you to place, within parentheses, the various
values you want assembled, in order and separated by commas:
SELECT CONCAT(t1, t2) FROM tablename

While you canand normally willapply CONCAT() to columns, you can also
incorporate strings, entered within quotation marks.

For example, to format a persons name as first name<SPACE>last name, you would use

Because concatenation normally returns values in a new format, its an excellent time to
use an alias:

You can calculate the length with the LENGTH( ) function, as in the following:

CONCAT() has a corollary function called CONCAT_WS(), which stands for with
separator. The syntax is CONCAT_WS(separator, t1, t2, ). The separator will be
inserted between each of the listed columns or values.
For example, to format a persons full name as first name<SPACE>last name<SPACE>
you would write

CONCAT_WS() has an added advantage over CONCAT() in that it will ignore


columns with NULL values.

Besides the standard math operators that MySQL uses (for addition, subtraction,
multiplication, and division), there are a couple dozen functions for formatting and
performing calculations on numeric values.

Date and time functions

The date and time column types in MySQL are particularly flexible and useful. But
because many database users are not familiar with all of the available date and time
functions, these options are frequently underused.
Whether you want to make calculations based upon a date or return only the month
name from a value, MySQL has a function for that purpose.
MySQL supports two data types that store both a date and a time (DATETIME and
TIMESTAMP), one type that stores just the date (DATE), one that stores just the time
(TIME), and one that stores just a year (YEAR). Besides allowing for different types of
values, each data type also has its own unique behaviors
But MySQL is very flexible as to which functions you can use with which type. You can
apply a date function to any value that contains a date (i.e., DATETIME, TIMESTAMP,
and DATE), or you can apply an hour function to any value that contains the time
(i.e.,DATETIME, TIMESTAMP, and TIME). MySQL will use the part of the value that it
needs and ignore the rest.
What you cannot do, however, is apply a date function to a TIME value or a time function
to a DATE or YEAR value.

Display the date of birth in the persons table in ascending order.

The DATE() function returns the date part of a value. To see the date that the

Display the day of the week that the persons was born.

To show the current date and time, according to MySQL.

To show what date and time MySQL currently thinks it is, you can select the CURDATE()
and CURTIME() functions, which return these values. This is another example of a query
that can be run without referring to a particular table name.

To show the last day of the current month

As the last query showed, CURDATE() returns the current date on the server. This value
can be used as an argument to the LAST_DAY() function, which returns the last date in
the month for a given date. The MONTHNAME() function returns the name of the current
month.

The date and time returned by MySQLs date and time functions correspond to those on
the server, not on the client accessing the database.

ADDDATE(), SUBDATE(), ADDTIME(), and SUBTIME() can be used to perform


arithmetic on date and time values.

As of MySQL 5.0.2, the server will also prevent invalid dates (e.g., February 31, 2009)
from being inserted into a date or date/time column.

Formatting the date and time

There are two additional date and time functions that you might find yourself usingmore
than all of the others combined: DATE_FORMAT() and TIME_FORMAT().
There is some overlap between the two and when you would use one or the other.
DATE_FORMAT() can be used to format both the date and time if a value contains both
(e.g.,YYYY-MM-DD HH:MM:SS).
Comparatively,TIME_FORMAT() can format only the time value and must be used if only
the time value is being stored (e.g., HH:MM:SS).
The syntax is
SELECT DATE_FORMAT(datetime, formatting)
The formatting relies upon combinations of key codes and the percent sign to indicate
what values you want returned.
The following lists the available date- and time-formatting parameters. You can use these
in any combination, along with literal characters, such as punctuation, to return a date
and time in a more presentable form.

*_FORMAT( ) Parameters
Term
%e
%d
%D
%W
%a
%c

Usage
Day of the month
Day of the month, two digit
Day with suffix
Weekday name
Abbreviated
Month number

Example
1-31
01-31
1st-31st
Sunday-Saturday
Sun-Sat weekday name
1-12

%m
%M
%b
%Y
%y
%l
%h
%k
%H
%i
%S
%r
%T
%p

Month number, two digit


Month name
Month name, abbreviated
Year
Year
Hour (lowercase L)
Hour, two digit
Hour, 24-hour clock
Hour, 24-hour clock, two digit
Minutes
Seconds
Time
Time, 24-hour clock
AM or PM

01-12
January-December
Jan-Dec
2002
02
1-12
01-12
0-23
00-23
00-59
00-59
8:17:02 PM
20:17:02
AM or PM

Assuming that a column called the_date has the date and time of 2010-05-11 11:07:45
stored in it, common formatting tasks and results would be

Time (11:07:45 AM)


TIME_FORMAT(the_date, '%r')
Time without seconds (11:07 AM)
TIME_FORMAT(the_date, '%l:%i %p')
Date(May 11th, 2010)
DATE_FORMAT(the_date, '%M %D, %Y')
Return the current date and time as Month DD,YYYY - HH:MM

Display the current time, using 24-hour notation

To select the pid, plast_name and pdob, ordered by pdob, formatting the date as Weekday
(abbreviated) Month (abbreviated) Day Year, for the last 3 persons.

This is just one more example of how you can use these formatting functions to alter the
output of an SQL query.
In your Web applications, you should almost always use MySQL functions to format any
dates coming from the database.
The only way to access the date or time on the client (the users machine) is touse
JavaScript. It cannot be done with PHP or MySQL.

ROUND() will take one value, presumably from a column, and round that to a specified
number of decimal places. If no decimal places are indicated, it will round the number to
the nearest integer. If more decimal places are indicated than exist in the original number,
the remaining spaces are padded with zeros (to the right of the decimal point).

The RAND() function,as you might infer, isused for returning random numbers
SELECT RAND()
A further benefit to the RAND() function is that it can be used with your queries to return
the results in a random order.
SELECT * FROM tablename ORDER BY RAND

Sorting Records and Eliminating Duplicates

If youd like to see the data from your table ordered by a specific field, SQL offers the
ORDER BY clause.
This clause enables you to specify both the column name and the direction in which you
would like to see data (ASCending or DESCending).
The default order when using ORDER BY is ascending (abbreviated ASC), meaning that
numbers increase from small to large, dates go from older to most recent, and text is
sorted alphabetically. You can reverse this by specifying a descending order (abbreviated
DESC).
SELECT * FROM tablename ORDER BY column DESC

You can even order the returned values by multiple columns:


SELECT * FROM tablename ORDER BY column1, column2

You can, and frequently will, use ORDER BY with WHERE or other clauses. When doing
so, place the ORDER BY after the conditions:
SELECT * FROM tablename WHERE conditions ORDER BY column

Here is an example of sorting the persons table by last name, in ascending order:

Here is the same table sorted by date of birth, in descending order:

Because MySQL works naturally with any number of languages, the ORDER BY will be
based upon the collation being used
If the column that you choose to sort on contains NULL values, those will appear first,
both in ascending and descending order

To eliminate duplicate records in a table, add the DISTINCT keyword.

Select distinct * from tablename;


Consider the following example, which illustrates the use of this keyword by printing a list
of all the unique year values in the movies table:

Limiting Results

Another SQL clause that can be added to most queries is LIMIT.


In a SELECT query, WHERE dictates which records to return, and ORDER BY decides
how those records are sorted, but LIMIT states how many records to return.
It is used like so:
SELECT * FROM tablename LIMIT x

In such queries, only the initial x records from the query result will be returned.
To return only three matching records, use:

Using this format


SELECT * FROM tablename LIMIT x, y
you can have y records returned, startingat x.

To display 2 records starting at record 5.

Like arrays in PHP, result sets begin at 0 when it comes to LIMITs, so 6 is the 5 th record.

You can use LIMIT with WHERE and/or ORDER BY clauses, always placing LIMIT last.
SELECT which_columns FROM tablename WHERE conditions ORDER BY column
LIMIT x

The following examples list the three people (as per their birth dates) I the persons table.

The LIMIT x, y clause is most frequently used when paginating query results
A LIMIT clause does not improve the execution speed of a query, since MySQL still has to
assemble the entire result and then truncate the list. But a LIMIT clause will minimize the
amount of data to handle when it comes to the mysql client or your PHP scripts.
The LIMIT term is not part of the SQL standard and is therefore (sadly) not available on
all databases.
The LIMIT clause can be used with most types of queries, not just SELECTs.

Exercise
1. Create a database db2.
Create database db2;
2. Create the table movies.
Use db2;
Create table movies (
->mid int(11) unsigned not null auto_increment,
->mtitle varchar(255) not null default ,
->myear year(4) not null default 0000,
->primary key (mid));
3. Insert records on the table movies.
Insert into movies values (1, Rear Window, 1954);
Insert into movies values (2, To Catch a Thief, 1955);
Insert into movies values (3, The Maltese Falcon, 1941);
Insert into movies values (4, The Birds, 1963);
Insert into movies values (5, The Maltese Falcon, 1941);

3. Create the table persons.


Create table persons (
->pid int(11) not null auto_increment,
->pfirst_name varchar(25) not null,
->plast_name varchar(25) not null,
->psex enum(M,F) not null default M,
->pdob date not null,
->primary key(pid));
4. Insert records on the persons table.
Insert into persons values (1,Alfred,Hitchcock,M,1899-08-13);
Insert into persons values (2,Carry,Grant,M,1904-01-18);
Insert into persons values (3,Grace,Kelly,F,1929-11-12);
Insert into persons values (4,Humphrey,Bogart,M,1899-12-25);
Insert into persons values (5,Sydney,Greenstreet,M,1879-12-27);

5. Create the table roles.


Create table roles (
->mid int(11) not null default 0,
->pid int(11) not null default 0,
->role enum(A,D) not null default A,
->primary key(mid,pid,role));
6. Insert record on the table roles.
Insert into roles values (1,1,D);
Insert into roles values (1,3,A);
Insert into roles values (1,6,A);
Insert into roles values (2,1,D);
Insert into roles values (2,2,A);
Insert into roles values (2,3,A);
Insert into roles values (3,4,A);
Insert into roles values (3,5,A);
Insert into roles values (4,1,D);

Insert into roles values (5,1,D);


Insert into roles values (5,2,A);
Insert into roles values (6,4,A);

Grouping Records

You can group records on the basis of a specific field with MySQLs GROUP BY clause.
Each group created in this manner is treated as a single row, even though it internally
contains multiple records.
Consider the following example, which groups the records in the persons table on the
basis of their sex:

A number of specialized functions are available when grouping records in this manner.
The most commonly used one in this context is the COUNT() function.
In the context of a GROUP BY clause, this function can be used to count the number of
records in each group. The following example illustrates by counting the number of males
and females in the persons table:

Performing Joins
The two main types of joins are inner and outer (there are subtypes within both).

Inner Joins

An inner join returns all of the records from the named tables wherever a match is made.

You can also use INNER JOIN syntax to make things clearer. The next example, which is
equivalent to the previous one, illustrates.

You can join as many tables as you like in this manner. The next example adds the
persons table to the previous join, and it also selects the rows and columns to be
displayed in the output of the join by specifying them in the SELECT statement:

Obviously, you can add more WHERE clauses to this join to further filter the result set.
For example, this next query prints a list of all those movies directed by Alfred Hitchcock:

Outer Joins

MySQL also supports outer joins, which are asymmetrical-all records from one side of the
join are included in the final result set, regardless of whether they match records on the
other side of the join.
An outer join differs from an inner join in that an outer join could return records not
matched by a conditional.
Consider the following example, which illustrates by using a left outer join to connect the
movies table to the roles table:

Full join
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

SELECT CustomerName AS Customer, ContactName AS [Contact Person]


FROM Customers;

You might also like