Search code examples
pythonmysqlsqlalchemyalter

Permanently sorting a table using SQLAlchemy


I have made a connection to the mysql database and trying to sort two columns of a table as:

import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import text
import pandas as pd
engine_query="mysql+pymysql://"+username+":"+password+"@"+server+"/"+database
engine = sqlalchemy.create_engine(engine_query)
with engine.connect() as conn:
    conn.execute(text("ALTER TABLE NG_Inventory_Inputs ORDER BY Contract_Name asc, Date asc"))

Above code is not showing any error but also respective columns does not get sorted in the table. It is same as previous when I use the following code to see the data of the table:

query = "SELECT * FROM NG_Inventory_Inputs"
sql_engine = sqlalchemy.create_engine(engine_query).connect()
data = pd.read_sql(query, sql_engine)

Can anyone please help me to sort the columns of a table without creating another table using sqlalchemy or any other library in python ?
Any help would be appreciated.


Solution

  • A table, by definition, has no "order".

    Output from a SELECT can be sorted dynamically via the ORDER BY clause. A suitable INDEX may make that run faster.

    Would you like to explain what your goal is.