Custom ORDER BY in SQLite for string date - sql

I have a column "date_time" and many other.
date_time is a string date (because in SQLite there is no date format), e.g. "2020.2.1" means 1st of February of 2020th.
I want to sort by this date 2020.1.1-2020.1.2-...-2020.12.31
I am using:
SELECT *
FROM Table
ORDER BY date_time
And I am getting sorted as a string:
here is an example:
2020.1.10
...
2020.1.29
2020.1.3
...
How I can sort it as a date if I am using SQLite and my date is string?

select *
from Table
order by cast(date_time as datetime)

Related

Invalid datetime string when CAST As Date

I have Time column in BigQuery, the values of which look like this: 2020-09-01-07:53:19 it is a STRING format. I need to extract just the date. Desired output: 2020-09-01.
My query:
SELECT
CAST(a.Time AS date) as Date
from `table_a`
The error message is: Invalid datetime string "2020-09-02-02:17:49"
You could also use the parse_datetime(), then convert to a date.
with temp as (select '2020-09-02-02:17:49' as Time)
select
date(parse_datetime('%Y-%m-%d-%T',Time)) as new_date
from temp
How about just taking the left-most 10 characters?
select substr(a.time, 1, 10)
If you want this as a date, then:
select parse_date('%Y-%m-%d', substr(a.time, 1, 10))
select STR_TO_DATE('2020-09-08 00:58:09','%Y-%m-%d') from DUAL;
or to be more specific as your column do as:
select STR_TO_DATE(a.Time,'%Y-%m-%d') from `table_a`;
Note: this format is applicable where mysql is supported

Converting String to Date in BigQuery?

I have a timestamp in my big query looking like this: 30/01/2020 00:14:05
date is one of the column names of the table
I have already tried:
1. cast(PARSE_DATE('%Y%m%d', date) as DATE)
2. CAST(date as DATE)
In your case you need SELECT PARSE_DATETIME('%d/%m/%Y %H:%M:%S','30/01/2020 00:14:05')
or SELECT PARSE_DATE('%d/%m/%Y',SUBSTR('30/01/2020 00:14:05',1,10)) if you only need the date

Convert/get varchar variable to YYYYMM

