Top 10 Advanced SQL Queries
- Ranking Rows Based on a Specific Ordering Criteria: This query ranks rows based on a specific ordering criteria. Here’s an example code snippet:
SELECT column1, column2, column3, RANK() OVER (ORDER BY column1 DESC) AS rank
FROM table_name;
- List The First 5 Rows of a Result Set: This query lists the first 5 rows of a result set. Here’s an example code snippet:
SELECT *
FROM table_name
LIMIT 5;
- List the Last 5 Rows of a Result Set: This query lists the last 5 rows of a result set. Here’s an example code snippet:
SELECT *
FROM table_name
ORDER BY column_name DESC
LIMIT 5;
- List The Second Highest Row of a Result Set: This query lists the second highest row of a result set. Here’s an example code snippet:
SELECT column_name
FROM table_name
ORDER BY column_name DESC
LIMIT 1 OFFSET 1;
- List the Second Highest Salary By Department: This query lists the second highest salary by department. Here’s an example code snippet:
SELECT department, MAX(salary) AS salary
FROM table_name
WHERE salary < (SELECT MAX(salary) FROM table_name)
GROUP BY department
ORDER BY salary DESC;
- List the First 50% Rows in a Result Set: This query lists the first 50% rows in a result set. Here’s an example code snippet:
SELECT *
FROM table_name
WHERE column_name <= (SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY column_name) FROM table_name);
- List the Last 25% Rows in a Result Set: This query lists the last 25% rows in a result set. Here’s an example code snippet:
SELECT *
FROM table_name
WHERE column_name >= (SELECT PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY column_name) FROM table_name);
- Number the Rows in a Result Set: This query numbers the rows in a result set. Here’s an example code snippet:
SELECT ROW_NUMBER() OVER (ORDER BY column_name) AS row_number, column_name
FROM table_name;
- List All Combinations of Rows from Two Tables: This query lists all combinations of rows from two tables. Here’s an example code snippet:
SELECT *
FROM table1
CROSS JOIN table2;
- Join a Table to Itself: This query joins a table to itself. Here’s an example code snippet:
SELECT a.column_name, b.column_name
FROM table_name a, table_name b
WHERE a.column_name = b.column_name;
I hope this helps you get started with advanced SQL queries!
Comments
Post a Comment