Order By clause is used to sort the records based on some column or columns in ascending or descending order. It sorts the records in ascending order by default. We can use the desc keyword to sort the records in the descending order.
Syntax:
SELECT column1, column2, ... FROM table_name WHERE condition ORDER BY column1, column2, ... ASC|DESC;
SELECT statement Syntax:
SELECT column1, column2, ... FROM table_name
Where condition Syntax:
SELECT column1, column2, ... FROM table_name WHERE condition
Order By clause Syntax:
SELECT column1, column2, ... FROM table_name WHERE condition ORDER BY column1, column2, ... ASC|DESC;
Python MySQL Order By Example:
Following is an example of using Order By clause in MySQL using Python:
Python MySQL Order By Example – Sort By One Column in Ascending Order
Python MySQL connector provides a method cursor.execute() to execute a SELECT statement. It returns table-like data that can be fetched using methods such as fetchall(), fetchmany(), or fetchone().
Consider the following example:
import mysql.connector # make connection mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) # get cursor mycursor = mydb.cursor() # prepare sql query sql = "SELECT * FROM students ORDER BY name" # execute the query mycursor.execute(sql) # get the result result = mycursor.fetchall() # print the result for row in result: print(row)
Output:
('Amy', 89) ('John', 90) ('Mira', 92) ('Rohit', 93) ('Tom', 95)
Python MySQL Order By Example – Sort By One Column in Descending Order
Consider the following example:
import mysql.connector # make connection mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) # get cursor mycursor = mydb.cursor() # prepare sql query sql = "SELECT * FROM students ORDER BY name DESC" # execute the query mycursor.execute(sql) # get the result result = mycursor.fetchall() # print the result for row in result: print(row)
Output:
('Tom', 95) ('Rohit', 93) ('Mira', 92) ('John', 90) ('Amy', 89)
Python MySQL Order By Example – Sort By Multiple Columns
Consider the following example:
import mysql.connector # make connection mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) # get cursor mycursor = mydb.cursor() # prepare sql query sql = "SELECT * FROM students ORDER BY marks DESC, name" # execute the query mycursor.execute(sql) # get the result result = mycursor.fetchall() # print the result for row in result: print(row)
Output:
('Tom', 95) ('Rohit', 93) ('Mira', 92) ('John', 90) ('Amy', 89)