Jam Eel Ahmed
Jam Eel Ahmed

Reputation: 79

SQL order by in union all query

I have following query which produces following below data. All I want to show list of users in Alphabetically order and First Record should be All , All.

enter image description here

Query:

SELECT 'All' created_by,
       'All' Prepby
FROM dual
UNION ALL
SELECT DISTINCT
       to_char(d.created_by) AS created_by,
       get_user_name(d.created_by) Prepby
FROM Hpml_Gp_dtl d
WHERE d.created_by IS NOT NULL
ORDER BY 2;

Upvotes: 0

Views: 3025

Answers (2)

MT0
MT0

Reputation: 168741

Perform the ORDER BY in a sub-query:

SELECT 'All' AS created_by,
       'All' AS Prepby
FROM   DUAL
UNION ALL
SELECT *
FROM   (
  SELECT DISTINCT
         to_char(created_by),
         get_user_name(created_by)
  FROM   Hpml_Gp_dtl
  WHERE  created_by IS NOT null
  ORDER BY 2
)

Upvotes: 0

Ullas
Ullas

Reputation: 11566

Use a CASE expression in ORDER BY.

Query

select t.* from (
    select 'All' created_by, 'All' Prepby
    from dual
    union all
    select distinct to_char(d.created_by) as created_by,
    get_user_name(d.created_by) Prepby
    from Hpml_Gp_dtl d
    where d.created_by is not null
) t
order by case Prepby when 'All' then 1 else 2 end, Prepby;

Upvotes: 1

Related Questions