Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select part of a Timestamp in a SQL Query

In the DB I am working with, I want to select only the year from a specific TimeStamp field. In particular, I'm hoping to select the unique years from this database column.

For instance, if all of the timestamps in the field "ModifyTimeStamp" are either from the year 2002 or the year 2006, I would like returned simply a result of '2002' and '2006'. If this is impossible, I'd be content with getting a result of a bunch of '2002's mixed with '2006's and would parse it later.

All I've been able to get working so far is "Select ModifyTimeStamp from Table" - all my attempts to parse have failed. I started reading about the extract command for SQL, but I believe it's only for PostgreSQL.

Any advice greatly appreciated!

Edit: Got the answer, thanks a lot datagod and Marc. The code I was looking for ended up being:

"Select distinct YEAR(ModifyTimeStamp) from Table"

like image 698
pghprogrammer4 Avatar asked Apr 27 '11 18:04

pghprogrammer4


1 Answers

You don't specify which RDBMS (database server) you're using, but most databases do have date handling functions built-in:

  • MySQL/SQL Server:

    select YEAR(modifytimestamp) from yourtable
    
  • Access/SQL Server:

    select DatePart(year, modifytimestamp) from yourtable
    
  • Oracle:

    select TO_CHAR(modifytimestamp, 'YYYY') from yourtable
    
like image 53
Marc B Avatar answered Oct 12 '22 22:10

Marc B