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

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

Complex SQL: fetch the users who logged in consecutively 3 or more times (lead perfect example)

Credit Card Data Analysis using PySpark (how to use auto broadcast join after disabling it)