Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - ORDER BY 'datetime' DESC [closed]

I have several values stored in my database as the DATETIME datatype (YYYY-MM-DD HH:MM:SS), and I've been trying to get them in a descending order - Greatest to least (In the case of dates - Newest to oldest), though, oddly enough, it seems to ignore the existence of the DESC operator entirely.

The SQL query (Abbreviated):

SELECT post_datetime FROM post WHERE type=`published` ORDER BY post_datetime DESC LIMIT 3

And from that, they print in this order:

2014-04-30 11:55:11
2014-07-01 12:25:40
2014-07-02 12:28:03

(Those happen to be the "oldest" date entries in the database too)

Solution? I'll note that using DESC on other things (Such as normal numbers) doesn't work either. I've checked my syntax, tried quotes, no quotes, double quotes & such.

(Note - I won't be able to answer any further questions for several hours, though I'll do my best to respond once I return)


(6/11/17)

Edit: To clarify, for future readers, the syntax typo was not related to the issue and was an error on my part when typing an example. I had been using a homemade query builder for so long that I had forgotten the proper syntax at the time. The issue lied within my program's logic—not the query. The above example has been edited and is correct solution for anyone looking to perform the mentioned task. I'm sorry this has been viewed over 50k times... but now you know.

like image 534
Super Cat Avatar asked Jul 04 '14 05:07

Super Cat


2 Answers

  1. use single quotes for strings
  2. do NOT put single quotes around table names(use ` instead)
  3. do NOT put single quotes around numbers (you can, but it's harder to read)
  4. do NOT put AND between ORDER BY and LIMIT
  5. do NOT put = between ORDER BY, LIMIT keywords and condition

So you query will look like:

SELECT post_datetime 
FROM post 
WHERE type = 'published' 
ORDER BY post_datetime DESC 
LIMIT 3
like image 113
Uriil Avatar answered Oct 21 '22 06:10

Uriil


Try:

SELECT post_datetime 
FROM post 
WHERE type = 'published' 
ORDER BY post_datetime DESC 
LIMIT 3
like image 27
pavel Avatar answered Oct 21 '22 06:10

pavel