Welcome to Appsloveworld in this post series, we discuss the most commonly asked SQL server interview questions and answers.
If you have attended an interview and if you have a question to be answered, please feel free to leave that question as a comment.
In this post, We’ll discuss how to find Nth high salary in the SQL server. This one of the very commonly asked questions in the Interview question.
Keep in mind, there are several ways of finding the Nth highest salary. In this post, we will discuss a few of those, by the end of this post, will be able to answer all these questions.
- How to find the Nth maximum salary from salary table using a subquery.
- How to find the Nth maximum salary from salary table using using CTE.
- How to find third, second highest, or 15th highest salary in emp table.
We will be using TblEmployeeSalary employee table
Table Script
CREATE TABLE [dbo].[TblEmployeeSalary](
[Id] [int] IDENTITY(1,1) NOT NULL,
[EmployeeName] [nvarchar](max) NULL,
[EmployeeSalary] [float] NULL,
[Adress] [nvarchar](max) NULL,
CONSTRAINT [PK_TblEmployeeSalary] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
)
GO
SET IDENTITY_INSERT [dbo].[TblEmployeeSalary] ON
GO
INSERT [dbo].[TblEmployeeSalary] ([Id], [EmployeeName], [EmployeeSalary], [Adress]) VALUES (1, 'Hunter', 80000, 'Osaka')
GO
INSERT [dbo].[TblEmployeeSalary] ([Id], [EmployeeName], [EmployeeSalary], [Adress]) VALUES (2, 'Connor', 70000, 'Kyoto')
GO
INSERT [dbo].[TblEmployeeSalary] ([Id], [EmployeeName], [EmployeeSalary], [Adress]) VALUES (3, 'Ezra', 60000, 'Vienna, Austria')
GO
INSERT [dbo].[TblEmployeeSalary] ([Id], [EmployeeName], [EmployeeSalary], [Adress]) VALUES (4, 'Aaron', 55000, 'Tokyo')
GO
INSERT [dbo].[TblEmployeeSalary] ([Id], [EmployeeName], [EmployeeSalary], [Adress]) VALUES (5, 'Adrian', 85000, 'Amsterdam, Netherlands')
GO
INSERT [dbo].[TblEmployeeSalary] ([Id], [EmployeeName], [EmployeeSalary], [Adress]) VALUES (6, 'Easton', 72000, 'Barcelona, Spain')
GO
INSERT [dbo].[TblEmployeeSalary] ([Id], [EmployeeName], [EmployeeSalary], [Adress]) VALUES (7, 'Colton', 85000, 'Singapore')
GO
INSERT [dbo].[TblEmployeeSalary] ([Id], [EmployeeName], [EmployeeSalary], [Adress]) VALUES (8, 'Angel', 42000, 'Monte Carlo, Monaco')
GO
INSERT [dbo].[TblEmployeeSalary] ([Id], [EmployeeName], [EmployeeSalary], [Adress]) VALUES (9, 'Jaxson', 32000, 'Cologne, Germany')
GO
INSERT [dbo].[TblEmployeeSalary] ([Id], [EmployeeName], [EmployeeSalary], [Adress]) VALUES (10, 'Greyson', 45000, 'Amsterdam, Netherlands')
GO
INSERT [dbo].[TblEmployeeSalary] ([Id], [EmployeeName], [EmployeeSalary], [Adress]) VALUES (11, 'Brayden', 78000, 'Tokyo')
GO
Now, if somebody asks us to find the highest salary that straightforward, all we do is use the max function.
So the higher salary is 85000. if we want the highest salary, we simply say Select Max(EmployeeSalary) from TblEmployeeSalary that would give us 85000.
Select Max(EmployeeSalary) from TblEmployeeSalary
But if somebody asks us to retrieve the second highest salary, then how are we going to do that?
But that’s not what we want.
We want the second-highest salary, To get the second highest we are going to use the max function with the outer query as well. So now when we execute this, we should get the second highest salary, which is 80000.
Select Max(EmployeeSalary) from TblEmployeeSalary
where EmployeeSalary < (Select Max(EmployeeSalary)
from TblEmployeeSalary)
Now let’s see how to get and nth highest salary. First, let’s see how to get nth higher salary using a subquery
How to find nth highest salary using Sub-Query
Generic Query
SELECT TOP 1 EmployeeSalary
FROM (
SELECT DISTINCT TOP Nth EmployeeSalary
FROM Table_Name
ORDER BY Table_Name DESC
) QueryRESULT
ORDER BY EmployeeSalary
So now this clearly can be used to retire any of the highest salaries, if you want. Let’s say the third-highest salary.
So what is the third-highest salary here? The first is 85000, the second is 80000, the third is 78000. So if you want the third-highest salary, simply replace N with 3.
So when we execute this now, we should get 78000 as the output. so you can use this query to find any of the nth highest salaries.
SELECT TOP 1 EmployeeSalary
FROM (
SELECT DISTINCT TOP 3 EmployeeSalary
FROM TblEmployeeSalary
ORDER BY EmployeeSalary DESC
) QueryRESULT
ORDER BY EmployeeSalary
How To find nth highest salary using CTE
Generic Query
WITH QueryRESULT AS
(
SELECT EmployeeSalary,
DENSE_RANK() OVER (ORDER BY EmployeeSalary DESC) AS DENSERANK
FROM Table_Name
)
SELECT TOP 1 EmployeeSalary
FROM QueryRESULT
WHERE DENSERANK = Nth
Now if we want the second-highest salary I put to 2. So now when we execute this, we should get 80000, which is our second highest.
WITH QueryRESULT AS
(
SELECT EmployeeSalary,
DENSE_RANK() OVER (ORDER BY EmployeeSalary DESC) AS DENSERANK
FROM TblEmployeeSalary
)
SELECT TOP 1 EmployeeSalary
FROM QueryRESULT
WHERE DENSERANK = 2
Now let’s see how to do it using CTE stands for Common Table Expression. I’m going to use the DENSE_RANK SQL server function here and a bit you’ll understand what the DENSE_RANK function is going to do. Now, it’s going to obviously rank rows and then give in rank to every row.
So when we use the DENSE_RANK function, we’ll have to specify the result set upon which we want that DENSE_RANK to be applied. we want the DENSE_RANK to be applied over the results set that we are going to specify here. So what we want to do is we want to order by salary column and that in descending order.
All right. So we have seen how to retrieve an nth highest salary using a subquery,using CTE as well.
Now, obviously, you know, this is going to be in here, meaning if you want 15th or 20th highest salary, simply replace it with 15 or 20 and it’s simply going to work. so if an interviewer asks you to find any of the highest salaries, you know what to do.
Point to Be Noted
On many of the forums,you can see the below SQL query to get the nth highest salary from the employee table. But let me tell you that this SQL query will only work if there are no duplicates salary records in the table.
WITH QueryRESULT AS
(
SELECT EmployeeSalary,
ROW_NUMBER() OVER (ORDER BY EmployeeSalary DESC) AS ROWNUMBER
FROM TblEmployeeSalary
)
SELECT EmployeeSalary
FROM QueryRESULT
WHERE ROWNUMBER = 1
Let’s take an example as you can see in the below table image Adrian and Colton have the same salary i. e 85000. Now I want to find out the second-highest salary from the table using the above query.
WITH QueryRESULT AS
(
SELECT EmployeeSalary,
ROW_NUMBER() OVER (ORDER BY EmployeeSalary DESC) AS ROWNUMBER
FROM TblEmployeeSalary
)
SELECT EmployeeSalary
FROM QueryRESULT
WHERE ROWNUMBER = 2
Now execute the below query it will return the 85000 but as you can see in the table 2nd highest salary is 80000.
The post How to find second or Nth maximum salary from salary table appeared first on Software Development | Programming Tutorials.
Read More Articles
- Linq to SQL Group by and Sum in Select | Linq To SQL Group By and Sum
- How send an HTTP POST request to a server from Excel using VBA?
- What is Difference between where and having clauses in SQL server
- How to Use EXCEPT Operator with an example in Sql
- How to use merge statement in the SQL server
- How to write Re-runnable SQL server query
- How to create Cursor in sql server with example
- How to generate random data in sql server for performance testing
- How to write subquery in select statement in Sql
- How to Log record changes in SQL server in an audit table
- How to join on distinct sub query in SQL Server
- How can I select fields from Cronus Sales Invoice Header table using php sqlsrv?
- transactional replication error due to OS error 3
- how to do a SELECT with a composite key?
- Creating indexes with T-SQL returns index exists error
- Sql query to convert nvarchar to int
- How can I make compatible SQL query between Oracle and SQL Server?
- Should I use EXISTS or IN
- Query runs fast in Query Analyzer but slow in C# application
- Implode type function in SQL Server 2000?
- Convert to Datetime MM/dd/yyyy HH:mm:ss in Sql Server
- Azure Sql request limit reached although the number of connections is well below the resource limit
- SQL Combine multiple rows into one with multiple columns
- Conversion issues with VARCHAR to DATE
- Can't use non INSERTED.fields with INSERT...OUTPUT?
- Get closest store for each customer
- Proper date formatting of string read from a SqlDataReader
- Stored Procedure not returning filtered results when using NULL to ignore parameter if empty
- LINQ puts unwanted trailing spaces on strings
- change SQL column from Float to Decimal Type
- Getting the current date in SQL Server?
- pulling data from MySql Server using SQL server openquery
- ASP.NET Core 3.0 - Can't Update-Database
- How to write IF(expr1,expr2,expr3) in mssql
- Calculate Average between columns by comparing two rows in SQL Server
- Looping ADODB recordset from Lotusscript do not finish or it return rows in random order
- OUTFILE Microsoft SQL Server equivalent?
- My inner join resulted in the repetition of many rows
- Inconsistent calls from service broker to SQL dependecy
- Why there is no semantic check for ddl statement inside if exists in mssql?
- Float or decimal for prices?
- Sql Server Distinct One Value
- Why does SQL Server explicit predicate locking disallow INSERT statements outside of the predicate lock
- Grouping data by Each Monday not working as intended
- Insert statement with subquery and extra column
- DateDiff asc and desc
- How to convert SQL column null value to 0 and varchar to decimal in sql query
- T-SQL equivalent to MySQL aggragate from other table
- Extract unique ids and then get all rows matching a random sample of those unique ids
- How to bring table values into temp table
- SQL Window aggregate function to hide repeating values
- Query in SQL with sum and group
- SchemaModel.SqlSpatialIndex: Timeout expired
- How to use different column values from other table based on value on current table column in SQL server
- Is there a program that will display a SQL schema diagram from an existing database?
- SQL Query - Can I compare using LEN in SELECT clause?
- Entity framework code first migrations, sql user permissions?
- How can I use my SQL query in the cursor query?
- How to execute Union of 2 queries from different SQL Servers?
- SQL Server 2000 + ASP.NET: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
- get top 10 posts and 10 comments for each post sql
- SQL - find parent in same column
- PHP mssql behaving weird with different statements
- Is my database good for hierarchical data? I want to write a SQL query it with "Where" value
- How many times does each word is repeated in a string in sql server?
- Need to run BCP utility through .net code
- Efficiently querying/ordering by Sum aggregate in related model in EfCore
- How to get an element tag in SQL Server
- Ranking before grouping problem in SQL Server 2005
- SQL Server Recognise SP_EXECUTESQL as object rather than Procedure Name
- SQL server 2008 restore .bak file failure
- Pass SQL value to asp.net HyperLink
- T-SQL: calculate number of occurrences across columns and rows
- Query to count table from all databases on server with WHERE clause
- How can I programatically publish a SQL Server Database Project?
- PHP SQLSRV: passing a string of values to IN clause
- Set variable for Select Top in SQL Server from a variable in code behind in ASP.NET
- Whats the reason for "Deprecated encryption algorithm"?
- SQL Concatenate Strings in order of line numbers
- Sql Server group by time interval join zero values
- How to edit column in Sql Server table?
- How to use count in subquery in MSSQL
- Get Orders status that can be delivered with reducing quantity from stock without curson or While loop
- Anyone can optimize this SQL statement?
- JOIN issue on 2 tables
- Implementing PHP password_hash() in MSSQL
- Running total with monthly reset
- "Closed connection error" while trying to connect Ruby to SQL server
- Using dash while using like in where clause in SQL Server 2008 query
- Determine that a database is currently mirroring or not?
- Error : odbc_connect with php
- Convert Date into nvarchar?
- How can I extract the column name when there is a change in the data in SQL Server 2014?
- zeppelin-ms sql server interpreter
- Need help creating a query for a non-normalized database
- sql server join query issue
- SQL SERVER DATETIME FORMAT
- Can one turn visual studio's 'smart' sql query assistant off?
- SQL to JSON - Create a Json Array
- Passing irregular xml file to the stored procedure
- Issue with limiting number of times a value can be inserted
- Getting tablenames from sys.tables and using them to find max value of a column in each table
- OverflowException reading decimal value from db
- Dynamic Pivot on sql data
- Backup filename format in SQL Server
- AWS MS SQL create table
- Why would an Entity Framework model generator not create code for a table when I selected it?
- Select columns based on text displayed on multiple TextBoxes
- Create a New Calculated Column
- How to Publish Website and its Database (ASP.net and SQL Server) on the internet
- Splitting a string in SSRS 2008 R2 using a custom code for three columns
- SQL sub query with complex criteria
- Return records even if they don't exist in the joined tables
- Create SQL View With Entity Framework 6 Code First
- Export to JSON format
- Does the current mssql drivers for php 5.6 work in windows 10?
- SQL Server Express 2017 fails install [0x851A001A]
- Export Data from Hadoop using sql-spark-connector (Apache)
- Error "Incorrect Syntax Near '/'
- Why doesn't the [NOT IN ] syntax work?
- SQL Server: how to insert random integers into table?
- How to count how many unique records with multiple records in one table
- High Sort Cost on Merge Operation
- SQL Server CE 3.5 update row error DB_E_ERRORSOCCURRED column error is DBSTATUS_E_SCHEMAVIOLATION
- Counting records issue
- SQL select multiple rows as one row
- left join table on string like '%table.name%'
- Why databases doing delete and insert as updating a row?
- check if id exists in multiple tables
- Not getting correct date from database
- Unpivot subquery
- Transform table using Cross Apply
- How can I show the row_number alphabetically
- How to get the first n sentences from a string in T-SQL?
- Table valued function in SQL Server; the table in the function is temporary?
- What is the best way to associate a Nested Content node to an Umbraco Member
- SQL Server: changing collation of selected columns
- SQL Show the previous value until the given value changes
- How to you WEIGHT returned values by a Group By value
- Transpose rows to columns in SQL Server
- PHP SQL Server: Trying to find most recent entry into a database by the column Date and Time
- SQL Query Update Error
- How to find missing sequence number which is minimum
- issues importing .tsv to sql Server
- Cannot find data type dbo.DBFLT8 error - Generated script from one server to another
- Implement symmetric difference in SQL Server?
- Primary key design and partitioning for large sets
- aggregate functions return null
- Assign weight based on hierarchical depth
- How do you convert VARCHAR to TIMESTAMP in MSSQL?
- SQL Server query using regex?
- Get average time between record creation
- SQL Replace and Update a Datetime string "before a certain date"
- Cannot create a foreign key becaue it is in conflict with itself
- SQL Server pattern matching..regular expression?
- @@IDENTITY, SCOPE_IDENTITY(), OUTPUT and other methods of retrieving last identity
- NServiceBus doesn't automatically create schema (SQL Server)
- Stored procedure to handle null parameter
- Price compare with multiple store in sql
- Execute a SProc from within a Sproc (using params passed in)