Get Started

Deleting all the records from a table

Often, you'll need to empty a table of all of its records so you can reload the data. You can do this with a delete statement with just the table as an argument. For example, in the video, Jason deleted the table extra_employees by executing as follows:

delete_stmt = delete(extra_employees)
result_proxy = connection.execute(delete_stmt)

Do be careful, though, as deleting cannot be undone!

This is a part of the course

“Introduction to Databases in Python”

View Course

Exercise instructions

  • Import delete and select from sqlalchemy.
  • Build a delete statement to remove all the data from the census table. Save it as delete_stmt.
  • Execute delete_stmt via the connection and save the results.
  • Submit the answer to select all remaining rows from the census table and print the result to confirm that the table is now empty!

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Import delete, select
from sqlalchemy import ____, ____

# Build a statement to empty the census table: stmt
delete_stmt = ____

# Execute the statement: results
results = ____

# Print affected rowcount
print(results.rowcount)

# Build a statement to select all records from the census table : select_stmt
select_stmt = select([census])

# Print the results of executing the statement to verify there are no rows
print(connection.execute(select_stmt).fetchall())

This exercise is part of the course

Introduction to Databases in Python

IntermediateSkill Level
4.4+
14 reviews

In this course, you'll learn the basics of relational databases and how to interact with them.

In the previous chapters, you interacted with existing databases and queried them in different ways. Now, you will learn how to build your own databases and keep them updated.

Exercise 1: Creating databases and tablesExercise 2: Creating tables with SQLAlchemyExercise 3: Constraints and data defaultsExercise 4: Inserting data into a tableExercise 5: Inserting a single rowExercise 6: Inserting multiple records at onceExercise 7: Loading a CSV into a tableExercise 8: Updating data in a tableExercise 9: Updating individual recordsExercise 10: Updating multiple recordsExercise 11: Correlated updatesExercise 12: Deleting data from a databaseExercise 13: Deleting all the records from a table
Exercise 14: Deleting specific recordsExercise 15: Deleting a table completely

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free