← Back to PHP Course | Chapter 11: Database | Lesson 18 of 21

PHP MySQL Order By

किसी database से return होने वाली rows किसी particular guaranteed order में नहीं आतीं जब तक आप explicitly एक न माँगें -- ORDER BY किसी SELECT query के results को एक या ज़्यादा columns से sort करता है, ascending या descending, जो एक alphabetized user list से लेकर एक "newest first" activity feed तक हर चीज़ के लिए ज़रूरी है।
Syntax
php
SELECT * FROM table_name ORDER BY column;             -- ascending
SELECT * FROM table_name ORDER BY column DESC;        -- descending
SELECT * FROM table_name ORDER BY column1, column2;

Results को Ascending Sort करना

ORDER BY column default रूप से किसी query के results को उस column से ascending order में sort करता है -- सबसे छोटे numbers पहले, सबसे पहले dates पहले, या text के लिए alphabetical order -- exactly जैसे आप एक plain, unqualified sort के behave करने की उम्मीद करेंगे।

उदाहरण: Sorting Results Ascending

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (name TEXT)");
$db->exec("INSERT INTO users VALUES ('Carol'), ('Alice'), ('Bob')");
// Declare `$result`, set to `$db->query("SELECT * FROM users ORDER BY name")`
$result = $db->query("SELECT * FROM users ORDER BY name");
// Keep looping while `$row = $result->fetchArray(SQLITE3_ASSOC)` holds
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    // Print `$row['name'] . "\n"` to the output
    echo $row['name'] . "\n";
}
?>

Results को Descending Sort करना

ORDER BY column DESC sort direction reverse कर देता है -- सबसे बड़ी values, सबसे नए dates, या reverse-alphabetical text पहले -- आमतौर पर सबसे नया content पहले दिखाने के लिए इस्तेमाल होता है, जैसे किसी blog की सबसे recent posts या एक activity feed के latest events।

उदाहरण: Sorting Results Descending

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE posts (title TEXT, created TEXT)");
$db->exec("INSERT INTO posts VALUES ('Old', '2023-01-01'), ('New', '2024-01-01')");
// Declare `$result`, set to `$db->query("SELECT * FROM posts ORDER BY created DESC")`
$result = $db->query("SELECT * FROM posts ORDER BY created DESC");
// Keep looping while `$row = $result->fetchArray(SQLITE3_ASSOC)` holds
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    // Print `$row['title'] . "\n"` to the output
    echo $row['title'] . "\n";
}
?>

कई Columns से Sort करना

ORDER BY col1, col2 मुख्य रूप से col1 से sort करता है, और सिर्फ उन rows के बीच order decide करने के लिए col2 इस्तेमाल करता है जिनकी col1 value exact same है -- जैसे किसी class roster को last name से, फिर same last name share करने वाले students के बीच ties तोड़ने के लिए first name से sort करना।

उदाहरण: Sorting by Multiple Columns

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE students (last_name TEXT, first_name TEXT)");
$db->exec("INSERT INTO students VALUES ('Smith','Bob'), ('Smith','Alice')");
// Declare `$result`, set to `$db->query("SELECT * FROM students ORDER BY last_name, first_name")`
$result = $db->query("SELECT * FROM students ORDER BY last_name, first_name");
// Keep looping while `$row = $result->fetchArray(SQLITE3_ASSOC)` holds
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    // Print `$row['first_name'] . " " . $row['last_name'] . "\n"` to the output
    echo $row['first_name'] . " " . $row['last_name'] . "\n";
}
?>

ORDER BY को WHERE के साथ Combine करना

ORDER BY एक WHERE clause के साथ मिलकर काम करता है, पहले rows filter करते हुए और फिर जो भी बचे उसे sort करते हुए -- SQL statement में WHERE हमेशा ORDER BY से पहले आता है, और sort सिर्फ पहले से filter pass कर चुकी rows पर apply होता है।

उदाहरण: Combining ORDER BY with WHERE

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (name TEXT, status TEXT)");
$db->exec("INSERT INTO users VALUES ('Bob','active'), ('Alice','active'), ('Carol','inactive')");
// Declare `$result`, set to `$db->query("SELECT * FROM users WHERE status = 'active' ORDER BY name")`
$result = $db->query("SELECT * FROM users WHERE status = 'active' ORDER BY name");
// Keep looping while `$row = $result->fetchArray(SQLITE3_ASSOC)` holds
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    // Print `$row['name'] . "\n"` to the output
    echo $row['name'] . "\n";
}
?>

एक Expression या Alias से Sort करना

ORDER BY सिर्फ एक plain column name से आगे भी sort कर सकता है -- यह एक computed expression (जैसे एक calculated total) या SELECT clause में किसी column को दिए गए alias को भी accept करता है, आपको ऐसी values से sort करने देते हुए जो अपने खुद के stored column की तरह exist नहीं करतीं।

उदाहरण: Sorting by an Expression or Alias

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE items (name TEXT, price INTEGER, qty INTEGER)");
$db->exec("INSERT INTO items VALUES ('A', 10, 2), ('B', 5, 10)");
// Declare `$result`, set to `$db->query("SELECT name, (price * qty) as total FROM items ORDER BY total DESC")`
$result = $db->query("SELECT name, (price * qty) as total FROM items ORDER BY total DESC");
// Keep looping while `$row = $result->fetchArray(SQLITE3_ASSOC)` holds
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    // Print `$row['name'] . ": " . $row['total'] . "\n"` to the output
    echo $row['name'] . ": " . $row['total'] . "\n";
}
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह मान लेना कि किसी table का natural row order (जैसे insertion order) बिना एक explicit ORDER BY के reliable है -- MySQL बिना एक के किसी particular order की guarantee नहीं देता।
  2. किसी बड़े result set को fetch करने के बाद PHP के sort functions से purely sort करना, जबकि खुद SQL query में ORDER BY कहीं ज़्यादा efficient है और table indexes इस्तेमाल कर सकता है।
  3. ASC/DESC direction भूल जाना और intended से opposite sort order पाना -- ASC (ascending, default) सबसे छोटे/शुरुआती को पहले sort करता है, DESC सबसे बड़े/नवीनतम को पहले।
चैप्टर सारांश
  • ORDER BY column query results को उस column से sort करता है, default रूप से ascending।
  • ORDER BY column DESC इसके बजाय descending order में sort करता है, सबसे बड़ी या सबसे recent values पहले।
  • ORDER BY col1, col2 पहले col1 से sort करता है, ties तोड़ने के लिए col2 सिर्फ तभी इस्तेमाल करते हुए जहाँ col1 values equal हों।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.