from keyword error in oracle apex site - sql

I have tried checking all the duplicate answers provided in this site but couldn't able to come up with rectifying my error could you guys help me out on this?
Getting this error
ORA-00923: FROM keyword not found where expected
SELECT TOP 1 sal FROM emp WHERE sal in
(SELECT DISTINCT TOP 3 sal FROM emp ORDER BY sal DESC)
ORDER BY sal ASC;
I am solving this using oracle apex site

You appear to want to find thew record with the third-lowest salary.
You can use a subquery to assign an analytic rank to each salary, and then filter on that:
select * from (
select e.*, dense_rank() over (order by sal desc) as rnk
from emp e
)
where rnk = 3;
From 12c you can use the offset and fetch syntax to do the same thing:
select * from emp
order by sal desc
offset 3 rows
fetch first row only;
You need to decide how to deal with ties though - if more than one employee shares that third-lowest salary; or even if the lowest and second lowest are awarded to more than one person. Depending on what you want to happen you can look at variations of the 12c row-limiting syntax, and other analytic functions - row_number(), dense_rank() - and their windowing options.

I was able to get my query now
SELECT A.* FROM emp A where 3 =(SELECT COUNT(DISTINCT sal) FROM emp B WHERE A.sal <= B.sal);

Yet another option, using analytic function:
WITH ranks
AS (SELECT empno, DENSE_RANK () OVER (ORDER BY sal DESC) rnk FROM emp)
SELECT e.*
FROM emp e, ranks r
WHERE e.empno = r.empno
AND r.rnk = 3;

Related

fetch the 1st row from the table for an employee with highest salary [duplicate]

This question already has answers here:
How do I limit the number of rows returned by an Oracle query after ordering?
(14 answers)
Closed 3 years ago.
I am searching for a query to find the details of highest paid employee in the entire organization. I am using oracle DB.
Queries which I tried are:
select * from EMP order by SAL desc FETCH FIRST 1ROW ONLY;
ERROR: SQL command not properly ended
select * from EMP order by SAL desc where rownum = 1;
ERROR: SQL command not properly ended
select * from EMP order by SAL desc LIMIT 0 , 1;
ERROR: SQL command not properly ended
You could use:
SELECT *
FROM (SELECT * FROM emp ORDER BY sal DESC)
WHERE ROWNUM = 1
Please note that if rows have identifical salaries, ROWNUMBER will rank them randomly. To handle ties, you could use RANK() instead (or maybe DENSE_RANK(), depending on your needs):
SELECT *
FROM (
SELECT
e.*,
RANK() OVER(ORDER BY sal DESC) rn
FROM emp
)
WHERE rn = 1
There is an issue with all three statements.
Try this:
select * from EMP order by SAL desc FETCH FIRST ROW ONLY;
or use an analytical function ROW_NUMBER:
SELECT T.* FROM
(SELECT
T.*, ROW_NUMBER() OVER(ORDER BY SAL DESC NULLS LAST) RN
FROM EMP) T
WHERE RN = 1
Cheers!!

Get the name of the employee with the second highest salary [duplicate]

This question already has answers here:
How to find the employee with the second highest salary?
(5 answers)
Closed 3 years ago.
I have to get the name of employee with the second highest salary the table name from where I am fetching is emp. I know the query for second highest salary which is
select max(sal)
from emp
where sal < (select max(sal) from emp)
it works and it returns the right answer.
But I have to get the name of the employee as well. I simply tried
select name, max(sal)
from emp
where sal < (select max(sal) from emp)
I get this error:
ORA-00937: not a single-group group function
how can i remove the error in order to get the name and salary both.
thank you to anyone who helps.
You can use
select name,sal from emp where sal = (select max(sal) from emp where sal < (select max(sal) from emp));
use this :
with cte (
select ROW_NUMBER() over(order by sal desc)rnum ,name,sal from emp )
select * from cte where rnum = 2
You can get this easily with a window function. Try something like this:
SELECT name, sal
FROM emp
QUALIFY RANK OVER(ORDER BY sal DESC) = 2
This will order your rows by Salary and then give each row a ranking. Then it will return the rows with ranking = 2.
If you want to ensure you only get one row back, change RANK to ROW_NUMBER.

