Oracle rownum + order by

Written on 22 August 2014, 09:39am

Tagged with: ,

Don’t do:


SELECT first_name, last_name
FROM employees 
WHERE  rownum = 1
ORDER BY creation_date DESC

You probably want to do this instead:


SELECT * from (
 SELECT first_name, last_name
 FROM employees 
 ORDER BY creation_date DESC
) where rownum = 1 

The first query takes the first row returned by Oracle and orders it by creation_date.
The second query gets the first row of the sub-query that contains the sorted records.
More on Stack Overflow

Versailles

Oracle – merge multiple records into single row

Written on 15 May 2014, 10:09am

Tagged with: ,

Another post in the series ‘remember this SQL trick‘ 🙂

The within group clause can be used to merge multiple records into a single row. In the classic emp table with ename and deptno columns, the query is:


select
   deptno,
   listagg (ename, ',') 
WITHIN GROUP 
(ORDER BY ename) enames
FROM 
   emp
GROUP BY 
   deptno

The article below displays more ways of doing this, but the query above worked for me.
Oracle SQL: displaying multiple column values per row