ใช้ ORDER BY CASE WHEN เพื่อ "ปักหมุด" (Pin) แถวที่มีค่าเฉพาะ (เช่น ชื่อ John) ให้อยู่บนสุด แล้วค่อยเรียงส่วนที่เหลือตามปกติ
ตัวอย่างการสร้างตาราง
mysql> create table DemoTable (
StudentName varchar(100),
StudentMarks int );
Query OK, 0 rows affected (0.97 sec)
เพิ่มข้อมูล (มีชื่อ John 3 คน)
mysql> insert into DemoTable values('Chris',45);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('John',67);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('David',89);
Query OK, 1 row affected (0.46 sec)
mysql> insert into DemoTable values('John',98);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Mike',79);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('John',99);
Query OK, 1 row affected (0.11 sec)
แสดงข้อมูลก่อนจัดเรียง
mysql> select * from DemoTable;
+-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | Chris | 45 | | John | 67 | | David | 89 | | John | 98 | | Mike | 79 | | John | 99 | +-------------+--------------+ 6 rows in set (0.00 sec)
คำสั่ง ORDER BY CASE ให้ John บนสุด แล้วเรียงชื่อ แล้วคะแนน
mysql> select * from DemoTable order by case StudentName when 'John' then 2 else 3 end, StudentName, StudentMarks;
ผลลัพธ์ (John 3 คนอยู่บนสุด เรียงคะแนนน้อยไปมาก)
+-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | John | 67 | | John | 98 | | John | 99 | | Chris | 45 | | David | 89 | | Mike | 79 | +-------------+--------------+ 6 rows in set (0.00 sec)
คำอธิบาย: CASE StudentName WHEN 'John' THEN 2 ELSE 3 END ให้ John = 2, อื่นๆ = 3 เรียง ASC ทำให้ 2 (John) อยู่บนสุด ในกลุ่ม John เรียงตาม StudentName (เหมือนกัน) แล้ว StudentMarks ASC
ประยุกต์ใช้: Featured products, Pinned posts, Priority users แสดงบนสุด