Skip to content

Commit ab0bc64

Browse files
kapilbk1996root
andauthored
SQL-134:- How to ORDER BY the Order of Values in a SQL IN() Clause (#117)
* SQL-134:- How to ORDER BY the Order of Values in a SQL IN() Clause * Create select-case-orderby.sql * Create select-cte-orderby.sql * Create select-field-orderby.sql * Create select-temp-orderby.sql * Deleted orderby-in-clause from sql-queries-3 directory --------- Co-authored-by: root <kapilbk@[email protected]>
1 parent c981978 commit ab0bc64

File tree

4 files changed

+36
-0
lines changed

4 files changed

+36
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
SELECT id, name
2+
FROM Student
3+
WHERE id IN (1110, 1101, 1617, 1107)
4+
ORDER BY CASE
5+
WHEN id = 1110 THEN 1
6+
WHEN id = 1101 THEN 2
7+
WHEN id = 1617 THEN 3
8+
WHEN id = 1107 THEN 4
9+
ELSE 5
10+
END;
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
WITH OrderList AS (
2+
SELECT 1110 AS id, 1 AS ord
3+
UNION ALL
4+
SELECT 1101 AS id, 2 AS ord
5+
UNION ALL
6+
SELECT 1617 AS id, 3 AS ord
7+
UNION ALL
8+
SELECT 1107 AS id, 4 AS ord
9+
)
10+
SELECT s.id, s.name
11+
FROM Student s
12+
JOIN OrderList ol ON s.id = ol.id
13+
ORDER BY ol.ord;
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
SELECT id, name
2+
FROM Student
3+
WHERE id IN (1110, 1101, 1617, 1107)
4+
ORDER BY FIELD(id, 1110, 1101, 1617, 1107);
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
CREATE TEMPORARY TABLE temp_order (id INT, ord INT);
2+
INSERT INTO temp_order (id, ord) VALUES (1110, 1), (1101, 2), (1617, 3), (1107, 4);
3+
4+
SELECT s.id, s.name
5+
FROM Student s
6+
JOIN temp_order t ON s.id = t.id
7+
ORDER BY t.ord;
8+
9+
DROP TEMPORARY TABLE temp_order;

0 commit comments

Comments
 (0)