ORDER BY
This is our table we will use ORDER BY
on
CREATE TABLE student( student_id INT AUTO_INCREMENT, name VARCHAR(20), major VARCHAR(20), PRIMARY KEY(student_id) ); INSERT INTO student(name,major) VALUES('John','Biology'); INSERT INTO student(name,major) VALUES('Kate','Sociology'); INSERT INTO student(name,major) VALUES('Claire','Chemistry'); INSERT INTO student(name,major) VALUES('Jack','Biology'); INSERT INTO student(name,major) VALUES('Mike','Computer Science'); SELECT * FROM student;
Use ORDER BY
with SELECT
.
By default order by will display the results alphabetically or numerically
depening on the values
SELECT name , major FROM student ORDER BY name;
This will display the columns by 'names' alphabetically.
We can show the columns in desending order with DESC
SELECT * FROM student ORDER BY student_id DESC;
This will put the student_id's
in decending order
You can use these on the whole table. ASC
'acending' is default and not needed
SELECT *
from student
ORDER BY student_id ASC;
** This would be default behavior and the same as
SELECT * FROM student
We can order multiple columns, it will do the first column then order by the second and so on
SELECT *
FROM student
ORDER BY major, student_id;
In this example, the major
column takes precedence over the student_id
column
**Notice how "John's" student_id
1 comes first
We can place majors first alphabetically but add DESC
after student_id
to decend the id's too.
This place 'Jack' before 'John'.
SELECT * FROM student ORDER BY major, student_id DESC;