The ORDER BY keyword is used to sort the result.
SELECT columnName(s) FROM tableName ORDER BY columnName [ASC|DESC]; |
The ORDER BY clause is used to sort the rows.
The "Books" table:
Title |
Author |
Publisher |
Year |
الدورة الدموية |
إبن النفيس |
دار العلم |
1650 |
Java 2 |
L. Johnston |
Fast Press |
2002 |
Linux and Unix |
J. Sam |
Fast Press |
2004 |
Operating Systems |
M. Stone |
Coriolis |
2005 |
Web Programming |
K. Yariv |
East Edition |
2005 |
XML Language |
M. Salim |
Knowledge Press |
2000 |
To display the books ordered by their years of publication:
SELECT * FROM Books ORDER BY Year; |
The result is:
Title |
Author |
Publisher |
Year |
الدورة الدموية |
إبن النفيس |
دار العلم |
1650 |
XML Language |
M. Salim |
Knowledge Press |
2000 |
Java 2 |
L. Johnston |
Fast Press |
2002 |
Linux and Unix |
J. Sam |
Fast Press |
2004 |
Operating Systems |
M. Stone |
Coriolis |
2005 |
Web Programming |
K. Yariv |
East Edition |
2005 |
To display the books in numerical order of their years of publication AND alphabetical order of their authors:
SELECT * FROM Books ORDER BY Year, Author; |
The result is:
Title |
Author |
Publisher |
Year |
الدورة الدموية |
إبن النفيس |
دار العلم |
1650 |
XML Language |
M. Salim |
Knowledge Press |
2000 |
Java 2 |
L. Johnston |
Fast Press |
2002 |
Linux and Unix |
J. Sam |
Fast Press |
2004 |
Web Programming |
K. Yariv |
East Edition |
2005 |
Operating Systems |
M. Stone |
Coriolis |
2005 |
To display the books in reverse numerical order of their years of publication:
SELECT * FROM Books ORDER BY Year DESC; |
The result is:
Title |
Author |
Publisher |
Year |
Operating Systems |
M. Stone |
Coriolis |
2005 |
Web Programming |
K. Yariv |
East Edition |
2005 |
Linux and Unix |
J. Sam |
Fast Press |
2004 |
Java 2 |
L. Johnston |
Fast Press |
2002 |
XML Language |
M. Salim |
Knowledge Press |
2000 |
الدورة الدموية |
إبن النفيس |
دار العلم |
1650 |
To display the books in reverse numerical order of their years of publication AND alphabetical order of their authors:
SELECT * FROM Books ORDER BY Year DESC, Author ASC; |
The result is:
Title |
Author |
Publisher |
Year |
Web Programming |
K. Yariv |
East Edition |
2005 |
Operating Systems |
M. Stone |
Coriolis |
2005 |
Linux and Unix |
J. Sam |
Fast Press |
2004 |
Java 2 |
L. Johnston |
Fast Press |
2002 |
XML Language |
M. Salim |
Knowledge Press |
2000 |
الدورة الدموية |
إبن النفيس |
دار العلم |
1650 |
To test your SQL skills click here.