Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL DELETE FROM (SELECT * FROM table FETCH FIRST 10 ROWS ONLY)

How do I delete only a few rows in postgreSQL? I want to fetch 10 rows to delete in a subquery.

My table

enter image description here

like image 413
ArthurDatur Avatar asked Oct 09 '15 06:10

ArthurDatur


People also ask

How do I delete a specific row in PostgreSQL?

First, specify the table from which you want to delete data in the DELETE FROM clause. Second, specify which rows to delete by using the condition in the WHERE clause. The WHERE clause is optional. However, if you omit it, the DELETE statement will delete all rows in the table.

How do you delete a specific row in Pgadmin?

To delete a row, press the Delete toolbar button. A popup will open, asking you to confirm the deletion.

What is Cascade delete in PostgreSQL?

In PostgreSQL, a cascade means that a delete or update of records in a parent table will automatically delete or update matching records in a child table where a foreign key relationship is in place.

How do I delete a specific row in a database?

To remove one or more rows in a table: First, you specify the table name where you want to remove data in the DELETE FROM clause. Second, you put a condition in the WHERE clause to specify which rows to remove. If you omit the WHERE clause, the statement will remove all rows in the table.


1 Answers

You need to use a where condition as per your requirement like this:

delete from mytable where id in(1,2,3,4,5,6,7,8,9,10)

or

delete from mytable where id in(select id from mytable where someconditon)

or you can try like this if you want to delete top 10 using ctid:

DELETE FROM mytable 
WHERE ctid IN (
    SELECT ctid
    FROM mytable 
    GROUP BY s.serialId, s.valuetimestamp
    ORDER BY s.serialId
    LIMIT 10
)

If you are looking to remove the duplicates from your table then try this:

DELETE FROM mytable
 WHERE ctid NOT IN
  (SELECT MAX(s.ctid)
    FROM table s
    GROUP BY s.serialId, s.valuetimestamp);
like image 141
Rahul Tripathi Avatar answered Oct 27 '22 07:10

Rahul Tripathi