2

The simplified version is this: I have a table with two fields. The first field, trx, will always have a value. The second field, tstop, can be either null or a timestamp.

I would like to organize the output from the select such that the first "group" of records all have tstop of null, the remaining records have a non-null value of tstop. Each group is ordered by trx desc.

How is this done?

TABLE rx
(
  recid serial NOT NULL,
  trx timestamp without time zone NOT NULL,
  tstop timestamp without time zone
)

Example values:
recid    trx                      tstop
36;      "2014-06-10 13:05:16";   "";
113759;  "2014-06-10 13:05:16";   "";
33558;   "2014-03-31 18:08:15";   "2014-03-31 18:08:15";
12535;   "2014-03-31 18:08:15";   "";
660;     "2014-03-31 18:05:59";   "";
144209;  "2014-03-30 19:21:14";   "";

Desired Output:

 recid         trx                  tstop
 36;      "2014-06-10 13:05:16";   "";
 113759;  "2014-06-10 13:05:16";   "";
 12535;   "2014-03-31 18:08:15";   "";
 660;     "2014-03-31 18:05:59";   "";
 144209;  "2014-03-30 19:21:14";   "";
 33558;   "2014-03-31 18:08:15";   "2014-03-31 18:08:15";

This obviously will not work:

select * from rx order by trx desc;

3 Answers 3

2

You could use IS NULL:

SELECT *
FROM rx
ORDER BY tstop IS NULL DESC, trx DESC

SqlFiddleDemo

Sign up to request clarification or add additional context in comments.

Comments

1

Just order by the columns and use the option nulls first to make null values appear first:

SELECT *
FROM rx
ORDER BY tstop DESC NULLS FIRST, trx DESC

1 Comment

NULLS FIRST is nice option, but check demo last two records, OP wants grouping by NULL/NOT NULL and order by trx DESC
0

ORDER BY (CASE WHEN tstop IS NULL THEN 1 ELSE 0 END) DESC, tstop DESC

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.