How can I select the record with the 2nd highest salary in database Oracle?

Suppose I have a table employee with id, user_name, salary. How can I select the record with the 2nd highest salary in Oracle?
I googled it, find this solution, is the following right?:
select sal from
(select rownum n,a.* from
( select distinct sal from emp order by sal desc) a)
where n = 2;
RANK and DENSE_RANK have already been suggested - depending on your requirements, you might also consider ROW_NUMBER():
select * from (
select e.*, row_number() over (order by sal desc) rn from emp e
)
where rn = 2;
The difference between RANK(), DENSE_RANK() and ROW_NUMBER() boils down to:
ROW_NUMBER() always generates a unique ranking; if the ORDER BY clause cannot distinguish between two rows, it will still give them different rankings (randomly)
RANK() and DENSE_RANK() will give the same ranking to rows that cannot be distinguished by the ORDER BY clause
DENSE_RANK() will always generate a contiguous sequence of ranks (1,2,3,...), whereas RANK() will leave gaps after two or more rows with the same rank (think "Olympic Games": if two athletes win the gold medal, there is no second place, only third)
So, if you only want one employee (even if there are several with the 2nd highest salary), I'd recommend ROW_NUMBER().
If you're using Oracle 8+, you can use the RANK() or DENSE_RANK() functions like so
SELECT *
FROM (
SELECT some_column,
rank() over (order by your_sort_column desc) as row_rank
) t
WHERE row_rank = 2;
This query works in SQL*PLUS to find out the 2nd Highest Salary -
SELECT * FROM EMP
WHERE SAL = (SELECT MAX(SAL) FROM EMP
WHERE SAL < (SELECT MAX(SAL) FROM EMP));
This is double sub-query.
I hope this helps you..
WITH records
AS
(
SELECT id, user_name, salary,
DENSE_RANK() OVER (PARTITION BY id ORDER BY salary DESC) rn
FROM tableName
)
SELECT id, user_name, salary
FROM records
WHERE rn = 2
DENSE_RANK()
You should use something like this:
SELECT *
FROM (select salary2.*, rownum rnum from
(select * from salary ORDER BY salary_amount DESC) salary2
where rownum <= 2 )
WHERE rnum >= 2;
select * from emp where sal=(select max(sal) from emp where sal<(select max(sal) from emp))
so in our emp table(default provided by oracle) here is the output
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7698 BLAKE MANAGER 7839 01-MAY-81 3000 30
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
or just you want 2nd maximum salary to be displayed
select max(sal) from emp where sal<(select max(sal) from emp)
MAX(SAL)
3000
select * FROM (
select EmployeeID, Salary
, dense_rank() over (order by Salary DESC) ranking
from Employee
)
WHERE ranking = 2;
dense_rank() is used for the salary has to be same.So it give the proper output instead of using rank().
select Max(Salary) as SecondHighestSalary from Employee where Salary not in
(select max(Salary) from Employee)
I would suggest following two ways to implement this in Oracle.
Using Sub-query:
select distinct SALARY
from EMPLOYEE e1
where 1=(select count(DISTINCT e2.SALARY) from EMPLOYEE e2 where
e2.SALARY>e1.SALARY);
This is very simple query to get required output. However, this query is quite slow as each salary in inner query is compared with all distinct salaries.
Using DENSE_RANK():
select distinct SALARY
from
(
select e1.*, DENSE_RANK () OVER (order by SALARY desc) as RN
from EMPLOYEE e
) E
where E.RN=2;
This is very efficient query. It works well with DENSE_RANK() which assigns consecutive ranks unlike RANK() which assigns next rank depending on row number which is like olympic medaling.
Difference between RANK() and DENSE_RANK():
https://oracle-base.com/articles/misc/rank-dense-rank-first-last-analytic-functions
I believe this will accomplish the same result, without a subquery or a ranking function:
SELECT *
FROM emp
ORDER BY sal DESC
LIMIT 1
OFFSET 2
This query helps me every time for problems like this. Replace N with position..
select *
from(
select *
from (select * from TABLE_NAME order by SALARY_COLUMN desc)
where rownum <=N
)
where SALARY_COLUMN <= all(
select SALARY_COLUMN
from (select * from TABLE_NAME order by SALARY_COLUMN desc)
where rownum <=N
);
select * from emp where sal = (
select sal from
(select rownum n,a.sal from
( select distinct sal from emp order by sal desc) a)
where n = 2);
This is more optimum, it suits all scenarios...
select max(Salary) from EmployeeTest where Salary < ( select max(Salary) from EmployeeTest ) ;
this will work for all DBs.
You can use two max function. Let's say get data of userid=10 and its 2nd highest salary from SALARY_TBL.
select max(salary) from SALARY_TBL
where
userid=10
salary <> (select max(salary) from SALARY_TBL where userid=10)
Replace N with your Highest Number
SELECT *
FROM Employee Emp1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)
Explanation
The query above can be quite confusing if you have not seen anything like it before – the inner query is what’s called a correlated sub-query because the inner query (the subquery) uses a value from the outer query (in this case the Emp1 table) in it’s WHERE clause.
And Source
I have given the answer here
By the way I am flagging this Question as Duplicate.
Syntax it for Sql server
SELECT MAX(Salary) as 'Salary' from EmployeeDetails
where Salary NOT IN
(
SELECT TOP n-1 (SALARY) from EmployeeDetails ORDER BY Salary Desc
)
To get 2nd highest salary of employee then we need replace “n” with 2 our query like will be this
SELECT MAX(Salary) as 'Salary' from EmployeeDetails
where Salary NOT IN
(
SELECT TOP 1 (SALARY) from EmployeeDetails ORDER BY Salary Desc
)
3rd highest salary of employee
SELECT MAX(Salary) as 'Salary' from EmployeeDetails
where Salary NOT IN
(
SELECT TOP 2 (SALARY) from EmployeeDetails ORDER BY Salary Desc
)
SELECT * FROM EMP WHERE SAL=(SELECT MAX(SAL) FROM EMP WHERE SAL<(SELECT MAX(SAL) FROM EMP));
(OR)
SELECT ENAME ,SAL FROM EMP ORDER BY SAL DESC;
(OR)
SELECT * FROM(SELECT ENAME,SAL ,DENSE_RANK()
OVER(PARTITION BY DEPTNO ORDER BY SAL DESC) R FROM EMP) WHERE R=2;
select salary from EmployeeDetails order by salary desc limit 1 offset (n-1).
If you want to find 2nd highest than replace n with that 2.

