Python MySQL Order By

📔 : Python 🔗

Order By का use records को sort करने के लिए किया जाता है , आप किसी भी column का use sorting के लिए कर सकते हैं।


Ascending order में record select करने के लिए ASC और descending order के लिए DESC का use किया जाता है , By Default Table से सभी records ascending order में ही आते हैं।

Python MySQL Order By Example
Copy Fullscreen Close Fullscreen
# import connector class from mysql module.
import mysql.connector as myconn
mydb = myconn.connect(
  host = 'localhost',
  user = 'root',
  password = '',
  database = 'python_db'
)
db_cursor = mydb.cursor()

# sort records in descending order.
query = "SELECT * FROM users ORDER BY id DESC"
db_cursor.execute(query)
rows = db_cursor.fetchall()
for row in rows : print(row)
Output
C:\Users\Rahulkumar\Desktop\python>python mysql_sort.py
(8, 'Raju', 'verma', None)
(5, 'Gyan Singh', 'Yadav', 'gyanxyz@email.com')
(4, 'Girish', 'Kumar', None)
(2, 'Mohit', 'Kumar', 'xyz@gmail.com')
(1, 'Rahul', 'Kumar', 'changedEmail@gmail.com')

Order By with Limit

Order By को आप limit के साथ भी use कर सकते हैं।

Copy Fullscreen Close Fullscreen
import mysql.connector as myconn
mydb = myconn.connect(
  host = 'localhost',
  user = 'root',
  password = '',
  database = 'python_db'
)
db_cursor = mydb.cursor()

# get last 3 records.
query = "SELECT * FROM users ORDER BY id DESC LIMIT 3"
db_cursor.execute(query)
rows = db_cursor.fetchall()
for row in rows : print(row)
Output
C:\Users\Rahulkumar\Desktop\python>python mysql_sort.py
(8, 'Raju', 'verma', None)
(5, 'Gyan Singh', 'Yadav', 'gyanxyz@email.com')
(4, 'Girish', 'Kumar', None)

Hey ! I'm Rahul founder of learnhindituts.com. Working in IT industry more than 4.5 years. I love to talk about programming as well as writing technical tutorials and blogs that can help to others .... keep learning :)

Get connected with me - LinkedIn Twitter Instagram Facebook