MySQL
  Home arrow MySQL arrow Optimizing Queries with Operators for ...
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
OLM
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MYSQL

Optimizing Queries with Operators for Date, Time and Other Functions
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 6
    2006-04-13

    Table of Contents:
  • Optimizing Queries with Operators for Date, Time and Other Functions
  • Date and Time Conversion Functions
  • Other MySQL Functions
  • Branching: Making Choices in Queries
  • Our Demonstration Revisited

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
     
    ADVERTISEMENT

    The Web Buyer's Guide is your best source for white papers on a wide range of IT products and services. This Week's Featured White Papers: Taming the Threat Landscape by Symantec

    Optimizing Queries with Operators for Date, Time and Other Functions
    (Page 1 of 5 )

    This article will give you a good grounding in operators, branching and functions in MySQL, so you can make the database, instead of your own code, do the bulk of the work. It is the third of three parts, and excerpted from chapter four of Beginning MySQL Database Design and Optimization: From Novice to Professional, written by Jon Stephens and Chad Russell (Apress; ISBN: 1590593324).

    Date and Time Functions

    In the previous chapter, you saw how MySQL’s date and time datatypes can save storage space—50% or more over storing dates as strings—but that’s not the only reason for using them. One aspect of applications programming that’s often troublesome is working with dates. Different programming languages have radically different ways of representing dates and performing date calculations; users and clients have different requirements for how they’re displayed. By leveraging MySQL functions that are associated with DATE, TIME, and DATETIME values, you can minimize and sometimes even eliminate many of these problems.

    First, let’s look at how to get the current date and time. MySQL supports all of the standard SQL functions for this, as well as several others, as shown in Table 4-3.

    Table 4-3. Current Date and Time Functions Supported by MySQL

    SQL STANDARD CURRENT_DATE

    DESCRIPTION Current date in YYYY-MM-DD format (server time)

    MYSQL ADDITIONS CURRENT_DATE(), CURDATE()

    CURRENT_TIME

    Current time in HH:MM:SS format (server time)

    CURRENT_TIME(), CURTIME()

    CURRENT_TIMESTAMP

    Current timestamp in YYYY-MM-DD HH:MM:SS format (server time)

    CURRENT_TIMESTAMP(), NOW(), SYSDATE()*

     

    Current timestamp in Unix format (seconds elapsed since 1970-01-01 00:00:00) (server time)

    UNIX_TIMESTAMP()

     

    Current UTC date in YYYY-MM-DD format

    UTC_DATE**, UTC_DATE()**

     

    Current UTC time in HH:MM:SS format

    UTC_TIME**, UTC_TIME()**

     

    Current UTC timestamp in YYYY-MM-DD HH:MM:SS format

    UTC_TIMESTAMP**, UTC_TIMESTAMP()**

    * SYSDATE() is supported to provide compatibility with Oracle.

    ** The UTC functions were added in MySQL 4.1.1.

    Note that functions expecting a TIME value will generally accept DATETIME values while ignoring the date part. Functions that expect a DATE value will generally accept a DATETIME value and ignore the time portion of the value.

    It’s somewhat customary in MySQL to use NOW(), CURDATE() , and CURTIME() , since these are short and convenient. However, if compatibility with other databases is an issue, you should use the standard SQL functions instead. To convert from a Unix-style timestamp to date/time format, use the FROM_UNIXTIME() function.

    If you call any functions returning the current date and/or time in the same query, they will always return the same date and/or time.

    Date and Time Formatting and Extraction

    If your application doesn’t need to support multiple locales or languages, you can perform most, if not all, of your date formatting in your queries using the DATE_FORMAT() function, which takes this form:

    DATE_FORMAT(date, format)

    where date is a date, and format is a string containing one or more format specifiers and optional additional punctuation marks. Table 4-4 shows a partial listing of the available format specifiers.

    Table 4-4. Some Format Specifiers for DATE_FORMAT() and Date Arithmetic Functions

    SPECIFIER*

    FORMAT

    %a

    Three-letter day of week (Sun, Mon, Tue, and so on)

    %b

    Three-letter name of month ( Jan, Feb, Mar, and so on)

    %c

    Month number (0–12)

    %D

    Day of month with ordinal suffix (0th, 1st, 2nd, 3rd, and so on)

    %d

    Two-digit day of month (00–31)

    %e

    Day of month (0–31)

    %f

    Microseconds (000000–999999)

    %H

    Two-digit hour (00–23)

    %h or %I

    Two-digit hour (01–12)

    %i

    Minutes (00–59)

    %j

    Day of year (001–366)

    %k

    Hour (0–23)

    %l

    Hour (1–12)

    %M

    Full month name ( January, February, March, and so on)

    %m

    Two-digit month number (00–12)

    %p

    AM/PM

    %r

    12-hour time in HH:MM:SS XM format

    %S or %s

    Seconds (00–59)

     

    Table 4-4. Some Format Specifiers for DATE_FORMAT() and Date Arithmetic Functions (Continued)

    SPECIFIER* %T

    FORMAT 24-hour time in HH:MM:SS format

    %U

    Week of year (00–53), where Sunday is the first day of the week

    %u

    Week of year (00–53), where Monday is the first day of the week

    %W

    Full day of week (Sunday, Monday, Tuesday, and so on)

    %w

    Day of the week (0–6, where 0=Sunday)

    %Y

    Four-digit year

    %y

    Two-digit year

    *These specifiers return the names of days and months in English.

    The following are a few examples of formatting dates.


    TIP  
    If you need to return only a formatted time, you can also use the TIME_FORMAT() function. It accepts any of the time-related format specifiers shown in Table 4-4.

    You can use practically any punctuation you like in formatting dates: commas, dashes, slashes, spaces, and so on. However, you cannot use alphanumeric characters except as part of a format specifier. In addition, you can return a date, time, or date/time value as a number with no formatting whatsoever, simply by forcing it to be evaluated in a numeric context. This will work with any of the functions shown in Table 4-3, as shown in the following example.

    Formatting dates can be even easier in MySQL 4.1.1 and above, using the GET_FORMAT() function. This function returns format strings for a number of locales:

    GET_FORMAT(DATE|TIME|DATETIME, locale)

    The locale argument can take one of several predefined values: 'EUR' , 'USA' , 'JIS' , 'ISO' , and 'INTERNAL' . GET_FORMAT() can be used in place of a format string wherever one is applicable. Here are some examples:

    The SUBDATE() function employed in the second example is used to subtract dates, as discussed in the “Date Arithmetic” section later in this chapter.

    You can also obtain the various parts of a date, time, or datetime as a number using the functions shown in Table 4-5.


    CAUTION  
    The WEEK() function exhibits incorrect behavior in MySQL versions previous to 4.0, where the mode argument is the default (0). See the MySQL documentation for details. We suggest that you use WEEKOFYEAR() instead if it’s available to you (MySQL 4.1.1 and above).

    Table 4-5. Functions Returning Portions of Date, Time, or Date/Time Values

    FUNCTION DAYNAME()

    VALUE RETURNED Name of the day of the week (English)

    DAYOFMONTH(), DAY()

    Day of the month (DAY() was added in MySQL 4.1.1)

    DAYOFWEEK()

    Number of the day of the week (1=Sunday, 7=Saturday)

    DAYOFYEAR()

    Day of the year as a number

    HOUR()

    Hours portion of the time (added in MySQL 4.1.1)

    MINUTE()

    Minutes portion of the time

    MONTH()

    Month portion of the date (1=January)

    MONTHNAME()

    Name of the month (in English); if the date holds a 0 for the month, this function returns NULL

    QUARTER()

    Quarter of the year (1–4)

    SECOND()

    Seconds from time

    TIME()

    Time portion of a date/time (added in MySQL 4..1.1)

    WEEK()*

    Week of the year (1–53)

    WEEKDAY()

    Day of the week (0=Monday, 6=Sunday)

    WEEKOFYEAR()

    Week of the year, the week reckoned as beginning on Monday (added in MySQL 4.1.1)

    YEAR()

    Four-digit year (1000–9999)

    * The WEEK() function takes an optional second mode argument. The behavior of this function also changed significantly in MySQL 4.0; see the MySQL Manual for details.

    Another means of extracting portions of dates and times is to use the EXTRACT() function, which takes this form:

    EXTRACT(type FROM date)

    It returns a number corresponding to the part of the date argument specified by type. The type argument is the name of one of the following units of time: MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR. MICROSECOND was added in MySQL 4.1.1; WEEK and QUARTER were added in MySQL 5.0.0. (The date argument is a date or date/time value in standard format.) Here are some examples:

    If a time value is missing when you use EXTRACT() , it returns 0.

    In addition, the following compound types are permitted: MINUTE_SECOND, HOUR_SECOND, HOUR_MINUTE, DAY_SECOND, DAY_MINUTE, DAY_HOUR, and YEAR_MONTH. Each of these actually specifies a complete set of values; that is, any values that would normally be expected are filled in. For example, if you use HOUR_SECOND for the type, MySQL returns the hours, minutes, and seconds as a number.

    MySQL 4.1.1 and above also supports these compound types, which include microseconds: SECOND_MICROSECOND, MINUTE_MICROSECOND, HOUR_MICROSECOND , and DAY_MICROSECOND. These also fill in the missing units from the range, as in this example:

    EXTRACT(DAY_MICROSECOND FROM '2004-05-15 15:35:25.104528')

    This returns the value 151535250104528.

     


     

    NOTE  All of the type specifiers mentioned in this section can also be used with date arithmetic functions such as DATE_ADD(). See the “Date Arithmetic” section later in this chapter.

     


     

    More MySQL Articles
    More By Apress Publishing


       · This article is an excerpt from the book "Beginning MySQL Database Design and...
       · Hai, Optimizing queries with operators for date, time and other functions of...
       · You're welcome! I'm glad you enjoyed the article.
     

    Buy this book now. This article is excerpted from chapter four of Beginning MySQL Database Design and Optimization: From Novice to Professional, written by Jon Stephens and Chad Russell (Apress; ISBN: 1590593324). Check it out at your favorite bookstore today. Buy this book now.

       

    MYSQL ARTICLES

    - MySQL Table Prefix Changer Tool in PHP
    - Using the SIGNAL Statement for Error Handling
    - Error Handling Examples
    - Error Handling
    - Completing a Search Engine with MySQL and PH...
    - Paginating Result Sets for a Search Engine B...
    - Building a Search Engine with MySQL and PHP 5
    - Using Boolean Operators for Full Text and Bo...
    - PHP, MySQL and the PEAR Database
    - Working with PHP and MySQL
    - Getting PHP to Talk to MySQL
    - Creating an RSS Reader: the Reader
    - MySQL Security Overview
    - Creating the Admin Script for a PHP/MySQL Bl...
    - Creating the Blog Script for a PHP/MySQL Blo...

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway