Selecting all rows more than 24 hours old in PostgreSQL [duplicate] - database

I have a timestamp field in a postgres database. I would like to select all dates that have happened within the last month. So something like select * from table where timestamp > (current timestamp - 1 month).

select * from table where timestamp > now() - interval '1 month'

To be precise:
SELECT *
FROM tbl
WHERE ts_col > now() - interval '1 month'
AND ts_col <= now();

Related

SQL Server : return boolean if timestamp is within 1 minute

Disclaimer that I am very novice on SQL writing...
How would I return a single boolean if any record within the query has a timestamp updated within the last 1 minute.
SELECT *
FROM myTable
WHERE mytimestamp >= NOW() - INTERVAL 1 MINUTE
Thanks!
This will give you one row if there is any record matching the criteria:
select exists (
select 1 from mytable where mytimestamp >= dateadd(minute, -1, getdate()) )
You could use current_timestamp which is ANSI SQL equivalent of getdate().

MSSQL Obtain the last entries added in the last 30 seconds?

I want to obtain the last entries in the last 30 seconds from a MSSQL database.
In Mysql you do:
SELECT * FROM table WHERE datetime > (now() - interval 30 second)
How to do that in MSSQL?
DATEDIFF is your solution here.
SELECT
*
FROM
[table]
WHERE
DATEDIFF(second, [datetime], GETDATE()) < 30
Using dateadd with a negative integer will give you the data you are asking for
DATEADD (Transact-SQL)
SELECT
*
FROM
table
WHERE
datetime >= DATEADD(SECOND,-30,datetime)
You can use GETDATE() in combindation with DATEADD:
SELECT * FROM table WHERE datetime > (DATEADD(second,-30,getdate()))
Use DATEADD()
DATEADD(SECOND,-30,GETDATE())

Get record based on year in oracle

