SQLite order by date - sql

My date is not in standard form. This is how it is: 07/15/2013 06:53:05 and is stored as string in the database.
How can I query it to order it by date.
This query is not working.
SELECT jobno, ondate FROM Reports ORDER BY DATE(ondate)
When I run this query it orders it alphabetically and not date wise.

As written here, SQLite doesn't have a date type, so you can do this:
SELECT jobno, ondate
FROM Reports
ORDER BY substr(ondate,7)||substr(ondate,1,2)||substr(ondate,4,2)
sql fiddle demo

This is why this format is not a recommend date/time storage mechanism in SQLite.
You can use strftime to covert the data into something that can be well-ordered (note that we just have to specify the American-ish format string), e.g.
SELECT jobno, ondate FROM Reports
ORDER BY strftime('%m/%d/%Y %H:%M:%S', ondate)
However, this approach (as well as the approach in the other answer) will not be able to use indices and performance on large data may suffer!
From SQLite Datatypes: 1.2 Date and Time Datatype the advice is:
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
I recommend using ISO 8601 as it's still human-readable, is well-understood (and culture neutral), can encode the TZ (just be consistent!), and can be indexed well.

Related

What is expected input date pattern for date_format function in databricks spark SQL

I am trying to better understand the date_format function offered by Spark SQL.As per the official databricks documentation (I am using databricks), this function expects any date/ string in a valid datetime format. Below is the link for the same.
I am finding it difficult to understand what is the exact definition of "valid" here. I am trying to understand the functionality through two examples here.
Input string in YYYY-MM-DD format (2021-07-09), for which I get the expected results correctly:
Input string in DD-MM-YYYY format (20-07-2021), and I get null:
Why is this happening? How did this function understand that the parameter that I am passing is indeed in YYYY-MM-DD format? It could also have been YYYY-DD-MM.
My requirement is that I implement a logic that could handle all kinds of valid date formats (MM-DD-YYYY, YYYY-MM-DD, DD-MM-YYYY) and format the dates accordingly.
The following is valid input and output formats for ANSI date/time data types:
Example: ANSIDATE yyyy-mm-dd 2007-02-28 TIME WITH TIME ZONE hh:mm:ss.ffff... [+|-]th:tm
The valid range of time zone offset is from -14:00 to +14:00. date complies with the ANSI SQL standard definition for the Gregorian calendar: "NOTE 85 - Datetime data types will allow dates in the Gregorian format to be stored in the date range 0001-01-01 CE through 9999-12-31 CE
See Databricks SQL datetime patterns for details on valid formats. The function checks that the resulting dates are valid dates in the Proleptic Gregorian calendar, otherwise it returns NULL
When you use "20-07-2021" it does not conform to "yyyy-mm-dd" so results in NULL
Alternately, you can use make_date function which Creates a date from year, month, and day fields. Or better use to_date function
select date_format(to_date('9/15/2021', 'MM/dd/yyyy'), 'yyyy/MM/dd')
See Datetime Patterns for Formatting and Parsing in Spark.

Select most recent records by DB2 date in form of YYYYMMDD

I am importing records from a DB2 data source into a MS SQL Server destination.
The records are coming in with the date format of 20150302/YYYYMMDD, but I only want the last 14 days based on current server date.
Can some advise on how to select based on this date format against DATEADD(d, - 1, { fn CURDATE() }) please.
Thanks!
It would be better to do this on the DB2 side, to reduce the number of records brought over.
Additionally, it's better from a performance standpoint to convert the static date into a numeric date and compare to the column in your table. Rather than convert the numeric date in your table to a actual date type for comparison.
where numdate >= int(replace(char(current_date - 14 days,iso),'-',''))
Doing it this way will allow you to take advantage of an index over numdate. In addition, DB2 will only need to perform this conversion once.
Depending on your platform & version, you may have an easier way to convert from a date data type to a numeric date. But the above works on DB2 for i and should work on most (all?) DB2 versions and platforms.
You may find it worthwhile to create a UDF to do this conversion for you.
If you want logic in SQL Server, then you are in luck, because you can just convert the YYYYMMDD format to a date:
where cast(datecol as date) >= cast(getdate() - 14 as date)
(This assumes no future dates.)
If you want to do this on the DB2 side, you can use to_date():
where to_date(datecol, 'YYYYMMDD') >= current date - 14 days

How to use datediff equivalent in Oracle with YYYYMMDD formatted number?

