How to find records added to a database table in the last 24 hours?

I use MySQL in particular, but I hope for a solution for different vendors. I use the NOW () function to add a timestamp as a column for each record.

INSERT INTO messages (typeId, messageTime, stationId, message) VALUES (?, NOW(), ?, ?) 
+4
source share
6 answers
 SELECT * FROM messages WHERE DATE_SUB(CURDATE(),INTERVAL 1 DAY) <= messageTime 
+4
source

SQL Server query:

 Select * From Messages Where MessageTime > DateAdd(dd, -1, GetDate()) 

As far as I can tell (unverified!) MySQL equivalent

 Select * From Messages Where MessageTime > ADDDATE(NOW(), INTERVAL -1 DAY) 
+2
source

For Sybase SQL Anywhere:

 Select * From Messages Where MessageTime > dateadd( day, -1, now() ) 
+1
source

For Oracle

 SELECT * FROM messages WHERE messageTime > SYSDATE - 1 

(the psuedo SYSDATE variable includes the time, so sysdate -1 will give you the last 24 hours)

+1
source

There is no solution for a cross database, since most of them have their own syntax and semantics for date processing (and basically interval representation).

In PostgreSQL it will be

 SELECT * FROM messages WHERE messagetime >= messagetime - interval '1 day' 
0
source

If you access this from an API-based client (I assume this is because of the โ€œ? In the queryโ€), you can do this from within your program, not through SQL.

Note. The rest is for JDBC syntax, other APIs / languages โ€‹โ€‹will be different from the syntax, but should be conceptually the same.

On the side of the insert do

 PreparedStatement stmt = connection.prepareStatement( "INSERT INTO messages " + "(typeId, messageTime, stationId, message) VALUES " + "(?, ?, ?, ?)" ); stmt.setInt(1, typeId); stmt.setDate(2, new java.sql.Date(System.currentTimeMillis())); stmt.setInt(3, stationId); stmt.setString(4, message); 

On the request side, do:

 PrepatedStatement stmt = connection.prepareStatement( "SELECT typeId, messageTime, stationId, message " + "from messages where messageTime < ?"); long yesterday = System.currentTimeMillis() - 86400000; // 86400 sec/day stmt.setDate(1,new java.sql.Date(yesterday)); 

This should work in a portable way.

0
source

Source: https://habr.com/ru/post/1276669/


All Articles