How do I delete a fixed number of rows with sorting in PostgreSQL?
You could try using the ctid
:
DELETE FROM logtable
WHERE ctid IN (
SELECT ctid
FROM logtable
ORDER BY timestamp
LIMIT 10
)
The ctid
is:
The physical location of the row version within its table. Note that although the
ctid
can be used to locate the row version very quickly, a row'sctid
will change if it is updated or moved byVACUUM FULL
. Thereforectid
is useless as a long-term row identifier.
There's also oid
but that only exists if you specifically ask for it when you create the table.
Delete with sorting in PostgreSQL
The only way I can think of is delete in a loop.
Here's an example using a cursor:
DO $$
DECLARE
test1_row test1%ROWTYPE;
DECLARE cur CURSOR FOR SELECT * FROM test1 ORDER BY co DESC FOR UPDATE;
BEGIN
FOR test1_row IN cur
LOOP
DELETE FROM test1 WHERE CURRENT OF cur;
END LOOP;
END $$
An example without a cursor:
DO $$
DECLARE
test1_row test1%ROWTYPE;
BEGIN
FOR test1_row IN SELECT * FROM test1 ORDER BY co DESC
LOOP
DELETE FROM test1 WHERE th = test1_row.th AND co = test1_row.co AND ty = test1_row.ty;
END LOOP;
END $$
Note: the WHERE
condition in DELETE
statement above is not reliable because test1
table does not have a primary/unique key. In other cases, you could just use: WHERE id = row.id
How to delete first few records from a table without any criteria in PostgreSQL?
Try to prepare subquery with LIMIT
as below
DELETE FROM txn_log
WHERE txn_log_pgm_id IN (SELECT txn_log_pgm_id
FROM txn_log
ORDER BY txn_log_timestamp asc
LIMIT 500)
Delete ranges of id's
You could do it this way:
DELETE
FROM users
WHERE
id between 754 and 759
OR id between 765 and 799
Related Topics
How to Select Date Without Time in SQL
How to Find Rows in One Table That Have No Corresponding Row in Another Table
SQL Speed Up Performance of Insert
Query a Database Based on Result of Query from Another Database
Insert All Values of a Table into Another Table in SQL
How to Execute an in Lookup in SQL Using Golang
How to Convert from Varbinary to Char/Varchar in MySQL
In SQL Server How to Pivot for Multiple Columns
How to Group by Date Time Column Without Taking Time into Consideration
SQL - Query to Get Server's Ip Address
How to Pass a List as a Parameter in a Stored Procedure
Is There a Product Function Like There Is a Sum Function in Oracle SQL
Postgresql Generate Sequence with No Gap
Why Is Iterating Through a Large Django Queryset Consuming Massive Amounts of Memory
Select Rows Where Column Value Has Changed