How do I sort a date field in mysql?

Asked

Viewed 315 times

0

How do I order decreasingly (select * from tabela order by date desc) a date field inserted by the datepicker script in the format dd-mm-yyyy in Mysql?

Note: The dates are being ordered only by day, ignoring the month and the next year. And the date field is varchar (10).

Ex: 02-05-2018 (dd-mm-yyyy)

  • What’s wrong with the select * from tabela order by date desc?

  • the dates are ordered only by the day, ignoring the month and next year. I forgot to mention that the date field is varchar type (10).

  • 02-05-2018 (in this format)

  • I understand. It would be ideal to add this information to the question, so just click the [Dit]

  • 1

    corrected, grateful.

1 answer

2


Because the date is on string it will order appeals for the data before the "-", it is necessary to convert the field to date

select 
  *
from tabela
  order by str_to_date(data, '%d-%m-%Y') desc

I put an example on Sqlfiddle for reference.

  • Show, thanks a lot @Barbetta, that’s right, now how do I write this query for codeigniter? rs

  • @Ramiro, the ideal is to create a question for every doubt, but, no codeigniter you can play to query directly, see here in the documentation if this answer has helped, do not forget to mark as solved if you have solved your problem How and why to accept an answer

  • Okay, thanks. I’ve already set it up, sorry, I’m new to the site.

  • @Ramiro, imagine, no need to apologize. we are there to help =D. Anything, take an OS tour

Browser other questions tagged

You are not signed in. Login or sign up in order to post.