MySQL delete data from a table - java

I have timestamp value in a column of my table.I need to keep all the data of the last week and delete rest data in the table(which is not belong to last 7 days).How can I do it?
The query that I tried is given below.
DELETE * FROM EmailMainTable WHERE DATE_FORMAT(timestamp, '%Y-%m-%d %H:%i:%s') >
DATE_SUB(DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s'), INTERVAL 8 DAY);
NOTE: My Filed Name is timestamp and i converted it to bigint
My table's structure:

Since you're converting the timestamps to varchars (using date_format), they will be compares lexicographically, which isn't the behavior you want. Just drop the formatting:
DELETE
FROM EmailMainTable
WHERE `timestamp` > DATE_SUB(NOW(), INTERVAL 8 DAY);

Finally I found the answer for my own question.
This is the answer that worked for me.
DELETE
FROM EmailMainTable
WHERE FROM_UNIXTIME(timestamp/1000,"%Y-%m-%d") < DATE_SUB(NOW(), INTERVAL 8 DAY);

Related

How do I convert between org.hibernate.type.TimestampType and Oracle SYSDATE?

I have a column that is mapped in hibernate using org.hibernate.type.TimestampType. How can I use native Oracle SQL to store and retrieve these values based on an Oracle TIMESTAMP?
The column is mapped as NUMBER(10). I tried using some formulas I found for Unix timestamps, but they did not seem to produce the correct results.
Here is a recent timestamp:
1579730473525
This would have been some date within the last 2-3 weeks (Jan 2020).
Details
I want to use Hibernate Envers, with the ValidityAuditStrategy. I'm running into trouble because I'm applying Envers to a database of existing records that have no audit history. What I'm trying to do is do a one-time insert of audit data, using Oracle SYSDATE as the timestamp.
I wasn't sure what format your number 1579730473525 was in, so I took a guess and took the first 10 digits using a SUBSTR, and the result was a reasonable 2020 date as follows.
SELECT TO_DATE('1970-01-01','YYYY-MM-DD') +
NUMTODSINTERVAL(TO_NUMBER(SUBSTR('1579730473525',1,10)), 'SECOND') FROM dual;
returns
22/01/2020 22:01:13
Then to get the TIMESTAMP, I added the last 4 digits.
SELECT to_char(TO_DATE('1970-01-01','YYYY-MM-DD') +
NUMTODSINTERVAL(TO_NUMBER(SUBSTR('1579730473525',1,10)), 'SECOND') ,'YYYY-MM-DD hh:mm:ss') ||'.'||SUBSTR('1579730473525',10,4)
FROM dual;
and this returns:
2020-01-22 10:01:13.3525
(I couldn't find a way of directly converting the 14 digit number back to a YYYY-MM-DD hh:mm:ss:ff format; it complained of precision)
Then to get the number into TIMESTAMP format:
SELECT TO_TIMESTAMP(TO_CHAR(TO_DATE('1970-01-01','YYYY-MM-DD') +
NUMTODSINTERVAL(TO_NUMBER(SUBSTR('1579730473525',1,10)), 'SECOND') ,'YYYY-MM-DD hh:mi:ss') ||'.'||SUBSTR('1579730473525',10,4),'YYYY-MM-DD hh:mi:ss:ff')
FROM dual;
and this returns it in the Oracle TIMESTAMP as requested, using Oracle SQL.
Just a hint: if you leave out formatting, make a note of your NLS parameter NLS_TIMESTAMP_FORMAT in case you get formatting issues.

How to select Date between Two date?

I want to select date between (System date - 2 hour ) to (system date)
I tested this for selecting records in the last two hours and it works.
#SQL Server
SELECT
*
FROM
table
WHERE
datetime_col >= DATEADD(hh, -2, CURRENT_TIMESTAMP)
AND
datetime_col <= CURRENT_TIMESTAMP;
I'm less familiar with Oracle but here is a possible solution I found online.
#oracle
SELECT
*
FROM
table
WHERE
datetime_col BETWEEN LOCALTIMESTAMP - 1/24 AND LOCALTIMESTAMP
Oracle Forum: Find record count between two time stamps

select query to find max date in a row

want help in sql query, I am using H2 database
i have 12 dates (date with time) in a row, field name like Date_1, Date_2, Date_3... Date_12
like to know which has max date and Time. have to know whether is there any date which is less than 10 minutes from current time.
can some one help in sql query for the above
You can use GREATEST to find max value from current row:
SELECT GREATEST(Date_1, Date_2, Date_3,... ,Date_12) AS Max_date_in_row
FROM your_table;
To find out:
is there any date which is less than 10 minutes from current time
SELECT *
FROM your_table
WHERE GREATEST(Date_1, Date_2, Date_3,... ,Date_12) > DATE_ADD(NOW(), INTERVAL -10 MINUTE);

Mysql between dates is not working

I'm writing the below query to get records between two dates. I'm using Mysql version 5.5. May its duplicate exactly I didn't know. But no answer working for me so that I'm asking. I'm following least date after latest date. Even though its not working.
Problem: Empty resultset.
pstmt=con.prepareStatement("SELECT urlid FROM youtubevideos WHERE lastwatched >=? AND lastwatched <=? order by id desc LIMIT 8");
pstmt.setString(1,previousdate);//14-05-2015
pstmt.setString(2,currentdate);//12-08-2015
rs=pstmt.executeQuery();
while(rs.next())
{
.........
}
But I'm getting empty resultset.
My table youtubevideos contains records
urlid lastwatched
-------------------
url1 12-08-2015
url2 11-08-2015
url3 08-05-2015
url4
url5 10-08-2015
Above is some data. Here lastwatched is of varchar and lastwatched is empty for some records. If my previous date 08-05-2015 means less than the current day (12) then above query working. Otherwise (from 13-05-2015 onwards) its not working. Any suggestions please.
You are using wrong date format for sql:
12-08-2015 // this is the output format
use yyyy-MM-dd instead:
2015-08-12 // this is the sql store format
This query works great in my Mysql database:
SELECT * FROM your_table where DATE <= "2015-05-08" AND DATE >= "2015-08-12"
To convert your strings:
Date initDate = new SimpleDateFormat("dd-MM-yyyy").parse(date);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String parsedDate = formatter.format(initDate);
Here lastwatched is of varchar
The issue is that you are storing date fields as type VARCHAR. This would work if your date format was Y-m-d since sorting this alphabetically is the same as sorting by date.
I recommend you change the lastwatched column to be a date type, this will allow the BETWEEN to work correctly and will also provide access to the date functions in MySQL.
Fix the data in the table. You should not be storing bona fide dates as varchar(). MySQL has a great data type for them, called date (or perhaps datetime.
Here is one method:
alter table youtubevideos add column NEW_lastwatched date;
update youtubevideos
set NEW_lastwatched = str_to_date(lastwatched, '%d-%m-%Y');
alter table drop column lastwatched;
alter table rename column NEW_lastwatched lastwatched date;
Then, pass in your parameters in the ISO standard format 'YYYY-MM-DD' and your problems with dates using this column will be fixed.

Getting the totalworkingdays dates through passing the dates dynamically

This is my MySQL database table structure and attendancedate datatype is Date:
attendancedate-------admissionnumber------------attendance
2013-10-03-----------LSTM-0008/2013-2014--------present
2013-10-09-----------LSTM-0008/2013-2014--------present
2013-11-02-----------LSTM-0008/2013-2014--------absent
and i want to disaply like that
monthname---------totalworkingdays---------present----absent
october-------------- 2--------------------2----------0
November--------------1--------------------0-----------1
so am writing the below MySQL query:
select monthname(attendencedate) as monthname,
(select distinct count(*)
from lstms_attendence
where attendencedate>='2013-10-03'
and attendencedate<='2013-10-09'
and addmissionno='LSTM-0008/2013-2014')as totalworkingdays,
sum(CASE WHEN attendence = 'present' THEN 1 ELSE 0 END) as present,
SUM(CASE WHEN attendence = 'absent' THEN 1 ELSE 0 END) AS absent
FROM lstms_attendence
WHERE addmissionno='LSTM-0008/2013-2014' GROUP BY monthname(attendencedate);
But the query is display like this:
monthname---------totalworkingdays---------present----absent
November-----------3-----------------------0------------2
October------------3-----------------------2------------1
please give me the exact query and here am passing dates as hardcoded but that dates are passing dynamically through java to that query.
Let me know the how to create dynamically dates and how to pass values to that query.
Try this:
SELECT
MONTHNAME(attendencedate) as the_month,
COUNT(*) as working_days,
SUM(IF(attendance='present',1,0)) as is_present,
SUM(IF(attendance='absent',1,0)) as is_absent
FROM
lstms_attendence
WHERE
addmissionno='LSTM-0008/2013-2014'
GROUP BY
the_month
Your question doesn't make clear what you're asking. What's wrong with your resultset? Is it the presence of your "november" row?
At any rate, you've got an excessively complex query here, as well as one which will break if you happen to include data from multiple years in it.
Instead of using MONTHNAME(attendancedate), we'll use
DATE_FORMAT(attendancedate, '%Y-%c-01') AS attendancemonth
to figure out in which month an attendancedate lies. This simply turns '2013-11-15' into '2013-11-01', the first day of the month in question. In other words, it truncates (rounds down) the date to the first day of the month.
SELECT admissionnumber,
DATE_FORMAT(attendancedate, '%Y-%c-01') AS attendancemonth,
COUNT(*) AS working_days,
SUM(IF(attendance='present',1,0)) AS is_present,
SUM(IF(attendance='absent',1,0)) AS is_absent
FROM lstms_attendence
WHERE attendancedate >= '2013-10-03'
AND attendancedate < '2013-10-06' + INTERVAL 1 DAY
AND admissionnumber='LSTM-0008/2013-2014'
GROUP BY admissionnumber,attendancemonth
Here is a sqlfiddle.http://sqlfiddle.com/#!2/a2dfb/7/0
This summarizes by both admissionnumber and month, so you can produce a report that contains multiple admissions if you want that.
It uses attendancedate < 'last' + INTERVAL 1 DAY in place of attendancedate <= 'last' because that is robust in cases where attendancedate contains a timestamp other than midnight.
If you need to pass in your parameters from Java, use a prepared statement. Replace the constants in the SQL query with ?, and use setTimestamp and setString. For one example, see JDBC Prepared Statement . setDate(....) doesn't save the time, just the date.. How can I save the time as well?

Categories