Select Query Order By
Example: Order by Ascending
import mysql.connector
from mysql.connector import errorcode
try:
# Connecting with MySql
con = mysql.connector.connect(user='root', password='mysql', host='127.0.0.1', database='company')
# Using cursor() method to create cursor object
cursor = con.cursor()
# SQL query with where clause to fetch data.
sql_query = (
"SELECT * FROM EMPLOYEE order by EMP_ID"
)
# Executing query
cursor.execute(sql_query)
# Fetch all records
rows = cursor.fetchall()
for row in rows:
print(row)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Your user name or password is incorrect")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
con.close()
Example: Order By Descending
import mysql.connector
from mysql.connector import errorcode
try:
# Connecting with MySql
con = mysql.connector.connect(user='root', password='mysql', host='127.0.0.1', database='company')
# Using cursor() method to create cursor object
cursor = con.cursor()
# SQL query with where clause to fetch data.
sql_query = (
"SELECT * FROM EMPLOYEE order by EMP_ID DESC"
)
# Executing query
cursor.execute(sql_query)
# Fetch all records
rows = cursor.fetchall()
for row in rows:
print(row)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Your user name or password is incorrect")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
con.close()
Conclusion
Well, in this topic, we have learnt to use order by in the MySQL query. The order by keyword is used to get data into an order such as either ascending or descending order.
In our next topic, we will learn to use limit in table inside this database. Till then keep learning and practice.