If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
Order By का use records को sort करने के लिए किया जाता है , आप किसी भी column का use sorting के लिए कर सकते हैं।
Ascending order में record select करने के लिए ASC और descending order के लिए DESC का use किया जाता है , By Default Table से सभी records ascending order में ही आते हैं।
# 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)
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 को आप limit के साथ भी use कर सकते हैं।
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)
C:\Users\Rahulkumar\Desktop\python>python mysql_sort.py (8, 'Raju', 'verma', None) (5, 'Gyan Singh', 'Yadav', 'gyanxyz@email.com') (4, 'Girish', 'Kumar', None)