Not sure how to write connect by clause - oracle

I have the following query to find employees who are not managers in the EMP table of oracle
select * from emp e1
where not exists (select null from emp e2
where e2.mgr=e1.empno)
I need output using start with connect by clause , thus avoiding self join

There is a function, CONNECT_BY_ISLEAF(), which indicates whether a given row in a hierarchical query is a leaf node. In the EMP table, employees who are not managers will be leaf nodes.
So, we can use this function in a nested hierarchical query to filter the non-managers:
select empno, mgr, ename
from (
select empno, mgr, ename, CONNECT_BY_ISLEAF cbi
from emp
start with mgr is null
connect by prior empno = mgr
) where cbi = 1
/
Oracle has several neat functions for interrogating hierarchies. Find out more.

Related

converting correlated oracle subquery to single query

Hi I have two tables EMP and Dept( data as normal emp and dept tables of oracle)
I want to find the number of employees earning more than the avg(sal) of their own dept without use of correlated subquery. I wrote the query as below
SELECT * from emp e JOIN
(SELECT avg(sal) avgsal,deptno
FROM emp group by deptno )avgsal_tab
on e.sal > avgsal_tab.avgsal where e.deptno =avgsal_tab.deptno
order by e.deptno
This gets me the output but how can I rewrite this with a single query without inline query as shown above.
You can use analytic window functions:
SELECT *
from (
SELECT
e.*
,avg(sal)over(partition by deptno) avgsal
from emp e
)
where avgsal>sal

Cursor with multiple queries in oracle not compiling

I have created a cursor that has two queries joined with inner join, but query is not compiling their is error at the end of first query but the same query is getting executed without cursor.
cursor data is
select * from
select rid,id, order from table1
inner join
select pid, name, order from table2
on table1.order = table2.order
original query is much bigger and complicated but end result would be this.
Their are compilation errors at the end of first query and those are generic nature, I guess may be syntax for creating a two joined queries is wrong (this is a wild guess though)
Error:
SQL statement ignored //at select word of first query
Missing right parenthesis //at the last word of first query
Example based on Scott's schema:
SELECT should contain column aliases if columns returned by those inline views share the same name; otherwise, you won't know which one you're using
inline views should have their own aliases; basically, that's always a good idea - prefix columns with table aliases, otherwise you'll soon forget which column belongs to which table
SQL> declare
2 cursor data is
3 select a.empno a_empno, b.ename b_ename
4 from (select empno, ename, deptno from emp) a
5 inner join
6 (select empno, ename, deptno from emp) b
7 on a.deptno = b.deptno
8 where rownum < 5;
9 begin
10 for data_r in data loop
11 dbms_output.put_line(data_r.b_ename);
12 end loop;
13 end;
14 /
SMITH
JONES
SCOTT
ADAMS
PL/SQL procedure successfully completed.
SQL>
You have to put your subqueries in parenthesis and add aliases for the subqueries:
cursor data is
select * from
(select rid,id, order from table1) table1
inner join
(select pid, name, order from table2) table2
on table1.order = table2.order
Here is another answer for you, with just small differences and with an example:
CREATE OR REPLACE PROCEDURE p_test(n_test in number)
AS
CURSOR data
IS
SELECT *
FROM
(SELECT rid
, id
, "order" or1
FROM table1) tab1
INNER JOIN
(SELECT pid
, name
, "order" or1
FROM table2 ) tab2
ON tab1.or1 = tab2.or1;
BEGIN
FOR data_i IN data LOOP
DBMS_OUTPUT.PUT_LINE(data_i.rid);
END LOOP;
END p_test;
Here is the DEMO

Hide column from Query

I don't want rank column but still, want the data in the same format by applying dense rank.
select ename,position,deptno,dense_rank() over(partition by deptno order by ename asc) as rank from emp where deptno in ('10','30');
Why do you need the rank just order by deptno first then ename.
SELECT ename,position,deptno,
FROM emp
WHERE deptno in ('10','30')
ORDER BY DeptNo, Ename
Using the analytical function two options derived table or CTE
Derived table/inline view.
SELECT ename,position,deptno
FROM (select ename,position,deptno,dense_rank() over(partition by deptno order by ename asc) as rank
from emp
where deptno in ('10','30')) Z
ORDER BY deptNo, rank
Common Table Expression (CTE):
with Z AS (SELECT ename,position,deptno
, dense_rank() over(partition by deptno order by ename asc) as rank
FROM emp
WHERE deptno in ('10','30'))
SELECT ename,position,deptno
FROM z
ORDER BY deptno, rank
Both these last 2 techniques simply avoid exposing the rank function to the outer query in which the results are returned. They are "Tricks" and sub-optimal execution time. unless there's a specific reason to have the rank data; I'd not use it.

How can i select just one row in Oracle by row id?

I have used mysql database in my application, but I want to migrate to Oracle.
The problem is in that query:
select * from users limit ?,1;"
That query returns every row one by one depending on ?.
How can i do that in oracle?
On Oracle 12c, you could use the row limiting feature using FETCH FIRST clause.
SQL> SELECT empno, sal, deptno FROM emp ORDER BY empno DESC
2 FETCH FIRST 1 ROWS ONLY;
EMPNO SAL DEPTNO
---------- ---------- ----------
7934 1300 10
SQL>
Prior 12c solution is ROWNUM, however, if you want the row to be first sorted, then you need to do it in a sub-query -
SQL> SELECT empno, sal, deptno FROM
2 ( SELECT * FROM emp ORDER BY empno DESC
3 ) WHERE ROWNUM = 1;
EMPNO SAL DEPTNO
---------- ---------- ----------
7934 1300 10
SQL>
If the order doesn't matter to you, if you just want any random row, simply use ROWNUM.
Depending on your requirement, you could also use ANALYTIC functions such as ROW_NUMBER, RANK, DENSE_RANK.
select * from (select rownum r, u.* from users u ) where r=1;
or if you want it sorted (replace x by columnnumber or columnname):
select * from (select rownum r, u.* from users u order by x) where r=1;

Alternate of sql server TOP in oracle

How to get top 3 records in oracle pl sql?i am new to oracle,earlier i have used sql server.
My requirement is to get distinct top 3 records of Column X.
Try this to retrieve the Top N records from a query, you can use the following syntax::-
SELECT *
FROM (your ordered query) alias_name
WHERE rownum <= Rows_to_return
Example:-
SELECT *
FROM (select * from suppliers ORDER BY supplier_name) suppliers2
WHERE rownum <= 3
This may help you
SELECT ename, sal
FROM ( SELECT ename, sal, RANK() OVER (ORDER BY sal DESC) sal_rank
FROM emp )
WHERE sal_rank <= 3;

Resources