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.

1

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.