Solved

MySQL query with substring

Posted on 2014-01-07
3
316 Views
Last Modified: 2014-01-07
What is wrong with this:

SELECT * FROM `citrans` WHERE substring(dtstamp,0,4) = '2012'.

See attached for structure of table citrans.

There are hundreds of records with year = 2012.
citrans-str.jpg
0
Comment
Question by:Richard Korts
3 Comments
 
LVL 82

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 250 total points
ID: 39763803
Are you getting an error message?  MySQL doesn't keep the DATETIME columns in text format but in an internal binary format.  It converts them to text when it returns them.

I wouldn't do it that way.  This is what I use.
SELECT * FROM `citrans` WHERE `dtstamp` >= '2012-01-01' AND `dtstamp` < '2013-01-01'

Open in new window

Without a time, MySQL makes it 0 so it is actually using '2013-01-01 00:00:00'.
0
 
LVL 11

Accepted Solution

by:
Murfur earned 250 total points
ID: 39763809
SUBSTRING is for text fields, better to use a date function:

SELECT * FROM citrans WHERE YEAR( dtstamp ) = '2012'
0
 
LVL 17

Expert Comment

by:Kent Dyer
ID: 39763850
Have a look here - I think this what you are looking for..

http://sqlfiddle.com/#!2/c00121/4
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Foreword This is an old article.  Instead of using the MySQL extension that was used in the original code examples, please choose one of the currently supported database extensions instead.  More information is available here: MySQLi / PDO (http://…
Creating and Managing Databases with phpMyAdmin in cPanel.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now