Simple sqlite3 syntax question - sql

Im new to sqlite3 (and databases in general for that matter). Anyway, in my database i have a date column and i wanted to get all of the data within the 3 days of the current date. Here is the query I have. I am just not sure if there is a built in way to get nearby dates in sqlite3. I dont know what to put in the '?'s.
SELECT date FROM fooTable WHERE date('now') ???????

Try this (3 days is 3*86400 seconds):
SELECT date FROM fooTable WHERE strftime('%s', now) - strftime('%s',date) < 259200

Related

Datediff function in TeraData SQL?

i'm new here and it's all a bit confusing, so i'm gonna excuse myself in the beginning, if i do something wrong here.
I usually used MySQL or sometimes Oracle but now I have to switch to Teradata.
Simply i need to convert this:
SELECT FLOOR(DATEDIFF(NOW(),`startdate`)/365.25) AS `years`,
COUNT(FLOOR(DATEDIFF(NOW(),`startdate`)/365.25)) AS `numberofemployees`
FROM `employees`
WHERE 1
GROUP BY `years`
ORDER BY `years`;
into teradata.
Would be great if someone could help :)
Equivalent of your query in Teradata would be :
SELECT FLOOR((CURRENT_DATE - startdate)/365.2500) AS years,
COUNT(FLOOR((CURRENT_DATE - startdate )/365.2500)) AS numberofemployees
FROM employees
--WHERE 1
GROUP BY years
ORDER BY years;
CURRENT_DATE is equivalent to NOW() (without the time part, part DATEDIFF would have ignored it, anyway).
In Teradata you can simply subtract dates to get days in between.
Also, I added two zeroes at the end of 365.25 to force Teradata to evaluate the division to 4 decimal places, because MySQL seems to perform it that way (https://dev.mysql.com/doc/refman/8.0/en/arithmetic-functions.html#:~:text=In%20division%20performed%20with%20/%2C%20the%20scale%20of%20the%20result%20when%20using%20two%20exact-value%20operands%20is%20the%20scale%20of%20the%20first%20operand%20plus%20the%20value%20of%20the%20div_precision_increment%20system%20variable%20(which%20is%204%20by%20default).
But, I am not sure if Understood your original query thoroughly:
What does WHERE 1 do?
Why do you count the years column and call it numberofemployees (why not simply do count(*))

Oracle SQL Todays Date from Data

Apologies as I am extremely green within SQL.
I am currently trying to run the below:
SELECT *
FROM test.message
WHERE MESSAGESUBJECT LIKE '%test%'
AND MESSAGEDATE = CURRENT_DATE
However the results are not pulling back - figured this to be the fact the format of the data within the field currently looks like this:
07-MAR-19 08.13.53.00000000 PM
So the obvious solution is to get it to look at the start of the field - where I'm losing track is that I need the query for a job that's running daily so I cant use exacts. Anyone able to assist?
Thanks,
D.
SELECT *
FROM test.message
where MESSAGESUBJECT like '%test%'
and MESSAGEDATE BETWEEN TRUNC(CURRENT_DATE) AND TRUNC(CURRENT_DATE) + 86399/86400
This will get rows where the message date was any time today.
The 86399/86400 bit is the number of seconds in a day minus 1, so it makes the BETWEEN range cover the whole day and none of the next day (which TRUNC(CURRENT_DATE)+1 would do).
Instead of adding 86399/86400, some find it clearer to add a whole day and then subtract out an an INTERVAL of 1 second. That also works, as does:
AND MESSAGEDATE >= TRUNC(SYSDATE)
AND MESSAGEDATE < TRUNC(SYSDATE)+1 -- Thanks #WernfriedDomscheit
Using
AND TRUNC(MESSAGEDATE) = TRUNC(CURRENT_DATE)
is logically correct, but it makes it impossible for Oracle to use an index on MESSAGEDATE if there is one, which can rob you of your best possible performance. But if you have a function based index on TRUNC(MESSAGEDATE), then that last way is also a reasonable option.

SQL SELECT date from table, and calculate how many days since that date

I'm looking to calculate how many days have passed since a specific date, retrieved from a table in my database. Based on the info I've found on W3Schools (Here), I have attempted using DATEDIFF, but am coming up against a couple of different errors I can't seem to work around.
I have included my code below, and based on this, what I want to happen is this: Select the "DD" from the "Wave_Data" table, and, based on "sysdate", work out how many days have lapsed since then.
SELECT DATEDIFF(WEEKDAY,:P1_DD,SYSDATE)
FROM WAVE_DATA
WHERE WAVE_NUMBER = :P1_WAVE;
The final calculation would then be inputted into a text field within my ApEx database.
Thank you in advance for any help you may be able to provide,
Dominic
In Oracle you can just subtract one Date from another to get the difference (in days) between them:
SELECT SYSDATE - :p1_dd
FROM Wave_Data
WHERE Wave_Number = :p1_wave;
If you want to know the difference between the dates without any time parts then you can do:
SELECT TRUNC( SYSDATE ) - TRUNC( :p1_dd )
FROM Wave_Data
WHERE Wave_Number = :p1_wave;
or
SELECT FLOOR( SYSDATE - :p1_dd )
FROM Wave_Data
WHERE Wave_Number = :p1_wave;

sqlalchemy select by date column only x newset days

suppose I have a table MyTable with a column some_date (date type of course) and I want to select the newest 3 months data (or x days).
What is the best way to achieve this?
Please notice that the date should not be measured from today but rather from the date range in the table (which might be older then today)
I need to find the maximum date and compare it to each row - if the difference is less than x days, return it.
All of this should be done with sqlalchemy and without loading the entire table.
What is the best way of doing it? must I have a subquery to find the maximum date? How do I select last X days?
Any help is appreciated.
EDIT:
The following query works in Oracle but seems inefficient (is max calculated for each row?) and I don't think that it'll work for all dialects:
select * from my_table where (select max(some_date) from my_table) - some_date < 10
You can do this in a single query and without resorting to creating datediff.
Here is an example I used for getting everything in the past day:
one_day = timedelta(hours=24)
one_day_ago = datetime.now() - one_day
Message.query.filter(Message.created > one_day_ago).all()
You can adapt the timedelta to whatever time range you are interested in.
UPDATE
Upon re-reading your question it looks like I failed to take into account the fact that you want to compare two dates which are in the database rather than today's day. I'm pretty sure that this sort of behavior is going to be database specific. In Postgres, you can use straightforward arithmetic.
Operations with DATEs
1. The difference between two DATES is always an INTEGER, representing the number of DAYS difference
DATE '1999-12-30' - DATE '1999-12-11' = INTEGER 19
You may add or subtract an INTEGER to a DATE to produce another DATE
DATE '1999-12-11' + INTEGER 19 = DATE '1999-12-30'
You're probably using timestamps if you are storing dates in postgres. Doing math with timestamps produces an interval object. Sqlalachemy works with timedeltas as a representation of intervals. So you could do something like:
one_day = timedelta(hours=24)
Model.query.join(ModelB, Model.created - ModelB.created < interval)
I haven't tested this exactly, but I've done things like this and they have worked.
I ended up doing two selects - one to get the max date and another to get the data
using the datediff recipe from this thread I added a datediff function and using the query q = session.query(MyTable).filter(datediff(max_date, some_date) < 10)
I still don't think this is the best way, but untill someone proves me wrong, it will have to do...

Get records as of today or up to a certain date in Oracle

Could somebody recommend the query to retrieve records up to today or certain dates?
I'm required to produce an Oracle report where user needs to enter a date and records up to that date will be shown.
I tried
select * from the_table where the_date <= sysdate
However it seems to produce an inaccurate result. What is the better query for this. For now I'm just playing around with sysdate. Later I will need to use a certain date keyed in by the user and all the records up to that date needs to be shown.
Any suggestions?
Sometimes you get inaccurate records because of little differences like minutes and seconds when two dates have the same day/month/year. Try the following
select * from the_table where TRUNC(the_date) <= sysdate
The TRUNC removes the minute and the seconds. Sometimes you get inaccurate records without using that