STR_TO_DATE in MY SQL Query is Null - mysql

I've read multiple posts and find nothing wrong with my syntax, can someone point out the error?
I am testing some queries in PHP MyAdmin, on a WordPress Database. The table I am querying has a meta_key of "Listing-End-Date" and meta_values of "2018/06/30".
My query looks like this:
SELECT * FROM `table`
WHERE `meta_key` LIKE 'Listing-End-Date'
AND STR_TO_DATE('meta_value', '%Y/%m/%d') > CURDATE()
and it returns 0 results. To test my STR_TO_DATE format, I did a new query:
SELECT `meta_key` , STR_TO_DATE( 'meta_value', '%Y/%m/%d' )
FROM 'table'
WHERE `meta_key` LIKE 'Listing-End-Date'
I get the expected 1 result returned, but the date is NULL. Is it because I am using PHP My Admin or did I type something wrong?

Meta_value should be ticked and not quoted inside string_to_date

You were trying to convert string value 'meta_value' to date which obviously fails. You probably wanted to reference a column meta_value from table meta_key instead:
SELECT * FROM `table`
WHERE meta_key LIKE 'Listing-End-Date'
AND STR_TO_DATE(meta_value, '%Y/%m/%d') > CURDATE()
I've removed backticks as they're not required here (all but table). Though, you really shouldn't name your table with a reserved keyword even if you can using backticks.
Also, one thing to note would be that meta_key LIKE 'Listening-End-Date' is equivalent of equality comparison meta_key = 'Listening-End-Date' because you don't do partial search (you're not using % anywhere).

Try to use DATE_FORMAT()
check this page

Related

SQL select order by date in varchar

I have my date in database in varchar column and i can't change it. However i want to sort things from newest to latest. My date in database looks like:
2014-09-22 10:28:28
So what i try is something like:
$sql = "SELECT * FROM axnmrs_cases WHERE vin = :vin ORDER BY STR_TO_DATE(date_created,'%b-%e-%Y') ASC LIMIT 30";
But unfortunately this not change anything for me , even if i change ASC to DESC , nothing changeing in result
and also something like:
$sql = "SELECT * FROM axnmrs_cases WHERE vin = :vin ORDER BY CONVERT(date_created, date, 103)";
This throw syntax SQL error and I have no idea why.
Is here anybody who can show me the right way?
Date stored in varchar is not a real date and hence the order by also does not give you what you want. The best approach would be store date always in mysql native data types. However in your case you can use str_to_date() function to convert the varchar dates to real date and then use it for sort something as
order by str_to_date(date_created,'%Y-%m-%d %H:%i:%s');
$sql = "SELECT * FROM `axnmrs_cases` WHERE `vin` = ':vin' ORDER BY `date_created` ASC LIMIT 30";
Already tried something like this?
You are using the wrong format in your STR_TO_DATE function, if the date is in the format:
2014-09-22 10:28:28
Then you need to use
STR_TO_DATE(date_created, '%Y-%m-%d %H:%i:%s')
i.e. the format you give should match the format your varchar is in.
Example on SQL Fiddle
In your case you are using '%b-%e-%Y', so you are looking for a date like Jan-1-2014, for a full list of the specifiers in the format defintion see the My SQL Docs for DATE_FORMAT
Also, CONVERT(date_created, date, 103) does not work because it is SQL Server Syntax.
Finally, I would really, really try and change the column data type. Storing dates as a varchar is never a good idea. Anything else is just a workaround, not a solution.

mysql query with 'like' doesn't work with varchar and space

