fhg
Volume 8, Number 25 -- July 9, 2008

A Handy SQL Timestamp Function

Published: July 9, 2008

Hey, Ted:

I have found a great tool for working with timestamp data. I have used it for performance tracking and analyzing data intervals. It's SQL's Timestampdiff function, and I think you should tell readers of Four Hundred Guru about it.

Timestampdiff returns the difference between two timestamps in the interval of your choice. The first parameter for the timestampdiff function is the interval to use. Valid values for this parameter are:


1

Fractions of a second

2

Seconds

4

Minutes

8

Hours

16

Days

32

Weeks

64

Months

128

Quarters

256

Years

 

The second parameter is used to subtract the two timestamp values. I cast the result as char(22).

Here's an example:

with STATISTICS as
  ( select count(*) as TRANSMITTED,
           min(TRANSMIT_TIMESTAMP) as START_TIMESTAMP,
           max(TRANSMIT_TIMESTAMP) as END_TIMESTAMP
      from XMITLOG
     where date(TRANSMIT_TIMESTAMP) = current_date)

select TRANSMITTED, START_TIMESTAMP, END_TIMESTAMP,
       timestampdiff(4,
          cast( (END_TIMESTAMP - START_TIMESTAMP) as char(22)))
          as ELAPSED_MINUTES
  from STATISTICS

The result set looked like this:


TRANSMITTED

START_TIMESTAMP

END_TIMESTAMP

ELAPSED_MINUTES

1,138

2008-03-19-05.46.51.473676

2008-03-19-06.15.14.241519

28

 

--Jeff


Thanks for bringing this powerful function to our attention, Jeff. One of the problems we've faced for so many years by storing dates and times in numeric and alpha fields is the difficulty of date/time arithmetic. It's marvelous to have such wonderful tools to work with these days.

--Ted




Copyright © 1996-2008 Guild Companies, Inc. All Rights Reserved.
Guild Companies, Inc., 50 Park Terrace East, Suite 8F, New York, NY 10034

Privacy Statement