Practice complex SQL queries-find second last record

Write a SQL query to fetch the second last record from employee table.

Table Name: EMPLOYEE

Approach: Using window function sort the data in descending order based on employee id. Provide a row number to each of the record and fetch the record having row number as 2.

Solution-1

select * from employees
where employee_id in(
select MAX(employee_id)-1 as employee_id from employees
);

— there is issue in this query, lets say employee_id 205 is not present then this query will fail

Solution-2
–PERFECT SOLUTION USING WINDOW FUNCTION WITHOUT PARTION BY
SELECT * FROM(
SELECT
ROW_NUMBER() OVER (ORDER BY EMPLOYEE_ID DESC) AS RN,
EMP.*
FROM employees EMP)
WHERE RN=2;

Popular posts from this blog

How to change column name in Dataframe and selection of few columns in Dataframe using Pyspark with example

What is Garbage collection in Spark and its impact and resolution

Window function in PySpark with Joins example using 2 Dataframes (inner join)