I have Oracle database columns with the number format YYYYMMDD. I have not been successful in using this format with datediff to get the difference between two dates. The documentation I've read online uses a different format:
DATEDIFF(day,'2008-06-05','2008-08-05')
What's the best way for me to get number of days between two dates given the format available to me in Oracle? Answers not involving datediff are acceptable as long as it gets the number of days between two dates with the format YYYYMMDD.
Simple subtraction in Oracle:
SELECT TO_DATE('20080805','YYYYMMDD') - TO_DATE('20080605','YYYYMMDD')
FROM DUAL;
Oracle doesn't have a DATEDIFF() function. Instead, you can use simple arithmetic with Oracle dates, where subtracting one date from another gives the number of days, and where you can add an subtract days from a given date. (You can also subtract fractions of days, but that might be outside the scope of this answer.)
To convert your NUMBER dates of the format YYYYMMDD to actual dates, just use the TO_DATE() function (I am pretty sure that Oracle will implicitly convert the NUMBER value to a VARCHAR2 before converting to a date; if not, use TO_CHAR() to do that explicitly).
TO_DATE(20150301, 'YYYYMMDD')
To get the difference between two dates, you can do the following:
SELECT TO_DATE(my_number_date1, 'YYYYMMDD') - TO_DATE(my_number_date2, 'YYYYMMDD')
FROM my_table;
Incidentally, if you want to get intervals instead of days, convert to timestamp (using TO_TIMESTAMP()) instead of converting to date.

Convert date format in Oracle

I have a date format 2011-01-06T06:30:10Z in Excel.I want to just load the date part into a table from excel.How do I get the date part from it.
i.e. 2011-01-06
Thanks
Try this:
select cast(TO_TIMESTAMP_TZ(REPLACE('2011-01-06T06:30:10Z', 'T', ''), 'YYYY-MM-DD HH:MI:SS TZH:TZM') as date) from dual
I think, some more explanation is needed.
Loading data into database is one part, and displaying it after fetching is another part.
If you have loaded the data into database, then all you need to do is use TRUNC. It will truncate the time portion and will display only the date portion.
A DATE always has a datetime part together. TIMESTAMP is an extension to the DATE type. And what you see the date looks like is not the way it is stored in database. The format is for we human beings to understand. A date is stored in 7 byte in internal format.
More information Based on OP's question via comments
NEVER store a DATE as VARCHAR2 datatype. A date is not a string literal. Oracle provides lot of FORMAT MODELS to display the datetime the way you want. Sooner or later, you will run into performance issues due to data conversion. Always use explicit conversion to convert a literal to a perfect DATE to compare it with other date value.

How do I display DATE in 'DD MON YYYY' format?

I am a newbie for Oracle database programming and I wish to INSERT date (also display) in 'DD MON YYYY' format. (PS: This only involves INSERT event). Which data type (DATE or TIMESTAMP) is the most suitable option for me in order to accomplish this format? How was I supposed to do that? Thanks.
A DATE column does not have any format.
So the format that you use when inserting or updating data is irrelevant for displaying that data (that's one of the reasons why you should never store a date in a VARCHAR column).
Any formatted output you see for a DATE column in your SQL tool (e.g. SQL*Plus) is applied by that tool. It is not part of the data stored in that column.
When providing a date literal you should either use the to_date() function with an explicit format mask:
insert into some_table (some_date_column)
values (to_date('27-06-2014', 'dd-mm-yyyy'));
I also do not recommend using formats with written month names (27-JUN-2014) when supplying a date literal because they also depend on the NLS settings of the client computer and might produce (random) errors due to different languages. Using numbers only is much more robust.
I prefer to use ANSI date literals because it's a bit less typing:
insert into some_table (some_date_column)
values (DATE '2014-06-27');
The format for an ANSI date (or timestamp) literal is always the ISO format (yyyy-mm-dd).
When you select your data you can display the date in whatever format you like. Either by using the to_char() function (e.g. when using a SQL tool) or using functions from your programming language (the preferred way to use inside an application):
select to_char(some_date_column,'dd-mon-yyyy')
from some_table;
Note that the DATE data type in Oracle (despite it's name) also stores the time. a TIMESTAMP does the same thing only with a higher precision (it includes milliseconds, whereas the DATE data type only stores seconds).
To insert a record,
INSERT INTO TABLE_NAME (DATE_FIELD) VALUES (TO_DATE ('27-JUN-2014', 'DD-MON-YYYY');
It is advisable to use DATE data-type until and unless you need the date's accuracy to be till milli seconds. In your case, go with DATE datatype and TIMESTAMP is not necessary
To select a record,
SELECT TO_CHAR(DATE_FIELD, 'DD-MON-YYYY') FROM TABLE_NAME;
In genral, remember this:
TO_DATE is a function used to convert a string(CHAR) TO DATE
TO_CHAR is a function used to convert a DATE to a string(CHAR)
In this scenario date datatype will be suitable for you, and for the desired format you should try like this:-
INSERT INTO TABLE_NAME(DATE_COLUMN) VALUES('27-JUN-2014');
Hope this can help you.