I have an interesting issue with the below SELECT.
Its about ORDER BY clause; I am
Thanks a lot for your inputs. i have to sort using ORDER BY with a variable p_sortby where p_sortby can take any column_name or column position.
Try to select the ORDER BY clause as a separate column using the DECODE() function:
SELECT DECODE(p_sortby, 'ID', gl.group_id, 'NAME', group_name) AS sort, ...
...
ORDER BY 1
Edit:
I'm not sure what you mean by "doesn't work". If you mean that member_count is not sorted as you expect, use TO_CHAR(gl.member_count, '000000') to enforce a formatted string conversion. (adjust format mask to expected number of digits)
If you want to do that, you will have to do dynamic SQL with PL/SQL.
DECLARE
sql_str VARCHAR2(500);
sortby VARCHAR2(30) := 'your_column_name';
BEGIN
-- Dynamic PL/SQL block invokes subprogram:
sql_str := 'select * from your_table where a = 1 order by :a';
OPEN CURSOR v_your_cursor for sql_str USING sortby;
-- Then iterate your cursor.
END;
/
Seems like dynamic SQL is what you want.
When you do things like:
... and (gl.group_name_key like '%' || p_name || '%' or p_name is null or p_name = '')
the optimizer can't use an index on the group_name_key column. Are you sure you want to do it this way?