I am creating a query to give number of days between two days based on year. Actually I have below type of date range
From Date: TO_DATE('01-Jun-2011','dd-MM-yyyy')
To Date: TO_DATE('31-Dec-2013','dd-MM-yyyy')
My Result should be:
Year Number of day
------------------------------
2011 XXX
2012 XXX
2013 XXX
I've tried below query
WITH all_dates AS
(SELECT start_date + LEVEL - 1 AS a_date
FROM
(SELECT TO_DATE ('21/03/2011', 'DD/MM/YYYY') AS start_date ,
TO_DATE ('25/06/2013', 'DD/MM/YYYY') AS end_date
FROM dual
)
CONNECT BY LEVEL <= end_date + 1 - start_date
)
SELECT TO_CHAR ( TRUNC (a_date, 'YEAR') , 'YYYY' ) AS YEAR,
COUNT (*) AS num_days
FROM all_dates
WHERE a_date - TRUNC (a_date, 'IW') < 7
GROUP BY TRUNC (a_date, 'YEAR')
ORDER BY TRUNC (a_date, 'YEAR') ;
I got exact output
Year Number of day
------------------------------
2011 286
2012 366
2013 176
My question is if i use connect by then query execution takes long time as i have millions of records in table and hence i don't want to use connect by clause
connect by clause is creating virtual rows against the particular record.
Any help or suggestion would be greatly appreciated.
From your vague expected results I think you want the number of records between those dates, not the number of days; but it's rather unclear. Since you refer to a table in the question I assume you want something related to the table data, not simply days between two dates which wouldn't depend on a table at all. (I have no idea what the connect by clause reference means though). This should give you that, if it is what you want:
select extract(year from date_field), count(*)
from t42
where date_field >= to_date('01-Jun-2011', 'DD-MON-YYYY')
and date_field < to_date('31-Dec-2013') + interval '1' day
group by extract(year from date_field)
order by extract(year from date_field);
The where clause is as you'd expect between two dates; I've assumed there might be times in your date field (i.e. not all at midnight) and that you want to count all records on the last date in your range. Then it's grouping and counting based on the year for each record.
SQL Fiddle.
If you want the number of days that have records within the range, then you can just vary the count slightly:
select extract(year from date_field), count(distinct trunc(date_field))
...
SQL Fiddle.
you can use the below function to reduce the number of virtual rows by considering only the years in between.You can check the SQLFIDDLE to check the performance.
First consider only the number of days between start date and the year end of that year or
End date if it is in same year
Then consider the years in between from next year of start date to the year before the end date year
Finally consider the number of days from start of end date year to end date
Hence instead of iterating for all the days between start date and end date we need to iterate only the years
WITH all_dates AS
(SELECT (TO_CHAR(START_DATE,'yyyy') + LEVEL - 1) YEARS_BETWEEN,start_date,end_date
FROM
(SELECT TO_DATE ('21/03/2011', 'DD/MM/YYYY') AS start_date ,
TO_DATE ('25/06/2013', 'DD/MM/YYYY') AS end_date
FROM dual
)
CONNECT BY LEVEL <= (TO_CHAR(end_date,'yyyy')) - (TO_CHAR(start_date,'yyyy')-1)
)
SELECT DECODE(TO_CHAR(END_DATE,'yyyy'),YEARS_BETWEEN,END_DATE
,to_date('31-12-'||years_between,'dd-mm-yyyy'))
- DECODE(TO_CHAR(START_DATE,'yyyy'),YEARS_BETWEEN,START_DATE
,to_date('01-01-'||years_between,'dd-mm-yyyy'))+1,years_between
FROM ALL_DATES;
In Oracle you can perform Addition and Substraction to dates like this...
SELECT
TO_DATE('31-Dec-2013','dd-MM-yyyy') - TO_DATE('01-Jun-2011','dd-MM-yyyy')
DAYS FROM DUAL;
it will return day difference between two dates....
select to_date(2011, 'yyyy'), to_date(2012, 'yyyy'), to_date(2013, 'yyyy')
from dual;
TO_DATE(2011,'Y TO_DATE(2012,'Y TO_DATE(2013,'Y
--------------- --------------- ---------------
01-MAY-11 01-MAY-12 01-MAY-13
select to_char(date_field,'yyyy'), count(*)
from your_table
where date_field between to_date('01-Jun-2011', 'DD-MON-YYYY')
and to_date('31-Dec-2013 23:59:59', 'DD-MON-YYYY hh24:mi:ss')
group by to_char(date_field,'yyyy')
order by to_char(date_field,'yyyy');

How to get number of rows with timestamp between 10am and now?

I am trying to run a T-SQL query that would return all rows that contain a timestamp between 00:00:00 and now for any given date.
I've used the following code, but this only returns items within the past 24 hours:
SELECT *
FROM table
WHERE timestamp_closed = DATE(GETDATE()-1);
Here you have the number of rows:
SELECT COUNT(*)
FROM *yourtable*
WHERE timestamp_closed BETWEEN CAST(GETDATE() AS DATE) AND GETDATE()
SELECT *
FROM table
WHERE timestamp_closed BETWEEN CAST(GETDATE() AS DATE) AND GETDATE()
You could build the datevalue for "Today at 00:00:00" and now and then do a
WHERE timestamp_closed >= "Today at 00:00:00" and timestamp_closed<=GETDATE()
You can probably wrap this in a function.
select *
from table
where datepart(hh,timestamp_closed)*100 + datepart(mi,timestampclosed) <
datepart(hh,getdate())*100 + datepart(mi,getdate())
SELECT *
FROM table
WHERE (timestamp_closed > CAST(#specificDate AS DATE)
AND timestamp_closed <= GETDATE())

Query last day, last week, last month SQLite

I have this table in my Android SQLite DB:
CREATE TABLE statistics (subject TEXT, hits INTEGER, fails INTEGER, date DATE)
On date field is stored datetime('now', 'localtime') in every register.
Now I must query last day, last week and last month registers for showing some statistics.
I've been trying something like this
SELECT Timestamp, datetime('now', '-1 week') FROM statistics WHERE TimeStamp < datetime('now', '-1 week')
and this
SELECT * FROM statistics WHERE date BETWEEN datetime('now', localtime') AND datetime ( 'now', '-1 month')
and doesn't work :(
How can I do it?
Can I check if the query is OK by simply forwarding date in the virtual device emulator?
Thanks!
I have found this solution. I hope it works for you.
For last day:
SELECT * FROM statistics WHERE date BETWEEN datetime('now', 'start of day') AND datetime('now', 'localtime');
For last week:
SELECT * FROM statistics WHERE date BETWEEN datetime('now', '-6 days') AND datetime('now', 'localtime');
For last month:
SELECT * FROM statistics WHERE date BETWEEN datetime('now', 'start of month') AND datetime('now', 'localtime');
This code should get you the previous month
SELECT *
FROM statistics
WHERE date >= date('now','start of month','-1 month')
AND date < date('now','start of month')
SELECT *
FROM statistics
WHERE date >= date('now','start of month','-1 months')
AND date < date('now','start of month')
On more months, is "months" and not month like as other said before.
This code will bring previous week records hopefully
SELECT * FROM order_master
WHERE strftime('%Y-%m-%d',om_date) >= date('now','-14 days') AND
strftime('%Y-%m-%d',om_date)<=date('now') order by om_date LIMIT 6
SELECT
max(date(date, 'weekday 0', '-7 day')) WeekStart,
max(date(date, 'weekday 0', '-1 day')) WeekEnd,date
FROM table;
You can create a calendar and then get the timestamp from it
final Calendar todayCalendar = Calendar.getInstance();
final long todayTimestamp = todayCalendar.getTime().getTime();
todayCalendar.add(Calendar.DAY_OF_YEAR, -7);
final long aWeekAgoTimestamp = todayCalendar.getTime().getTime();
final String selection = TABLE_COLUMN_DATE_CREATED + " BETWEEN " + aWeekAgoTimestamp + " AND " + todayTimestamp;

Resources