Skip to content
Advertisement

SQL: Query column (string) as date

Assume I have a few columns in a database: id, date_added, tag

`20134` | `February 07, 2019` | `New`
`40323` | `February 09, 2019` | `New`

I want to run a query with a filter based on date_added:

SELECT * FROM table
WHERE date_added > 'February 08, 2019'

How would I do this? I saw you can convert strings to date objects, but wasn’t sure if that is possible inside a WHERE filter.

Any help is appreciated!

Edit: I am using SQLite

Advertisement

Answer

You chose a format for the date_added column, that is not comparable.
SQLite is not that flexible with dates, which are in fact Text.
So in this case you need to extract the date parts piece by piece and create a comparable date:

select *
from tablename
where 
  substr(date_added, instr(date_added, ',') + 2) ||
  case substr(date_added, 1, instr(date_added, ' ') - 1) 
    when 'January' then '01'
    when 'February' then '02'
    when 'March' then '03'
    when 'April' then '04'
    when 'May' then '05'
    when 'June' then '06'
    when 'July' then '07'
    when 'August' then '08'
    when 'September' then '09'
    when 'October' then '10'
    when 'November' then '11'
    when 'December' then '12'
  end ||
  substr(date_added, instr(date_added, ' ') + 1, 2) > '20190208'

See the demo

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement