SQL query to retrieve last twelve months data for Oracle database - sql

I am using Oracle database. I have a table called "TEST" where the dates/timestamps(These are stored as "Char" in my case) are stored in the following format. Now I want to retrieve the records of last twelve months based on today's date. What would be the correct way to do that?
TESTCOLUMN
------------
2019-06-28-02.01.07.327240
2020-06-28-04.49.12.480240
2020-06-28-05.05.10.681240

I think you need to use the ADD_MONTHS function and BETWEEN clause as follows:
SELECT * FROM YOUR_TABLE
WHERE TO_TIMESTAMP(YOUR_COLUMN,'YYYY-MM-DD HH24.MI.SS.FF')
BETWEEN ADD_MONTHS(SYSTIMESTAMP,-12) AND SYSTIMESTAMP;

Although storing values in a string is not recommended, your format is comparable. So you can do the comparison using strings rather than date/timestamps. Assuming your values are only in the past:
where testcolumn >= to_char(SYSTIMESTAMP, -12), 'YYYY-MM-DD HH24.MI.SS.FF')
This has an advantage over Tejash's solution, because this can make use of an index (or partitions) on testcolumn. Moving the date manipulations only on the "constants" (i.e. the system timestamp) helps the Oracle optimizer.

Related

SQLite - TZ format to Date time only using SQL queries

I have a SQLite database with a simple table in the format of:
ID,DateText,Name
1,2020-09-01T18:57:17Z,John
2,2022-12-01T04:00:09Z,Laurel
...
The DateText column is declared as TEXT on the "create table" statement. Using only SQL, I need to:
Create a new column with the DateText data.
Obtain the "oldest" date
Obtain the "newest" date
Note that I need to resolve this with a SQL query. I cannot read into a programming language, parse, and update table--I need to do everything on SQL. For example, SQL Server DateTime with timezone is the opposite, but they are using node.js, something I cannot do.
You can get the oldest and newest using min() and max():
SELECT ID, min(DateTime), Name FROM YourTable; -- Oldest
SELECT ID, max(DateTime), Name FROM YourTable; -- Newest
The nice thing about ISO-8601 date and time format strings is that they sort lexicographically without having to do anything special with them.
These queries would give an error on most SQL database engines because of the mix of non-grouped columns with an aggregate function, but SQLite explicitly will return the row that goes with the minimum or maximum column value. And of course if you don't want the other columns, just leave them out of the SELECT.

Formatting timestamp in oracle

We have a column of type varchar2(200 char) which holds a timestamp in the format 2019-03-28:17:01:44.407000000
Now we would like to update the values in the column so that the format looks like 3/28/2019 5:01:43.475 PM
We are using Oracle 12c.
I am new to oracle, Any lead would be helpful.
This is a pretty terrible data model. A timestamp should really, really be stored in a timestamp column rather than in a varchar2. Both because then the data type identifies what is actually in the column and because it is more efficient and because it lets you use all Oracle's timestamp functions on the data sensibly.
Assuming that you are stuck with an incorrect data model
update your_table
set your_column = to_char( to_timestamp( your_column, 'YYYY-MM-DD:HH24:MI:SS.FF9' ),
'MM/DD/YYYY HH:MI:SS.FF3 PM' )
would update all the data to the new format in the unlikely event that every single value in the table is in the correct format already. In most real-world systems, you'd need to do a fair amount of clean-up first because inevitably someone has stored in incorrect string or two in your column.
If you do happen to be able to update all the data successfully, be aware that any queries that do order by your_column will almost certainly stop doing what you want. Since the column is a varchar2 rather than a timestamp, sorting is done alphabetically rather than by the point in time that the string represents. If you change the format to something where temporal order doesn't match alphabetical order, you are likely to have unhappy users.

SQL timestamp Query

Table has Created_time column with values like 25-MAY-2012.10.12.320000 PM.
I need to write a query to display the all the fields from table XYZ which were created between the month of March and April, agnostic to the year they are in.
I would like to display the records in ascending order based on their id.
Can someone help me?
Check out month and year function.
if created_time is of type datetime:
select *
from TABLE
where month(Created_time) in (3, 4)
If you need to check whether the Created_time was in March of any year, then the idea is to do something like this:
select *
from XYZ
where Created_time like '%-MARCH-%'
order by id;
Or, if this is not supported for your column's type, then convert it to varchar. Also, there are some RDBMS-specific functions that could help you, but for a more thorough answer I would need to know the RDBMS you are using and the type of Created_time.
EDIT
As pointed out by Jarhl, EXTRACT should be usable in this case to check the month. Source, proving that he is right says:
Name
EXTRACT
The ANSI SQL scalar function for extracting parts from a date is
EXTRACT. ANSI SQL Standard Syntax
The ANSI SQL EXTRACT function takes a date_part and an expression that
evaluates to a datetime value. MySQL, Oracle, and PostgreSQL support
the ANSI SQL standard syntax:
EXTRACT( date_part FROM expression )

Return an oracle column as timestamp

I'm in coldfusion working with data from an sql table, and using a query of queries to join the sql data to some data from an oracle database. Unfortunately, I need to order them by date, and the oracle table has two columns - DRWR_DATE which is of type DATE and TIME which is of type VARCHAR2. The two columns put into a string read 17-JUN-03 16:35:18 or something similar. I need to return these two columns as a TIMESTAMP so I can use query of queries to sort them.
Also, I think I read that a date column holds the time in Oracle anyway? I don't have much experience with Oracle so I am unsure how best to do this.
Try this:
SELECT to_timestamp(
to_char( drwr_date,'dd-mon-yy') ||' '|| time
, 'dd-mon-yy hh24:mi:ss'
)
FROM your_table
Try using TO_TIMESTAMP function:
SELECT TO_TIMESTAMP('17-JUN-03 16:35:18', 'DD-MON-RR HH24:MI:SS')
FROM DUAL;
you can try converting the column to date as the following:
TO_DATE(column,'DD-MON-YY HH24:MI:SS')
The first parameter takes your column and the second parameter specifies the date format that is used
If all you have to do is order by date, all you need is an order by clause.
order by drwr_date, time
You don't have to cast these to anything, unless you need to do so for another reason. Remember that a date datatype is essentially a floating point number. This, "17-JUN-03" is simply how your client is displaying it.

SQL oracle beginner questions

Question1:
Do i have to use to_date while inserting date?
INSERT INTO some_table (date1, date2)
VALUES (to_date('2012-10-24','YYYY-MM-DD'), to_date('2012-10-24','YYYY-MM-DD'));
Or can just insert as string? Will everything be OK this way too? I've tried and it worked.
INSERT INTO some_table (date1, date2)
VALUES ('2012-10-24',2012-10-24');
Question2:
What happens if i won't name columns that i'm inserting into? It works, but my question is if it inserts randomly now or it takes order of columns during creation of table?
INSERT INTO some_table
VALUES ('2012-10-24',2012-10-24');
1 seems to only work with the 'YYYY-MM-DD' format:
http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements003.htm#SQLRF51049 says
You can specify a DATE value as a string literal ... to specify a DATE value as a literal, you must use the Gregorian calendar. You can specify an ANSI literal... The ANSI date literal contains no time portion, and must be specified in the format 'YYYY-MM-DD'.
However, it might work with time if you use the
Alternatively you can specify an Oracle date value... The default date format for an Oracle DATE value is specified by the initialization parameter NLS_DATE_FORMAT.
For question 2, it uses the order at definition of the table. However you have to give values for all columns in that case.
Oracle supports Standard SQL date literals (since 9i).
It's DATE followed by a string with 'yyyy-mm-dd' format
DATE '2014-05-10'
It's much shorter than TO_DATE and it's independent of any NLS settings.
Similar for timestamps:
TIMESTAMP '2014-05-10 09:52:35'
Regarding your 2nd question: It's the order of columns as defined within the CREATE TABLE.
You could even do it like this one:
ALTER SESSION SET NLS_DATE_FORMAT = 'MM:YYYY:DD';
INSERT INTO some_table (date1) VALUES ('05:2014:10');
...but doing it like this is not recommended. Use TO_DATE or DATE Literal, e.g. DATE '2014-05-10' instead. It makes your life easier.