How can I sort a query by date?
SELECT * FROM agenda ORDER BY evento ASC
In this way it is appearing as follows: 03/30/2017, 05/31/2016 (the date with 2016 should appear first).
How can I sort a query by date?
SELECT * FROM agenda ORDER BY evento ASC
In this way it is appearing as follows: 03/30/2017, 05/31/2016 (the date with 2016 should appear first).
Guilherme, to be able to sort by date the field evento
it is necessary to be with type datetime
.
If the field is of type string, you will need to convert this date to a date instance and thus perform manipulation.
SELECT * FROM agenda ORDER BY STR_TO_DATE(evento, '%d/%m/%Y') ASC
Reference:
STR_TO_DATE (str, format) STR_TO_DATE (str, format) This is the inverse of the DATE_FORMAT () function. You need a str string and a string format. STR_TO_DATE () returns a DATETIME value if the format string contains date and time portions, or a DATE or TIME value if the string contains only date or time portions. If the date, time, or datetime value extracted from str is illegal, STR_TO_DATE () returns NULL and produces a warning.
link
It is recommended that if the field evento
is type varchar()
you switch to type datetime
, as it is the right way and you will have many features available in MySQL to work with this field.
See more details on this other response: Varchar or Datetime?