2

A mysql query is returning unexpected. I'm trying to concatenate a few strings containing date queries like so:

mysql> select month(timestamp) +'-'+ day(timestamp) + '-' + 
       year(timestamp) as date FROM table ORDER BY timestamp DESC LIMIT 1;

and I'm getting a 4 digit result, which I assume is the sum of the expected result:

+------+
| date |
+------+
| 2035 |
+------+

I've also tried casting each one as CHAR which didn't work:

mysql> select CAST(month(timestamp) as CHAR) +'-'+ CAST(day(timestamp) as CHAR) + '-' + 
CAST(year(timestamp) as CHAR) as date FROM table ORDER BY timestamp DESC LIMIT 1;

Could someone let me know what I'm doing wrong? ... and I guess how to fix it would be nice too :)

1
  • 1
    + is the addition operator (but works in MSSQL for string concatenation). Commented Jan 22, 2013 at 8:18

2 Answers 2

5

In MySQL, use CONCAT_WS

CONCAT_WS('-', month(timestamp),day(timestamp),year(timestamp))

query,

SELECT CONCAT_WS('-', month(timestamp),day(timestamp),year(timestamp)) AS DATE
FROM   tablename
ORDER  BY timestamp DESC 
LIMIT  1

or use DATE_FORMAT

SELECT DATE_FORMAT(timestamp, '%m-%d-%Y') AS DATE
FROM   Table1
ORDER  BY timestamp DESC 
LIMIT  1

Other(s):

Sign up to request clarification or add additional context in comments.

1 Comment

awesome! plain old CONCAT worked perfectly. forgot about those ... thank you!
2

Using CONCAT, DAY, MONTH, YEAR, etc to format dates is silly.

If timestamp is an integer column containing a UNIX timestamp use this:

SELECT DATE_FORMAT(FROM_UNIXTIME(`timestamp`), '%m-%d-%Y') AS `Formatted Date`
...

If timestamp is a date/datetime column use this:

SELECT DATE_FORMAT(`timestamp`, '%m-%d-%Y') AS `Formatted Date`
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.