How to delete a table in SQLAlchemy? How to delete a table in SQLAlchemy? sqlite sqlite

How to delete a table in SQLAlchemy?


Just call drop() against the table object.From the docs:

Issue a DROP statement for this Table, using the given Connectable for connectivity.

In your case it should be:

User.__table__.drop()

If you get an exception like:

sqlalchemy.exc.UnboundExecutionError: Table object 'my_users' is not bound to an Engine or Connection. Execution can not proceed without a database to execute against

You need to pass the engine:

User.__table__.drop(engine)


Alternative to calling cls.__table__.drop(your_engine), you can try this:

Base.metadata.drop_all(bind=your_engine, tables=[User.__table__])

This method as well as the create_all() method accept an optional argument tables, which takes an iterator of sqlalchemy.sql.schema.Table instances.

You can control which tables are to be created or dropped in this way.


For the special case when you don't have access to the table class and just need to delete the table by table name then use this code

import loggingfrom sqlalchemy import MetaDatafrom sqlalchemy import create_enginefrom sqlalchemy.engine.url import URLfrom sqlalchemy.ext.declarative import declarative_baseDATABASE = {   'drivername': 'sqlite',   # 'host': 'localhost',   # 'port': '5432',   # 'username': 'YOUR_USERNAME',   # 'password': 'YOUR_PASSWORD',   'database': '/path/to/your_db.sqlite'}def drop_table(table_name):   engine = create_engine(URL(**DATABASE))   base = declarative_base()   metadata = MetaData(engine, reflect=True)   table = metadata.tables.get(table_name)   if table is not None:       logging.info(f'Deleting {table_name} table')       base.metadata.drop_all(engine, [table], checkfirst=True)drop_table('users')