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)
Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)
Get connected with me. :) LinkedIn Twitter Instagram Facebook