Fetch all the Duplicate Records in a Table
Approach
Use ROW_NUMBER() and partition the table by user_name
If a user exists more than once that the partition will row numbers that are greater than 1
NOTE
- The
ROW_NUMBER()
function is similar to SEQUENCE() and will return the next incremental number in the series- If same number is required for matching records use the
RANK()
function- Overview of the SQL ROW_NUMBER function
Fetch the 2nd Last (or Nth) Record from Table
Approach 1
Use window function and ROW_NUMBER() to assign each row a number
Fetch the nth record that is required using the above column as reference
Approach 2
If Database supports LIMIT clause use its offset parameter to fetch the required record
SQL Limit: A Beginner’s Guide
Syntax : LIMIT(starting_point, rows_to_return) - Count for starting point is from Zero
SELECT emp_id, emp_name, dept_name
FROM employee
ORDER BY emp_id DESC
LIMIT 1,1;
Fetch 3 consecutive records from a Table
Approach
When consecutive values from a table need to be compared then mostly the LEAD()
and LAG()
function need to be used
Here we need to check if the next 2 user_names from the current one has the same value for username
This can be achieved using the LEAD(scalar_expression, offset, default_value)
function
Offset and default values are optional parameters
MySQL LEAD Function By Practical Examples
INFO
- The
LEAD()
andLAG()
function in MariaDB does not support default_value- LEAD - MariaDB Knowledge Base
SQL query to interchange the adjacent student names
Approach
If row number is even then LAG() the name, if even then LEAD the name
INFO
- The
LEAD()
andLAG()
function in MariaDB does not support default_value- LEAD - MariaDB Knowledge Base
Fetch all the records when London had extremely cold temperature for 3 consecutive days or more
Approach
Use Window function to find row where its next 2 rows have extreme temperature
Then write a window function that finds the row above and below the current row that has extreme temperature
And finally window function to find 2 rows above the current row that have extreme temperature
This can be implemented using an CASE statement
Learn how to write SQL Queries(Practice Complex SQL Queries) — techTFQ