background

SQL Order By Clause

PLEASE NOTE: This tutorial comes from my FREE video course called SQL Boot Camp.

-- drop table posts;
create table posts (
  id integer,
  title character varying(100),
  content text,
  published_at timestamp without time zone
);

insert into posts (id, title, content, published_at) values (100, 'Intro to SQL', 'Epic SQL Content', '2018-01-01');
insert into posts (id, title, content, published_at) values (101, 'Intro to PostgreSQL', 'PostgreSQL is awesome!', now());
insert into posts (id, title, content)               values (102, 'Intro to SQL Where Clause', 'Easy as pie!');
insert into posts (id, title, content)               values (103, 'Intro to SQL Order By Clause', 'What comes first?');

-- undefined order
select * from posts;

-- defined order
select * from posts order by title;
select * from posts order by title desc;

-- order by two columns
select * from posts order by published_at, title;

-- advanced ordering
select * from posts order by published_at;
select * from posts order by published_at nulls first;

select * from posts order by published_at desc nulls first, id desc;

-- Putting it all together
select *
from posts
where published_at is null
order by id desc;

Please go ahead and leave a comment below if you have any questions about this tutorial.