0

In the following table, I want to set delete = true if the total records for same orgid exceed 500 and I want to do it according to createdate such that if records exceed 500 the old records get deleted and make total records 500 for that orgid.

here is my table

Table A
+----+-------+------------------+--------+------------+
| id | orgid | transactionvalue | delete | createdate |  
+----+-------+------------------+--------+------------+
|  1 |     1 |              123 | false  | 05-16-2020 |  
|  2 |     1 |              412 | false  | 07-16-2020 |  
|  3 |     2 |              762 | false  | 07-16-2020 |  
+----+-------+------------------+--------+------------+

Here is the query I am trying

update A 
set 
  delete = true 
where orgid = 1 
and (select count(*) as records 
      from (select * 
            from A order by createdate
    ) as pseudotable)) >500
3
  • 2
    You could clarify and simplify by providing sample data for 3 companies (5 each) keeping 2. Commented Jul 16, 2020 at 13:36
  • 1
    What version of MySQL are you running? Commented Jul 16, 2020 at 13:53
  • @EricBrandt 8.0.17 Commented Jul 17, 2020 at 11:18

3 Answers 3

1

use subquery and join update

   UPDATE tablea
            INNER JOIN
        (select orgid, count(*) cnt from tablea group by orgid
        ) b ON tablea.orgid = b.orgid 
    SET 
        delete = 'true'
    where cnt>500
Sign up to request clarification or add additional context in comments.

2 Comments

Createdate has to feature here somewhere surely?
order by createdate desc ?
1

You can use row_number() to find the 500th record for each org and then use that information:

update tablea a join
       (select a2.org_id, a2.created_date as cutoff_created_date
        from (select a2.*,
                     row_number() over (partition by a2.org_id order by create_date desc) as seqnum
              from tablea a2
             ) a2
        where a2.seqnum = 500
       ) a2
       on a.org_id = a2.org_id and and
          a.created_date < a2.cutoff_created_date
    set delete = true;

Comments

0

I did not try all of the other answers, they might be correct but this is what worked for me

update A 
set `delete` = true 
where orgid = 1 AND id IN (
SELECT id FROM  A where orgid = 1
order by createdate DESC
LIMIT 500,18446744073709551615);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.