2

I'm beginner in SQL.

Consider my simple code:

cnx = mysql.connector.connect(user='root', password='',
                              host='127.0.0.1', database='employees')
cursor = cnx.cursor()

cursor.execute('SELECT * FROM people ORDER BY Height DESC, Weight')

my_result = cursor.fetchall()

cnx.close()

for x in my_result:
  print(x[0], x[1], x[2])

I have a people table in my employees database with columns name, Height and Weight. If I run this code, it prints the desired sorting and there's no problem. But, it seems that this code essentially doesn't change the order of rows of the table. I mean, now if I run

SELECT * FROM people;

in terminal I get the latter table (which does not have the desired order). Now, my question is:

How can I change the order of the table to obtain a new table with desired sorting using Python? Is it possible?

Thanks.

  • Does this answer your question? [SELECT results with wrong column order with PyMySQL](https://stackoverflow.com/questions/32503795/select-results-with-wrong-column-order-with-pymysql) – Cagy79 Oct 28 '20 at 22:53

1 Answers1

1

You can create a new table like the old one and insert rows with the desired order, otherwise always run your query with ORDER BY.

To create a new table you can run a query similar to:

CREATE TABLE people_sorted LIKE people; 
INSERT people_sorted SELECT * FROM people ORDER BY Height DESC, Weight;
Thaer A
  • 2,243
  • 1
  • 10
  • 14