Тёмный

Part 1 How to find nth highest salary in sql 

kudvenkat
Подписаться 828 тыс.
Просмотров 1,9 млн
50% 1

If you are a foodie like me, I am sure you will enjoy the recipes on my friend's RU-vid channel. If you find them useful, please subscribe and share to support her. She's really good at what she does.
/ @aarvikitchen5572
Link for all dot net and sql server video tutorial playlists
/ kudvenkat
Link for slides, code samples and text version of the video
csharp-video-tutorials.blogspo...
This is a very common SQL Server Interview Question. There are several ways of finding the nth highest salary.
By the end of this video, we will be able to answer all the following questions as well.
How to find nth highest salary in SQL Server using a Sub-Query
How to find nth highest salary in SQL Server using a CTE
How to find the 2nd, 3rd or 15th highest salary
Let's use the following Employees table for this demo
Use the following script to create Employees table
Create table Employees
(
ID int primary key identity,
FirstName nvarchar(50),
LastName nvarchar(50),
Gender nvarchar(50),
Salary int
)
GO
Insert into Employees values ('Ben', 'Hoskins', 'Male', 70000)
Insert into Employees values ('Mark', 'Hastings', 'Male', 60000)
Insert into Employees values ('Steve', 'Pound', 'Male', 45000)
Insert into Employees values ('Ben', 'Hoskins', 'Male', 70000)
Insert into Employees values ('Philip', 'Hastings', 'Male', 45000)
Insert into Employees values ('Mary', 'Lambeth', 'Female', 30000)
Insert into Employees values ('Valarie', 'Vikings', 'Female', 35000)
Insert into Employees values ('John', 'Stanmore', 'Male', 80000)
GO
To find the highest salary it is straight forward. We can simply use the Max() function as shown below.
Select Max(Salary) from Employees
To get the second highest salary use a sub query along with Max() function as shown below.
Select Max(Salary) from Employees where Salary [ (Select Max(Salary) from Employees)
To find nth highest salary using Sub-Query
SELECT TOP 1 SALARY
FROM (
SELECT DISTINCT TOP N SALARY
FROM EMPLOYEES
ORDER BY SALARY DESC
) RESULT
ORDER BY SALARY
To find nth highest salary using CTE
WITH RESULT AS
(
SELECT SALARY,
DENSE_RANK() OVER (ORDER BY SALARY DESC) AS DENSERANK
FROM EMPLOYEES
)
SELECT TOP 1 SALARY
FROM RESULT
WHERE DENSERANK = N
To find 2nd highest salary we can use any of the above queries. Simple replace N with 2.
Similarly, to find 3rd highest salary, simple replace N with 3.
Please Note: On many of the websites, you may have seen that, the following query can be used to get the nth highest salary. The below query will only work if there are no duplicates.
WITH RESULT AS
(
SELECT SALARY,
ROW_NUMBER() OVER (ORDER BY SALARY DESC) AS ROWNUMBER
FROM EMPLOYEES
)
SELECT SALARY
FROM RESULT
WHERE ROWNUMBER = 3

Опубликовано:

 

30 июн 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 671   
@AbelMengistuweb
@AbelMengistuweb 8 лет назад
Thank you for the resources, they are very helpful
@Csharp-video-tutorialsBlogspot
+Abel Mengistu Thanks a lot for stopping by to provide your feedback. This means a lot to me. I am really glad you found the video tuorials useful. All the Pragim Tech video tutorials are organised in to playlists, which help you find the videos you are looking for easily ru-vid.complaylists?view=1&sort=dd You can also order DVDs or download all the videos and slides for offline viewing using the link below www.pragimtech.com/kudvenkat_dvd.aspx Image version of the slides and text Version of the videos are on my blog csharp-video-tutorials.blogspot.com Tips to effectively use our free channel. ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-y780MwhY70s.html To receive email alerts, when new videos are uploaded, please subscribe to my youtube channel. ru-vid.com If you like these videos, please click the THUMBS UP button below the video. We like to see these free video tutorials helping others as well. Please share the link with your friends and family who you think would also benefit from them. Thanks Venkat
@techspace5642
@techspace5642 5 лет назад
Another way to nth highest salary is this : Select min(Salary) from (Select distinct top 7 Salary from Employee order by Salary desc) Result :: :: Like my comment if my query works
@danieltaye6566
@danieltaye6566 5 лет назад
@@techspace5642 It doesn't. 'cause min pulls the minimum by value not by order
@brackishdreams
@brackishdreams Год назад
Thank you so much
@mangorez0
@mangorez0 4 года назад
6 years passed from the video posted in May 2014. And today in May 2020 I still found it very helpful. Great job done for explanation and preparation. It is the best tutorial I have ever met in video, plus it has links to the slides and code. BRAVO! TOP JOB!
@arunkaiser
@arunkaiser Год назад
I am from 2023 still found it useful
@TheSourav1986
@TheSourav1986 5 месяцев назад
@@arunkaiser Now I am fin 2024 still found relevant
@kripamishra1001
@kripamishra1001 5 месяцев назад
Still in 2024...
@rohitpatil1993
@rohitpatil1993 6 лет назад
When it comes to SQL learning ..Your Channel is the only thing comes to my mind. Really appreciate your hard-work.
@ga7853
@ga7853 5 лет назад
This is just a beauty, I really loved the new Dense_Rank Function, kudvenkat you are the man. Thanks a million.
@mirrapriya
@mirrapriya 8 лет назад
Hi Venkat , I really appreciate your effort in creating all these tutorials.It helped me to get 2 job offers.Your explanations and examples are very vivid.Thanks for your time and effort.Keep going !! I have been recommending your channel to many friends and will keep doing it.
@Csharp-video-tutorialsBlogspot
+mirrapriya Wow....Congratulations. Very happy for you. I am honored, when you say these videos helped you to get the job. Thank you very much for taking time to share the good news. Good luck and all the very best with your new role.
@sirsyed3502
@sirsyed3502 8 лет назад
+kudvenkat hi sir hope u well i have a question i have a website name web1 and database my website is live and hosted on domain i have another website web2 also live n hosted both database are different my task is that perform some search in web2 and the the result will be as the stored question and answer in web1 database it goes on web1 database n shown it on web2 page to retrieve the search result as google search technique its crawler or google cse technique please kindly guide me
@1256dimple
@1256dimple 7 лет назад
the way you explain any concept is simply amazing! thank you so much!
@sarahlee1877
@sarahlee1877 5 лет назад
Venkat, so grateful to your instructions! Your tutorials are comprehensive and inspiring, and get me away from fears coding the queries. I have followed 6 parts and will be keeping on learning. Thank you again!
@Csharp-video-tutorialsBlogspot
Hello Sarah - Thank you very much for taking time to give feedback. This means a lot. I am very glad you found the videos useful. Good luck and all the very best with your programming career.
@shirshodatta2886
@shirshodatta2886 3 года назад
Last part where you showed the difference with row_number, it was a great finisher indeed. My concept got clear about the ranking functions. Thanks a lot @kudvenkat
@codewithcreativecoder8834
@codewithcreativecoder8834 5 месяцев назад
it's 2024 and this video is still helpful for me. Thank you so much kudvenkat
@shanks24a3
@shanks24a3 6 лет назад
Your explanation is very precise, I love the way u first write sub query first and then the outer query..it just fits in mind quickly. One more thing others uses rownumber function , coz they first make it distinct rows and accordingly top number is given for req. Salary.
@shekharmishra9903
@shekharmishra9903 8 лет назад
Thanks Kudvenkat for your clear description.
@AbdulWahab-li9ri
@AbdulWahab-li9ri 8 лет назад
Hello Venkat, I am thank full to you that you create a great tutorial and yes this is the only tutorial which lead me to a great job. The efforts you made are very helpful for many peoples. You Rocks Man.
@himanshurustagi7351
@himanshurustagi7351 5 лет назад
Hi Venkat, I have recently come across your videos. these videos are actually gold mines. Thank you very much for explaining is such a simple way.
@krismaly6300
@krismaly6300 10 лет назад
I revisited this video to refresh my mind. I enjoyed watching this video and recommend others to watch. Topic has been explained in crisp and clear. Thanks Guru Venkat
@adrolee1
@adrolee1 6 лет назад
Thank you! This helped me with understanding CTEs as well.
@shantilal_suthar
@shantilal_suthar 7 лет назад
I got first job by following your videos for learning.... and its been 2 years experience and still following your videos so that can get better opportunity. I am sure its gonna work again...XD
@prasadm1117
@prasadm1117 6 лет назад
Bro please help me wr r u Staying I'm looking for job for SQL Server DBA
@rituagrawal3950
@rituagrawal3950 6 лет назад
Shantilal Suthar hi
@TableauTip
@TableauTip 5 лет назад
ru-vid.com/show-UCMyjwXfdnf1ezjJyUDHXrsA
@hanifhani1
@hanifhani1 5 лет назад
same here
@nonoobott8602
@nonoobott8602 2 года назад
You're a genius. I've been searching for this. Your explanation is everything. Thanks for sharing
@humanitylover792
@humanitylover792 Год назад
Your way of explanation is amazing and unique Thank you so much because you made my skills much polished from zero to hero. I was unable to prepare anything but you made me the most confident one. Thanks once again
@riyankabhowmick697
@riyankabhowmick697 7 лет назад
I became fan of you... You explain everything so nicely...
@AbhishekAbhi-mc1dv
@AbhishekAbhi-mc1dv 5 лет назад
I really liked your way of explaining the query ...appreciate thanks
@krismaly6300
@krismaly6300 10 лет назад
I enjoyed watching this video and I recommend others to watch since it has been clearly expressed concept Very helpful in interview and also in real life
@KhalidAfridi1
@KhalidAfridi1 10 лет назад
Thanks Venkat, Excellent You are awesome dear, not only this one but all the other videos specially the SQL are fabulous and very much informative and very easy to understand. Your way of teaching is very much understandable and easy. We have learnt a lot from your video series on all the programming fields C#, SQL Server etc. Be blessed and thanks a lot.
@nitincsawant
@nitincsawant 9 лет назад
Hats off to the way you explain...thank you very much Venkat.
@ahmadganteng7435
@ahmadganteng7435 4 года назад
Best SQL Server course I ever had.. Thanks Venkat
@rashmi933
@rashmi933 8 лет назад
Hi Venkat , You are really wonderful , Thanks for helping us , May God bless you.
@vijaydubey1734
@vijaydubey1734 8 лет назад
Great Sir, a true professional as well as a proficient person with awesome convincing skill (y)
@LetCode96666
@LetCode96666 5 лет назад
This video is 100% on point and saved my time ! Thanks a lot :D
@letmeexcel5943
@letmeexcel5943 3 года назад
Kud Venkat is Good Venkat. Thanks for all the efforts you have put in to make these videos.
@sanjarmatin6227
@sanjarmatin6227 6 лет назад
Awesome man ,crystal clear and crisp !!!
@ryanmariner
@ryanmariner 4 года назад
Very helpful and very clearly explained! Thank you for making this video. Please keep up the good work!
@lijessica8392
@lijessica8392 8 лет назад
THIS IS A VERY HELPFUL VIDEO, YOU DID GREAT JOB,THANK YOU FOR SHARING YOUR KNOWLEDGE.
@poojagore2582
@poojagore2582 9 месяцев назад
Watching this vedio after 9 years, still this question is asked in every interview ... Thank you for explaining in such a giod way 😊
@zx-25r12
@zx-25r12 8 лет назад
Great! Thanks for sharing your knowledge, this is very helpful
@nawaltarekmatarid8880
@nawaltarekmatarid8880 5 лет назад
OMG why did I just discover your channel... I have so much to catch up on.... *Goes on to watch all your vids*
@vipulzambare5329
@vipulzambare5329 10 лет назад
sir,these all tutorials are really nice... HATS OFF!!!
@rajasekharreddy478
@rajasekharreddy478 Год назад
Iam Raja Sekhar recently i watched your vedios about SQL for beginner's it's very useful to me. Full explanation it's amazing ,it's easy to understand .thanks lot for ur helping the viewer by giving free knowledge to us .once thanks for alot.
@venureddy8218
@venureddy8218 4 года назад
what an explanation! hats off... you got very good communication
@geoffreyluwemba8434
@geoffreyluwemba8434 3 года назад
Bro, you have explained it so well. Perfect!!
@poomanivenugopal3193
@poomanivenugopal3193 2 года назад
simply superb.. i got lot of confusions before while these kind of queries... now got it.. really super and Thankyou so much...
@JymVer
@JymVer 10 месяцев назад
best video of this nature and ive watched a few today. Well done sir
@ankitatripathi9743
@ankitatripathi9743 5 лет назад
Thank you..it is very important qun of an interview,which i was looking for that
@neel9097
@neel9097 7 лет назад
Explained in most decent way !
@gardeningforeveryone8585
@gardeningforeveryone8585 3 года назад
Still useful in 2021. Very well explained. Thank you🙏
@vishaljaiswar3913
@vishaljaiswar3913 4 года назад
you are awesome ...👍👍🙏🙏 respect man..just because your way of explaination is to step by step which becomes easy to understand thanx man..
@GutoRos
@GutoRos 6 лет назад
Amazing video and explanation! Very helpful. Thank you!
@SriramM289
@SriramM289 6 лет назад
Excellent way of explanation.
@rajatjoshi6695
@rajatjoshi6695 6 лет назад
You got an amazing voice...helps to learn quickly
@krismaly
@krismaly 9 лет назад
Wow thre functionalities explained with example clearly. DENSERANK, CTE, ROW_NUM. Thanks a lot
@MasterjiClassy
@MasterjiClassy 6 лет назад
It is simply wow....this is the first time I understood this answer. :-)
@sunilkumarkashyap199
@sunilkumarkashyap199 10 лет назад
Hi Venkat! we are learning too much from you....and it is very helpful. thanx for sharing.. could you please share more tutorials on sql (advance sql). thnx again.
@tarapanthi9615
@tarapanthi9615 4 года назад
your videos are very effective n helpful for beginners...I follow your tutorials to study IT.Thank you.
@dattakashiwale
@dattakashiwale 4 года назад
Excellent.... Ek Number... Concept Cleared....
@nijamuddinsayyed8243
@nijamuddinsayyed8243 5 лет назад
Really u t great sir . Thank u so much sir. I have never seen like this video. It is very helpful for me.
@vishnuvamshi4645
@vishnuvamshi4645 2 года назад
THANKS ALOT CLEARED CONFUSION.... BEST PART OF YOUR VIDEO IS GIVEN COMPLETE DETAILS FROM TABLE CREATION TO EXECUTION IN DESCRIPTION WHICH SAVES TIME
@sonikagoyal9479
@sonikagoyal9479 4 года назад
Thankyou Venkat . You can make anyone to get offer letter with nice packages . I am so confident today just because of you
@Csharp-video-tutorialsBlogspot
@Csharp-video-tutorialsBlogspot 4 года назад
Wow! That's great news Sonika. Will be delighted to know if you made it. Thank you for sharing.
@jamjalajagadeesh5098
@jamjalajagadeesh5098 3 года назад
Ur superb man ., the way you explained abt dense rank its awesome
@miteshjain56
@miteshjain56 4 года назад
Best teacher . Please make more videos . Thank you so much sir. Very helpful videos . Nice explanation.
@balrandhawa7128
@balrandhawa7128 4 года назад
Awesome teaching technique. Very useful channel. Keep up the good work.
@krismaly6300
@krismaly6300 9 лет назад
I think this kind of video would be very useful educational material. Thanks for all your efforts. Please please keep publishing some more such videos
@Some_Little_Knowledge
@Some_Little_Knowledge 4 года назад
How to find the three highest salary from each department
@DharmendraSingh-vy3if
@DharmendraSingh-vy3if 5 лет назад
Quite Help Full, Nice one Thanks.....
@vdesh1234
@vdesh1234 5 лет назад
Awesome work 💪 bro. Simplified simply
@vaibhavverma6973
@vaibhavverma6973 7 лет назад
the ascent is nice ..keep going..thanks !!!
@hareesh17
@hareesh17 7 лет назад
Hi Venkat, Thank you. Nice set of questions.
@heelakeri8847
@heelakeri8847 4 года назад
thank you Venkat your videos are so helpful keep on your good deeds
@ayandey4742
@ayandey4742 3 года назад
Thank You very much Sir. Your videos are better than some paid courses.
@Maraxusofk
@Maraxusofk 5 лет назад
Great video. Thank you for creating this!
@poornaps
@poornaps 5 лет назад
Excellent One sir thanks teaching nth highest salary using Sub-Query !!
@aravinds3808
@aravinds3808 3 года назад
Thanks guys.. your videos are awesome.. U also helped me to land SQL developer job..
@AbdulKahar
@AbdulKahar 10 лет назад
kudvenkat Really enjoy your videos. Please think about doing an advanced SQL series like your beginners series. Thanks in advance!
@iim1914
@iim1914 9 лет назад
Great video. Thank you. Can you please tell me one or some of the SSIS challenges you have faced on the job and how you resolved them?
@Dk-gl7rq
@Dk-gl7rq 2 года назад
I watched many lecture but finally i understand subquery concept
@amkytube5242
@amkytube5242 2 года назад
You are the best one. Keep Going bro.
@sabarinathkr7603
@sabarinathkr7603 7 лет назад
Thanks for your video tutorials which helps me lot really. I recently was asked questions below . can you please post some videos on this 1) what is fill factor 2) what is dirty read
@beautyofnature6709
@beautyofnature6709 Год назад
Amazing Teaching Technique I Learned within min My All doubts Clear within min
@rajeshgaikar7535
@rajeshgaikar7535 6 лет назад
Simple elegant and Great explanation..
@ArvindSingh-hk8bt
@ArvindSingh-hk8bt 5 лет назад
Nice and clear explanation . Good job!!
@khadijaait-6964
@khadijaait-6964 6 лет назад
thank youuu so mutch i always get the right information from your channel thank u again
@rubanprakash8088
@rubanprakash8088 3 года назад
Brilliant explanation. Keep up the good work.
@yamaya5136
@yamaya5136 Год назад
Still helpful, 2022. My favorite teacher by far.
@madhusmitatripathy8767
@madhusmitatripathy8767 8 лет назад
Really nice and clear explanation...Thanks for this.Please provide some tutorials for sql dba.
@SunilChintu-sh2ct
@SunilChintu-sh2ct 3 месяца назад
Thank you, you are providing good SQL interview question & Answer ,It's was helped to me, i have crack the interview.
@prudhvikumar813
@prudhvikumar813 8 лет назад
superb videos//.......very useful......
@LearningwithIzaan
@LearningwithIzaan 6 лет назад
Can you please do SAS tutorial....I havnt found a single youtube tutorial that helped me. I find your tutorials very clear and to the point.Please upload SAS ...Please...:)
@Krranganathakr
@Krranganathakr 8 лет назад
Hi Venkat, I am thank full to you that you create a great tutorial and yes this is the only tutorial which lead me to a great job .. Can you please tel how we can swap row date in single table using only select statement , This is one of interviewer question . Ex -- in table have 5 row . 1 - ranga , 2- Venkat , 3 - Manoj ,4 - Ranga 5- Venkat , we need to swap where ever we find ranga and next to that venkat we need to swap output like venkat next ranga .
@tothedust
@tothedust 9 лет назад
Dear sir what is the purpose of ldf file or transaction log and how to find duplicate data in SQL in more than one columns using having clause.
@MrJonnis13
@MrJonnis13 7 лет назад
Superb tutorial, as usual. Just an alternative though: SELECT MIN(salary) FROM dbo.Employees WHERE salary IN(SELECT DISTINCT TOP N salary FROM dbo.Employees ORDER BY salary DESC)
@spicytuna08
@spicytuna08 6 лет назад
i don't think you need desc operator. min() will find the minimum.
@RamcharitmanasHindi
@RamcharitmanasHindi 5 лет назад
NICE TUTORIALS HELPED ME A LOT ..THANKS
@rajeshmanivannan5313
@rajeshmanivannan5313 2 года назад
This is very useful video, I got this question in the interview > How to find the 75th highest salary record in an employee table where there are 1000 records.
@SunilKumar-nm4cs
@SunilKumar-nm4cs 7 лет назад
Hi Venkat Sir, Your videos are really being helpful.Thanks a lot for creating these videos.Can you please share a video to find the highest paid employees(top 3 or 5 like that) , it is based on two tables : employee table contains the employee details, salary column is present in department table.
@ankitsrivastava6066
@ankitsrivastava6066 4 года назад
crisp and clear.Thank you !
@GajendraPawarChhindwara
@GajendraPawarChhindwara 10 лет назад
Thank u venkat sir for such a good videos series ... +1 for this and for u :)
@Sonny0276
@Sonny0276 7 лет назад
Great Video. Thank you for posting.
@chintalapativenkataramarahul
@chintalapativenkataramarahul 5 лет назад
Thank you very much sir!!
@TheHimaBindu
@TheHimaBindu 8 лет назад
Very informative
@hopeislife1651
@hopeislife1651 3 года назад
Clear explanation, thank you, have a pleasant day sir
@vivekvenu2675
@vivekvenu2675 9 лет назад
Hi venkat your video tutorials are really helping me a lot and i am eagerly waiting for your asp.net interview questions tutorials,silverlight,wpf ,html,css
@igalye
@igalye 7 лет назад
Good. BTW, it's highly recommended to use semicolon before WITH clause, then you won't need GO. Especially if you are writing a multiple stage query. Also, using Dense_rank is more preferable - in case, say, you need to write a function, in which N is a variable. You can't do it with Top (like - Top @salary_no). Or, better to say - it's not that simple. The problem is that Dense_rank is much slower.
@UdayKumar-lt1nu
@UdayKumar-lt1nu 3 года назад
Please write a that query in simple way
@WaynezWorldz
@WaynezWorldz 6 лет назад
Excellent...very helpful, thanks!
@positivejostyle3169
@positivejostyle3169 5 лет назад
Excellent..explanation was clear
@saylishah6708
@saylishah6708 7 лет назад
Hi Venkat. Thanks for the video. I have a doubt here. For finding the 2nd highest salary, you have first order by Sal Desc in subquery and then in main query you have order by Sal Asc. Instead of 2 steps why dnt we directly Order by Sal Asc in sub query? Can we do that?
Далее