Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

PostgreSQL: Sort result by DateTime, but the null value should be first or last

$
0
0

I want to sort my result by date time column in ascending order but null values ​​should come first or vice versa. Suppose I have a table employee and it has the column appraisal_date if I sorted the result set by appraisal_date in ASC/DESC order it should be the null value come FIRST/LAST.
         
PostgreSQL provides keywords such as "NULLS FIRST | LAST" that help find accurate results with "ORDER BY CLAUSE."

Illustration to get the accurate result-set sort by DateTime in ascending (ASC) order but null first


First I will create an employee table


CREATETABLEemployee
(
       emp_idintgeneratedalwaysasidentity,
       nametext,
       appraisal_datedate
);

-- Here I will insert some records

INSERTINTOemployee(name,appraisal_date)
                     VALUES
                     ('Dilip','27/04/2020'),
                     ('Mamta','28/04/2020'),
                     ('Ashish',null),
                     ('Naina','30/04/2020'),
                     ('Aradhya','21/04/2020'),
                     ('Mukesh',null);


Sort Result null first



SELECT*FROMemployeeORDERBYappraisal_dateASCNULLSFIRST;


Expected result



Illustration to get the accurate result-set sort by DateTime in descending (ASC) order but null first



SELECT*FROMemployeeORDERBYappraisal_dateDESCNULLSFIRST;


Expected Result


Illustration to get the accurate result-set sort by DateTime in descending (ASC) order but null first



SELECT*FROMemployeeORDERBYappraisal_dateASCNULLSLAST;


Expected Result


Illustration to get the accurate result-set sort by DateTime in descending (ASC) order but null first



SELECT*FROMemployeeORDERBYappraisal_dateDESCNULLSLAST;


Expected Result


To support the query with an index, make it match:


CREATEINDEXappraisal_date_indexONemployee(appraisal_dateASCNULLSFIRST);


OR


CREATEINDEXappraisal_date_indexONemployee(appraisal_dateDESCNULLSLAST);




Viewing all articles
Browse latest Browse all 265