I have 4 CTE's in this table and the third one contains a DATETIME converted to VARCHAR (with format based on the requirement) as startDate in DD/MM/YYYY format. The last cte does calculations based on the data generated and one of the columns needs to store YYYYMM date based on startDate.
The problem it's getting the year and the month from this converted DATETIME, using convert() it shows this:
IDPER
-------
01/01/ --DD/MM/
These 2 show YYYYMM correctly when startDate isn't converted:
Select *, left(convert(nvarchar(6),new_ini,112),6) as IDPER from table
Select *, convert(nvarchar(6),new_ini,112) as IDPER from table
How could I get YYYYMM format having startDate converted? Or what could be a more smart approach to the requirement
If you have a string in the format DD/MM/YYYY and you want YYYYMM, then use string operations:
select right(new_ini, 4) + substring(new_ini, 4, 2)
You should be storing date values as dates or a related type, not as string. But given that you have already stored this as a string, string operations can do what you need.
My way would be slightly different
SELECT CONVERT(NVARCHAR(6), CONVERT(DATE, new_ini, 103), 112);
Here, I first converted it to date and then formatted to YYYYMMDD and taken 6 chars only
declare #date DATE = GETDATE();
select REPLACE(LEFT(CONVERT(DATE,#date,112),8),'-','') -- 1st approach
select FORMAT(#date,'yyyyMM') --2nd approach

SQLite Order By Date1530019888000

Every record in my SQLite database contains a field which contains a Date stored as a string in the format 'yyyy-MM-dd HH:mm:ss'.
Is it possible to query the database to get the record which contains the most recent date please?
you can do it like this
SELECT * FROM Table ORDER BY date(dateColumn) DESC Limit 1
For me I had my query this way to solve my problem
select * from Table order by datetime(datetimeColumn) DESC LIMIT 1
Since I was storing it as datetime not date column
When you sure the format of text field is yyyy-MM-dd HH:mm:ss (ex.: 2017-01-02 16:02:55), So It works for me simply:
SELECT * FROM Table ORDER BY dateColumn DESC Limit 1
Without any extra date function!
You need to convert it to unix timestamp, and then compare them:
SELECT * FROM data ORDER BY strftime('%s', date_column) DESC
But this can be pretty slow, if there are lots of rows.
Better approach would be to store unix timestamp by default, and create an index for that column.
You can convert your column sent_date_time to yyyy-MM-dd format and then order by date:
1) substr(sent_date_time,7,4)||"-"||substr(sent_date_time,1,2)||"-"||substr(sent_date_time,4,2) as date
2) order by date desc
In my case everything works fine without casting column to type 'date'. Just by specifying column name with double quotes like that:
SELECT * FROM 'Repair' ORDER BY "Date" DESC;
I think SQLite makes casting by itself or something like that, but when I tried to 'cast' Date column by myself it's not worked. And there was no error messages.
You can also use the following query
"SELECT * FROM Table ORDER BY strftime('%Y-%m-%d %H:%M:%S'," + dateColumn + ") DESC Limit 1"
I found this ugly hack worked.
select *, substr(date_col_name,7,4)as yy,
substr(date_col_name,4,2) as mm,
substr(date_col_name,1,2) as dd
from my_table
order by yy desc,mm desc,dd desc
it would be better to convert the text column to date field type, but I found that did not work reliably for me.
If you do a lot of date sorting/comparison, you may get better results by storing time as ticks rather than strings, here is showing how to get 'now' in ticks with:
((strftime('%s', 'now') - strftime('%S', 'now') + strftime('%f', 'now')) * 1000)
(see https://stackoverflow.com/a/20478329/460084)
Then it's easy to sort, compare, etc ...
This will work for both date and time
SELECT *
FROM Table
ORDER BY
julianday(dateColumn)
DESC Limit 1

How to select rows by date in sqlite

I have to select all rows from database by just passing date. For example to get all rows that have date 10/23/2012
In sqlite db I store this in DATE column:
01/01/1900 11:00:00 AM
I have tried to get by using date() but I get nothing for date:
select itemId, date(dateColumn) from items
So all I need is to compare only dates but can't find how to do this in sqlite.
Firstly, format your dates to the ISO-8601 standard. Wrap it in Date() to ensure it gets processed as a DATE. Finally, construct your range so that it will include everything from 12:00am onwards until just before 12:00am the next day.
select itemId, dateColumn
from items
where dateColumn >= date('2012-10-23')
AND dateColumn < date('2012-10-23', '+1 day')
SQLite columns are not typed. However, if you compare the column to a DATE as shown, it is sufficient to coerced the column data into dates (null if not coercible) and the comparison will work properly.
Example on SQLFiddle:
create table items (
itemid, datecolumn);
insert into items select
1,'abc' union all select
2,null union all select
3,'10/23/2012 12:23' union all select
4,'10/23/2012' union all select
5,'2012-10-23 12:23' union all select
6,'2012-10-23' union all select
7,'2012-10-24 12:23' union all select
8,'2012-10-24' union all select
9,date('2012-10-24 12:23') union all select
10,date('2012-10-24');
Results:
itemid datecolumn
5 2012-10-23 12:23
6 2012-10-23
Note that although rows 3 and 4 appear to be dates, they are not, because they do not conform to ISO-8601 formatting which is the only format recognized by SQLite.
In SQLite, there is no datatype DATE, it's stored as strings. Therefor, the Strings have to match exactly to be equal.
Since we don't want that, you'll want to "cast" the values from the date-column to pseudo-date and also cast your argument to a pseudo-date, so they can be compared:
SELECT itemId FROM items WHERE date(dateColumn) = date("2012-10-22");
Note that the date-command takes dates formated as YYYY-MM-DD, as further explained in an answer to this older question. The question also shows that you can use the BETWEEN x AND y-command to get dates, matching a range.
SELECT itemId,dateColumn FROM items WHERE dateColumn=date('YYYY-MM-DD HH:MM:SS');
SQLite Reference
select itemId,dateColumn from items
where dateColumn = #date