I have a Db with one table with 3 fields like the following:
user_id TimeStamp Azioni
where the 'timestamp' field is a varchar(25) like this: 2012/09/19 16:34:01.95
It is a varchar and not a timestamp value because i need it to be in the shown format.
And i cannot change its type even if i wanted to.
Now, I'm trying to get all db entries with the same date. For example, when Timestamp contains 2012/09/19
I tied several queries:
Query 0:
SELECT Azioni.Action
FROM Azioni
WHERE TimeStamp LIKE '2012/09/19%'
Query 1:
SELECT `Azioni`.*
FROM Azioni
Where `TimeStamp` LIKE '{2012/09/19}%'
Query 2:
SELECT `Azioni` . *
FROM Azioni
WHERE LOCATE( '2008/09/19', `TimeStamp` ) >0
Query 3:
SELECT `Azioni` . *
FROM Azioni
WHERE INSTR( `TimeStamp` , '2012/09/19' ) >0
Query 4:
SELECT * FROM `Azioni`
WHERE `TimeStamp` like '2012|/09|/19%' escape '|'
and I always get: MySQL returned an empty result set (i.e. zero rows).
But I am sure there are rows containing the said timestamp. What am i doing wrong? Does the 'space' between date and time create a problem? If so how can i solve it? Do you have any suggestion?
EDIT:
Aa suggested, from
SELECT TIMESTAMP, HEX( TIMESTAMP )
FROM Azioni
i get the following
2009-06-06 09:28:00.0000 323030392D30362D30362030393A32383A30302E30303030
2009-06-06 09:29:00.0000 323030392D30362D30362030393A32393A30302E30303030
2009-06-06 09:30:51.0000 323030392D30362D30362030393A33303A35312E30303030
2009-06-06 14:25:00.0000 323030392D30362D30362031343A32353A30302E30303030
2009-06-06 14:26:00.0000 323030392D30362D30362031343A32363A30302E30303030
EDIT 2:
ehm yeah, i was typing the date wrong in the query. Sigh, i'm stupid. Sorry for wasting your time guys.
How about this:
where timestamp like '2012/09/19%'
And, if you are going to call the field timestamp you should store it as a date/datetime/timestamp. Call it something else if it is going to be stored as a string. Timestamp is actually the name of a type in MySQL, so having that in a column name with a different type is quite misleading.
EDIT:
Have you tried:
where left(timestamp, 10) = '2012/09/19'
It sounds like there are string characters in the field, which are preventing reasonable code from working.
SELECT * FROM Azioni
WHERE `TimeStamp' LIKE '2012/09/19%'

MySQL LIKE with range doesn't work

I've got a database table mytable with a column name in Varchar format, and column date with Datetime values. I'd like to count names with certain parameters grouped by date. Here is what I do:
SELECT
CAST(t.date AS DATE) AS 'date',
COUNT(*) AS total,
SUM(LENGTH(LTRIM(RTRIM(t.name))) > 4
AND (LOWER(t.name) LIKE '%[a-z]%')) AS 'n'
FROM
mytable t
GROUP BY
CAST(t.date AS DATE)
It seems that there's something wrong with range syntax here, if I just do LIKE 'a%' it does count properly all the fields starting with 'a'. However, the query above returns 0 for n, although should count all the fields containing at least one letter.
You write:
It seems that there's something wrong with range syntax here
Indeed so. MySQL's LIKE operator (and SQL generally) does not support range notation, merely simple wildcards.
Try MySQL's nonstandard RLIKE (a.k.a. REGEXP), for fuller-featured pattern matching.
I believe LIKE is just for searching for parts of a string, but it sounds like you want to implement a regular expression to search for a range.
In that case, use REGEXP instead. For example (simplified):
SELECT * FROM mytable WHERE name REGEXP "[a-z]"
Your current query is looking for a string of literally "[a-z]".
Updated:
SELECT
CAST(t.date AS DATE) AS 'date',
COUNT(*) AS total,
SUM(LENGTH(LTRIM(RTRIM(t.name))) > 4
AND (LOWER(t.name) REGEXP '%[a-z]%')) AS 'n'
FROM
mytable t
GROUP BY
CAST(t.date AS DATE)
I believe you want to use WHERE REGEXP '^[a-z]$' instead of LIKE.
You have regex in your LIKE statement, which doesn't work. You need to use RLIKE or REGEXP.
SELECT CAST(t.date AS DATE) AS date,
COUNT(*) AS total
FROM mytable AS t
WHERE t.name REGEXP '%[a-zA-Z]%'
GROUP BY CAST(t.date AS DATE)
HAVING SUM(LENGTH(LTRIM(RTRIM(t.name))) > 4
Also just FYI, MySQL is terrible with strings, so you really should trim before you insert into the database. That way you don't get all that crazy overhead everytime you want to select.

Sort longtext as int in SQL

I have table in MySQL database where one column type is longtext and there are stored numbers. I need to get content from table sorted by numbers in that column.
SELECT * FROM wp_postmeta WHERE meta_key = 'rating_avg' ORDER BY meta_value
With this query sorting is not proper and looks like:
0
1.6
10
5
but I need like this:
10
5
1.6
0
I may not change column type, because this column have many different types of data. Is there any possibility to change column type temporary in SQL query?
What you are looking for is CAST.
CAST(expr AS type)
Your SQL Query should look like this:
SELECT * FROM wp_postmeta WHERE meta_key = 'rating_avg' ORDER BY CAST(`meta_value` AS DECIMAL) DESC
This can also be accomplished through native WordPress functions without having to resort to raw SQL. Give WP_Query an orderby parameter of meta_value_num rather than meta_value (reference).
It's been over a year since the question was asked, but for reference to anyone that came here after the search, the answer is
CAST(meta_value AS DECIMAL(10,2))
so the query should be:
SELECT * FROM wp_postmeta WHERE meta_key = 'rating_avg' ORDER BY CAST(`meta_value` AS DECIMAL(10,2)) DESC

Using AND/OR mysql commands with FROM_UNIXTIME

Trying to select a query in php/mysql to get "Upcoming Items" in a calendar. We store the dates in the DB as a unix time. Here's what my query looks like right now
SELECT *
FROM `calendar`
WHERE (`eventDate` > '$yesterday')
OR (FROM_UNIXTIME(eventDate, '%m') > '$current_month' AND `$yearly` = '1')
ORDER BY `eventDate`
LIMIT 4
This is giving me an error "Unknown column '' in 'where clause'". I'm sure it has to do with my use of parenthesis (which I've never used before in a query) and the FROM_UNIXTIME command.
Can someone help me out and let me know how I've screwed this up?
Thanks!
This to me looks suspicious:
`$yearly`
What is the value of $yearly? Is it empty? When you use backticks MySQL treats the contents as the name of a column.
Perhaps you meant to create a string instead, in which case you should use a different type of quote:
'$yearly' = '1'
Or perhaps you intended to refer to the column yearly:
yearly = '1'
Another tip is to print the SQL query after the PHP variables have been interpolated as this sometimes makes it easier to understand the error message from MySQL. I'd imagine your query looks something like this:
SELECT *
FROM `calendar`
WHERE (`eventDate` > '1295071200')
OR (FROM_UNIXTIME(eventDate, '%m') > '1' AND `` = '1')
ORDER BY `eventDate`
LIMIT 4
The suspicious part is here:
`` = '1'
Do you have a column named $yearly ?, try removing the dollar sign