PostgreSQL Python: Delete Data from Tables
Summary: This tutorial shows you how to delete data from PostgreSQL tables in Python.
This tutorial picks up from where the Querying Data from Tables Tutorial left off.
Steps for deleting data from a PostgreSQL table in Python
To delete data from the PostgreSQL table in Python, you use the following steps:
First, create a new database connection by calling the connect()
function of the psycopg2
module.
The connect()
function returns a new connection
object.
Next, create a new Cursor
object by calling the cursor()
method of the Connection
object:
Then, execute the DELETE statement. If you want to pass values to the DELETE
statement, you use the placeholders ( %s
) in the DELETE
statement and pass input values to the second parameter of the execute()
method.
The DELETE
statement with a placeholder for the value of the id
field is as follows:
To bind value value1
to the placeholder, you call the execute()
method and pass the input value as a tuple to the second parameter like the following:
After that, save the changes to the database permanently by calling the commit()
method of the connection
object.
Finally, close the communication with the PostgreSQL database server by calling the close()
method of the cursor
and connection
objects.
If you use context managers, you don’t need to explicitly close the cursor or connection.
Example of deleting data in PostgreSQL table in Python
We will use the parts
table in the suppliers
database for the demonstration purposes.
The following delete_part()
function deletes a row in the parts
table specified by the part_id
.
Now we run the Python program to delete the part with the part id 1.
Output:
Retrieve data from the parts
table again to confirm the deletion:
Output:
The output indicates that part id 2 has been deleted successfully.
Download the project source code
Summary
- Use the
execute()
method of acursor
object to delete a row from a table.