Display columns based on sub query

I want to display the name of department with highest SUM of salary.
I am using oracle sql and the table structure is Dept(Deptno,Dname,Loc) and Emp(Empno,Ename,Job,Salary,Deptno).
The query I use was
select Dname
from Dept
where Deptno=
( select Deptno
from Emp
where rownum=1
group by Deptno
order by sum(Salary) Desc
);
This gives an error:
Right parenthesis missing.
When I run the sub-query alone, it successfully returns a Deptno. But with the parent query, I get the above error.
What is the problem and what can be the possible solution?
select dname
from (select dname, rank() over (order by sum(salary) desc) rnk
from dept d
inner join emp e
on e.deptno = d.deptno
group by dname, e.deptno
)
where rnk = 1;
note, in your example putting where rownum=1 where you did is a huge bug. it would mean pick 1 random row and sort it (not really the highest salary row..just any old row)
my solution may get over 1 row if 2 deptartments have the same highest salary. you can use row_number() instead of rank() to just pick one if you want.

ORACLE sql query for getting top 3 salaries rownum greater than

I want to write a query to display employees getting top 3 salaries
SELECT *
FROM (SELECT salary, first_name
FROM employees
ORDER BY salary desc)
WHERE rownum <= 3;
But I dont understand how this rownum is calculated for the nested query
will this work or if it has problem ,request you to please make me understand:
SELECT *
FROM (SELECT salary, first_name
FROM employees
ORDER BY salary )
WHERE rownum >= 3;
I went through this link Oracle/SQL: Why does query "SELECT * FROM records WHERE rownum >= 5 AND rownum <= 10" - return zero rows ,but it again points to a link, which does not gives the answer
a_horse_with_no_name's answer is a good one,
but just to make you understand why you're 1st query works and your 2nd doesn't:
When you use the subquery, Oracle doesn't magically use the rownum of the subquery, it just gets the data ordered so it gives the rownum accordingly, the first row that matches criteria still gets rownum 1 and so on. This is why your 2nd query still returns no rows.
If you want to limit the starting row, you need to keep the subquery's rownum, ie:
SELECT *
FROM (SELECT * , rownum rn
FROM (SELECT salary, first_name
FROM employees
ORDER BY salary ) )sq
WHERE sq.rn >= 3;
But as a_horse_with_no_name said there are better options ...
EDIT: To make things clearer, look at this query:
with t as (
select 'a' aa, 4 sal from dual
union all
select 'b' aa, 1 sal from dual
union all
select 'c' aa, 5 sal from dual
union all
select 'd' aa, 3 sal from dual
union all
select 'e' aa, 2 sal from dual
order by aa
)
select sub.*, rownum main_rn
from (select t.*, rownum sub_rn from t order by sal) sub
where rownum < 4
note the difference between the sub rownum and the main rownum, see which one is used for criteria
The "rownum" of a query is assigned before an order by is applied to the result. So the rownumw 42 could wind up being the first row.
Generally speaking you need to use the rownum from the inner query to limit your overall output. This is very well explained in the manual:
http://docs.oracle.com/cd/E11882_01/server.112/e26088/pseudocolumns009.htm#i1006297
I prefer using row_number() instead, because you have much better control over the sorting and additionally it's a standard feature that works on most modern DBMS:
SELECT *
FROM (
SELECT salary,
first_name,
row_number() over (order by salary) as rn
FROM employees
)
WHERE rn <= 3
ORDER BY salary;
You should understand that the derived table in this case is only necessary to be able to apply a condition on the generated rn column. It's not there to avoid the "rownum problem" as the value of row_number() only depends on the order specifiy in the over(...) part (it is independent of any ordering applied to the query itself)
Note this would not return employees that have the same salary and would still fall under the top three. In that case using dense_rank() is probably more approriate.
if you want to select the people with the top 3 salaries.. perhaps you should consider using analytics.. something more like
SELECT *
FROM (
SELECT salary, first_name, dense_rank() over(order by salary desc) sal_rank
FROM employees
)
WHERE sal_rank <= 3
ie ALL people with the 3rd highest(ranked) salary amount(or more)
the advantage of this over using plain rownum is if you have multiple people with the same salary they will all be returned.
Easiest way to print 5th highest salary.
SELECT MIN(SALARY) FROM (SELECT SALARY FROM EMPLOYEES ORDER BY DESC) WHERE ROWNUM BETWEEN 1 AND 5
according to same if u want to print 3rd or 4th highest salary then just chage last value.(means instead of 5 use 3 or 4 you will get 3rd or 4th highest salary).
SELECT MIN(SALARY) FROM (SELECT SALARY FROM EMPLOYEES ORDER BY DESC) WHERE ROWNUM BETWEEN 1 AND 4
SELECT MIN(SALARY) FROM (SELECT SALARY FROM EMPLOYEES ORDER BY DESC) WHERE ROWNUM BETWEEN 1 AND 3
SELECT EMPNO,
SAL,
(SELECT SUM(E.SAL) FROM TEST E WHERE E.EMPNO <= T.EMPNO) R_SAL
FROM (SELECT EMPNO, SAL FROM TEST ORDER BY EMPNO) T
Easiest way to find the top 3 employees in oracle returning all fields details:
SELECT *
FROM (
SELECT * FROM emp
ORDER BY sal DESC)
WHERE rownum <= 3 ;
select *
from (
select emp.*,
row_number() over(order by sal desc)r
from emp
)
where r <= 3;
SELECT Max(Salary)
FROM Employee
WHERE Salary < (SELECT Max(salary) FROM employee WHERE Salary NOT IN (SELECT max(salary) FROM employee))
ORDER BY salary DESC;