Sobes.tech
Junior — Middle

How can you clear the contents of a table in a database by deleting all its records?

sobes.tech AI

Answer from AI

To clear the contents of a table in a database by deleting all its records, you can use SQL queries. The main methods are:

  1. DELETE FROM table_name; — deletes all records but can be slower as it deletes one record at a time and logs each deletion.
  2. TRUNCATE TABLE table_name; — quickly deletes all records, freeing space, but is not always supported in transactions.

In Python, using libraries like sqlite3 or psycopg2, it might look like this:

import sqlite3

conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('DELETE FROM table_name')  # or 'TRUNCATE TABLE table_name' for other DBMS
conn.commit()
conn.close()

It's important to choose the method based on transactional requirements and performance.