Text Size: Normal / Large

6.3. Deleting Data

So far we have explained how to add data to tables and how to change data. What remains is to discuss how to remove data that is no longer needed. Just as adding data is only possible in whole rows, you can only remove entire rows from a table. In the previous section we discussed that SQL does not provide a way to directly address individual rows. Therefore, removing rows can only be done by specifying conditions that the rows to be removed have to match. If you have a primary key in the table then you can specify the exact row. But you can also remove groups of rows matching a condition, or you can remove all rows in the table at once.

You use the DELETE command to remove rows; the syntax is very similar to the UPDATE command. For instance, to remove all rows from the products table that have a price of 10, use

DELETE FROM products WHERE price = 10;

If you simply write

DELETE FROM products;

then all rows in the table will be deleted! Caveat programmer.


User Comments


Rodolfo <rofranco AT gmail.com>
04 Jul 2006 19:58:29

Note that using aliases in DELETE queries is not allowed.

I needed to delete records from a table "parent" which where not contained in table "child" and tried this at first:

DELETE FROM parent AS p WHERE NOT EXISTS
(SELECT 'exists' FROM child AS c WHERE c.id = p.id);

since the aliases are not allowed, you have to use the full name of the "parent" table in the subquery like this:

DELETE FROM parent AS p WHERE NOT EXISTS
(SELECT 'exists' FROM child AS c WHERE c.id = parent.id);

and that works fine.

New comments cannot be added to old documentation versions.

Privacy Policy | Project hosted by our server sponsors. | Designed by tinysofa
Copyright © 1996 – 2009 PostgreSQL Global Development Group