SQL tricky Query | Sort by one country always at top and others in ascending order | Custom sorting

แชร์
ฝัง
  • เผยแพร่เมื่อ 5 ก.ย. 2024
  • In this video, we answer the SQL tricky Query - How to sort country names with one country name always on top.
    How to install SQL Server for practice?
    • How to install SQL Ser...
    Check out the complete list of SQL Query Interview Questions -
    • SQL Query Interview Qu...
    Sign up for a free trial of Coupler.io - The No code data integration tool
    app.coupler.io...
    Get USD 100 off Coursera Plus Annual Subscription
    imp.i384100.ne...
    Get 50% off Skillshare Annual Subscription with code AFF50.
    Dates: 11/24 at midnight - 11/28 at midnight
    skillshare.eqc...
    Best Data Science / Analytics / SQL courses
    Learn SQL Basics for Data Science Specialization
    imp.i384100.ne...
    Data Science Fundamentals with Python and SQL Specialization
    imp.i384100.ne...
    IBM Data Science Professional Certificate
    imp.i384100.ne...
    Python for Everybody Specialization
    imp.i384100.ne...
    Google Data Analytics Professional Certificate
    imp.i384100.ne...
    Coursera Plus - Data Science Career Skills
    imp.i384100.ne...
    Please do not forget to like, subscribe and share.
    For enrolling and enquiries, please contact us at
    Website - knowstar.org/
    Facebook - / knowstartrainings
    Linkedin - www.linkedin.c...
    Email - learn@knowstar.org

ความคิดเห็น • 185

  • @debashish_dutta
    @debashish_dutta 2 ปีที่แล้ว +74

    The first thing came to my mind was doing a union. But I have to do table scan 2 times. Your solution is optimized and will definitely use from next time.

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว +7

      Glad it was useful.

    • @TheNubaHS
      @TheNubaHS 2 ปีที่แล้ว +1

      yeah I think everyone's first response to this is going to just do a union but the response in this video is the one the interviewer is expecting you to say in order to get a higher grade

    • @Myrslokstok
      @Myrslokstok 2 ปีที่แล้ว

      Yhee but sometimes a clear code is better I think anyway, but yhee nice solution anyway.

    • @debashish_dutta
      @debashish_dutta 2 ปีที่แล้ว

      @Anaeze Somto Can you elaborate your question with an example ?

    • @MK-lh3xd
      @MK-lh3xd ปีที่แล้ว

      When you do a union, the order by is applied for the entire result set right. Not sure how you can achieve the desired ordering with union of two queries. I am missing something.

  • @rutgerdekok1324
    @rutgerdekok1324 2 ปีที่แล้ว +37

    A simpeler solution, just add the different order cases by priority seperated by comma's. ORDER BY Country_Name = 'India' DESC, Country_Name = 'Singapore' DESC, Country_Name;

    • @rutgerdekok1324
      @rutgerdekok1324 2 ปีที่แล้ว +22

      Or even shorter: ORDER BY Country_Name != 'India' , Country_Name != 'Singapore' , Country_Name;

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว +2

      Thank you for sharing your approach 👍

    • @ashokwwf
      @ashokwwf 2 ปีที่แล้ว

      Does this work on all types of SQL ?

    • @rutgerdekok1324
      @rutgerdekok1324 2 ปีที่แล้ว +2

      Yes, I think so, because a condition like Country_Name = 'india' resolves to 0 or 1, that is standard sql, and also chaining ordering condition seperated by commas is standard sql.

    • @rm-uy8hv
      @rm-uy8hv 2 ปีที่แล้ว

      @@rutgerdekok1324 not working with T-SQL

  • @cadmus777
    @cadmus777 2 ปีที่แล้ว +16

    I've never come across this question before, and my first thought was to add another column with a sub-select, but this solution was beautiful, thank you!

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว +1

      Thank you

    • @alextiga8166
      @alextiga8166 2 ปีที่แล้ว

      Yeah and you are never going to come across it because it's not something you will ever need in reality, it's just done for the sake of it

    • @dsvechnikov
      @dsvechnikov 2 ปีที่แล้ว

      @@alextiga8166 I wish you were right... I have this kind of sorting in my current project all over the place. It is used in things like getting right setting for something for user based on other settings of that user and some other things... Reading and trying to understand this is a huge pain in the butt.

    • @johnossmann7036
      @johnossmann7036 2 ปีที่แล้ว

      @@alextiga8166 If you output the query results to csv, and you have a very large number of records that you would have to sort through in the csv to get certain records to be at the top, then this is method is useful

  • @PicaPauDiablo1
    @PicaPauDiablo1 2 ปีที่แล้ว +16

    This was a very clever way to solve it. I had done it before using a union and excluding the first record but this is better in every way. Much thanks.

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว +1

      Thank you

    • @jakubsawczuk6392
      @jakubsawczuk6392 2 ปีที่แล้ว

      Did you take in account that with UNION you are not certain of order of the records in the result set?
      select expression from table union select expression from other_table is not granted to return records first from 'table' and then after that records from 'other_table'. In 99% cases it will but is not granted so you shouldn't count on it. If you really need to employ UNION, you should do following:
      select 0 as ordby, expression from table
      union all
      select 1, expression from other_table
      order by 1
      BTW it is more efficient to use UNION ALL instead of UNION itself every time it is granted that both subsets are exclusive (which is the case)

  • @KEDARPATILArSeNaL
    @KEDARPATILArSeNaL 2 ปีที่แล้ว +2

    Haven’t used Case statement in Order By clause, learnt new thing 💯

  • @leyrua
    @leyrua 2 ปีที่แล้ว +2

    Oh yeah I use this method a lot. Good advice. This and ROW_NUMBER() are two of my favorite methods to selectively sort data.

  • @patricior7300
    @patricior7300 2 ปีที่แล้ว +3

    Excellent video and thanks for enlarging the font size so that it can be read from a tablet. Liked and subscribed 👍

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว

      Thank you so much for your support ❤️

  • @larrywaller7411
    @larrywaller7411 2 ปีที่แล้ว

    We use techniques like this very often. Depending on SQL language this shorter version works too:
    SELECT * FROM Country ORDER BY iif(Country_Name = 'India'),0,1), Country_Name
    Since Singapore follows India, you can use this for the second case:
    SELECT * FROM Country ORDER BY iif(Country_Name IN ('India', 'Singapore'),0,1), Country_Name
    (You could also add DESC after the iif clause if the reverse was needed.)
    The CASE statement is needed when the top items order is arbitrary. Using this technique will generate the same query plan in SQL Server as in the video and some languages don't support iif.

  • @jasonmalley8573
    @jasonmalley8573 2 ปีที่แล้ว

    I like this solution a lot! Great job! The only thing i would say is always alias your tables. it creates good habits and demonstrates the importance of it for when the query is more complex.

  • @ArabianHorse
    @ArabianHorse 2 ปีที่แล้ว

    Excellent trick , congratulation from Misr (=Egypt)

  • @batistavebriarta
    @batistavebriarta 2 ปีที่แล้ว

    I never tought that case clause can be use for ordering. Great tips!

  • @tommcneill9353
    @tommcneill9353 2 ปีที่แล้ว

    I spent four months telling the client”Sorry, I can’t sort like that.” Then I found this video and solved it in five minutes. I was trying to sort events by date where the soonest events displayed first, up to the future-most event, then show the events that already happened after that.

    • @ashokwwf
      @ashokwwf 2 ปีที่แล้ว

      Everything is possible. Just extra steps. :)

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว

      Glad it was useful.

    • @vbaclasses3553
      @vbaclasses3553 2 ปีที่แล้ว

      Lol, hope the client never sees this video. Well done on getting it done though.

  • @markhathaway228
    @markhathaway228 2 หลายเดือนก่อน

    Here's another way to do it.
    select *
    from Country
    ORDER BY replace(Country_Name, 'India', '0')
    Since all the other Country Names begin with a letter replacing India with a zero insures it will always be at the top.

  • @raylightzzz
    @raylightzzz 2 ปีที่แล้ว +1

    A even simplier solution is to create an INT column (named for instance ITEM_ORDER) and add values to the countries you want to order first, and leave the other NULL. A similar CASE can be applied to guarantee that items NOT NULL appear first. In this way, if you want to change the country order, you don't need to change the query.

  • @papachoudhary5482
    @papachoudhary5482 2 ปีที่แล้ว +1

    Thanks Madam

  • @oldisgold9272
    @oldisgold9272 2 ปีที่แล้ว

    Case statement in order by clause is not optimised way..instead write case in select and then do order by which will give faster result for large tables.

  • @Lexluthor2024
    @Lexluthor2024 2 ปีที่แล้ว

    Great trick. Now how to sql make coffe please. Thx

  • @sunilbamel6147
    @sunilbamel6147 2 ปีที่แล้ว

    Your voice haaye just went through mind

  • @Amarjeet-fb3lk
    @Amarjeet-fb3lk 2 ปีที่แล้ว +3

    select country from table order by IF(country='India', 1,0) desc, 1 desc

    • @shavadre
      @shavadre 2 ปีที่แล้ว

      You can just write "ORDER BY Country = 'India' DESC, Country" with same result.

    • @Mahesh9_
      @Mahesh9_ 11 หลายเดือนก่อน

      Why to write desc ??

  • @edgarmachado6008
    @edgarmachado6008 ปีที่แล้ว

    Thank you for the lesson. I learned something new.

  • @rosonerri-faithful
    @rosonerri-faithful 2 ปีที่แล้ว +2

    Mam, this query approach using CASE , seemed very unfamiliar to me. If you could give some details about it, it would be helpful
    Nice video thankyou!

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว +2

      Case statement in this example would create a dummy column. In the end, data will be sorted based on the values of this dummy column along with Country Name column

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว

      Case works like an if then else. Will try to post a video explaining how it works. Thanks for posting your queries. Really appreciate it.

  • @hv0032113
    @hv0032113 2 ปีที่แล้ว +1

    You provide amazing content. Many thanks.

  • @dineshpandey5008
    @dineshpandey5008 ปีที่แล้ว

    Hi This is good and really helped me alot, but I have one dobut can we do sorting like india and singapore in asceding order and rest country in desc order. Hope my question is clear to your. I want to output like this-
    India
    Singapore
    Italy
    Germany
    France
    China
    Australia
    Afghanistan

  • @chu1452
    @chu1452 2 ปีที่แล้ว

    New subscriber here, please keep uploading sql question like this thank you

  • @nikolaybaranov2213
    @nikolaybaranov2213 2 ปีที่แล้ว

    Its a good idea, thanks!

  • @nibinibiru119
    @nibinibiru119 2 ปีที่แล้ว

    Very nice. Good presentation. Thanks.

  • @gocrow23
    @gocrow23 2 ปีที่แล้ว

    Can you make similar video in KQL Kusti used in Azure.
    Also, a detailed video on joins vs union, when to use what in terms of Kql not SQL.

  • @OcteractSG
    @OcteractSG 2 ปีที่แล้ว +1

    Interesting. I would have used a union to join the country I want with a list that has that country excluded.

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว +2

      Thank you. That is also another solution.

  • @jagadesh4220
    @jagadesh4220 2 ปีที่แล้ว

    Super..... One question from my side pls slove it..... How to do sum with out using windows function?

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว

      Thank you. You will need to use group by and use subqueries to perform join on the grouped level.

    • @jagadesh4220
      @jagadesh4220 2 ปีที่แล้ว

      @@LearnatKnowstar we don't want to use any Analytic Function.... Or Group by then?

  • @manaspanigrahi0989
    @manaspanigrahi0989 8 หลายเดือนก่อน

    will this order by case work if we used distinct in select statement

  • @sureshtamil2925
    @sureshtamil2925 2 ปีที่แล้ว

    This was really useful. If you could also post an end to end datawarehouse pratical tutorial that would be really helpful

  • @FactsHeaven
    @FactsHeaven 2 ปีที่แล้ว

    Great video

  • @thearunjaat
    @thearunjaat 2 ปีที่แล้ว

    It really helps, great ... Please share a video of join function, Left join right join.

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว +1

      Thank you
      Here is the link for the video tutorial on SQL joins
      th-cam.com/video/4HmERpUNjqY/w-d-xo.html

  • @sandhyaganji8268
    @sandhyaganji8268 2 ปีที่แล้ว

    Can you please make a video on ..in stored procedure how o write a select statement in sp

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว +1

      Sure, will plan a video soon. Thanks !

  • @jagadeeswararaokarajada6696
    @jagadeeswararaokarajada6696 2 ปีที่แล้ว

    Really good efforts to share ur knowledge.... ThnQ

  • @srisuman3996
    @srisuman3996 2 ปีที่แล้ว

    Must be noted very thank full…

  • @anhhaopham7919
    @anhhaopham7919 2 ปีที่แล้ว

    How can i download the example data in the video ? Thank you

  • @drkenny7928
    @drkenny7928 2 ปีที่แล้ว

    case statement are soo underrated

  • @ajay_jangra
    @ajay_jangra 2 ปีที่แล้ว

    useful and intresting, thanks for sharing!

  • @ujjwalprakash348
    @ujjwalprakash348 2 ปีที่แล้ว

    Nice one

  • @GenNextAnalyst
    @GenNextAnalyst 2 ปีที่แล้ว

    Thanks!

  • @jijadahifale1375
    @jijadahifale1375 2 ปีที่แล้ว

    Smartly written query, I was upto case statement but forgot to add country-name in order by clause

  • @kristyowens2284
    @kristyowens2284 2 ปีที่แล้ว

    amazing

  • @rajaguru7151
    @rajaguru7151 2 ปีที่แล้ว

    really it is a good stuff !

  • @styleslv8800
    @styleslv8800 2 ปีที่แล้ว +2

    Why you use two captial letters while using WHEN 'CO'untry_Name ?? SQL is non case sensitive for reserved words but it's a coloum name or is it some kind of convention?

    • @4086pp
      @4086pp 2 ปีที่แล้ว +1

      It was just a typo.

    • @styleslv8800
      @styleslv8800 2 ปีที่แล้ว

      @@4086pp no if you notice it she did it twice . Why would she make same mistake twice ?

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว

      Thanks for noting this. It is just a typo as suggested in other comments. The column names are not case sensitive.

    • @tony7671
      @tony7671 2 ปีที่แล้ว

      @@LearnatKnowstar I did actually find situations where column names can be case sensitive - I think it is where the default collation of the database is case sensitive. In my case, I was working with a pre-existing database with collation Latin1_General_BIN.

  • @asitkumarrout9796
    @asitkumarrout9796 ปีที่แล้ว

    If I want to display Singapore on last then what should I do

  • @marcm8745
    @marcm8745 2 ปีที่แล้ว

    Great video!

  • @zhalie12345
    @zhalie12345 2 ปีที่แล้ว

    Really helpful.. Thanks!

  • @misaelchuc7172
    @misaelchuc7172 2 ปีที่แล้ว

    Good information, What about the plan execution?

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว +1

      Thank you. The query is optimized in terms of plan execution.

  • @johnmckown1267
    @johnmckown1267 2 ปีที่แล้ว

    Clever.

  • @dimpyrathore818
    @dimpyrathore818 2 ปีที่แล้ว

    Very useful series

  • @walkermom100
    @walkermom100 2 ปีที่แล้ว

    Did this many years ago.

  • @souvik5560
    @souvik5560 2 ปีที่แล้ว

    Fantastic 👍

  • @sureshallampalli6703
    @sureshallampalli6703 ปีที่แล้ว

    perfect

  • @kingstonxavier
    @kingstonxavier 2 ปีที่แล้ว

    Thank you! useful tip.

  • @Faisal1504
    @Faisal1504 2 ปีที่แล้ว

    Thanks.
    How Can user display the values from dummy col created by case statement. ?

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว

      You can put the case in Select statement.

  • @walkermom100
    @walkermom100 2 ปีที่แล้ว +1

    Do you have any videos on using openjson

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว +1

      Not at this time. Will surely plan in the future

    • @walkermom100
      @walkermom100 2 ปีที่แล้ว

      @@LearnatKnowstar thank you. I just started using them and it's pretty interesting.

  • @prakashsrinivasan7840
    @prakashsrinivasan7840 2 ปีที่แล้ว

    Super Mam 👌👌👌👌

  • @maxmudamatov138
    @maxmudamatov138 2 ปีที่แล้ว

    thanks

  • @var4d
    @var4d 2 ปีที่แล้ว

    Very nice 👍

  • @artus198
    @artus198 2 ปีที่แล้ว

    Do a Union

  • @CaribouDataScience
    @CaribouDataScience 2 ปีที่แล้ว

    Nice

  • @Be_Happpy_
    @Be_Happpy_ 2 ปีที่แล้ว

    its real simply super

  • @jeffs4810
    @jeffs4810 2 ปีที่แล้ว

    This is a nice trick

  • @avinashm624
    @avinashm624 2 ปีที่แล้ว

    super queries 👌👌

  • @kamleshprajapati6621
    @kamleshprajapati6621 2 ปีที่แล้ว

    Very useful

  • @akshaychauhan545
    @akshaychauhan545 2 ปีที่แล้ว

    Its not working in workbench how can i do the same in workbench

  • @lenulka0696
    @lenulka0696 2 ปีที่แล้ว

    What is it? This for teens?

  • @sahameed
    @sahameed 2 ปีที่แล้ว

    That was cool 😎

  • @gamemonster6376
    @gamemonster6376 2 ปีที่แล้ว

    wow, just wow

  • @pradeepba1439
    @pradeepba1439 2 ปีที่แล้ว

    When we might expect regex videos..other videos what have been doing are also great but i have little confusions over regex videos.. Please do as soon as possible..

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว

      Sure. We will plan something for next week. Stay tuned!

    • @cockbeard
      @cockbeard 2 ปีที่แล้ว

      If you use regex to solve a problem, you now have two problems

  • @eswark6786
    @eswark6786 2 ปีที่แล้ว

    please make complete sql video

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว

      Sure. Stay tuned for further videos!

  • @__goyal__
    @__goyal__ 2 ปีที่แล้ว

    Unreal!

  • @guillermofernandez1971
    @guillermofernandez1971 2 ปีที่แล้ว

    this just with SQL Server?
    when I use MySQL?

  • @wildtomi23
    @wildtomi23 2 ปีที่แล้ว +1

    this is actually one of the worst solutions because you are mixing specific column values into the query. You can already see the complexity of maintaining such query when you extend it for a second country.. Also you have to generate specific "pseudorandom" priority values local to the query making them SPOF risk. Classic solution would be to have a priority table with those extra countries and outer join it with the countries table....

  • @AnthonyThomas_Ant
    @AnthonyThomas_Ant 2 ปีที่แล้ว

    Neat.

  • @amanyele6695
    @amanyele6695 2 ปีที่แล้ว

    where to get real time project on sql ? anyone?

  • @epuriraghavendra3847
    @epuriraghavendra3847 7 หลายเดือนก่อน

    👏🏻

  • @saikrishnakatepalli8298
    @saikrishnakatepalli8298 2 ปีที่แล้ว +1

    Hi Recently I had an SQL interview in which they asked me to find the latest created file per day by giving the sample input as:
    Date of Creation FileName as 2 columns with data like
    2022-04-08 3:00PM File 1
    2022-04-08 3:10PM File 2
    2022-04-09 2:00PM File 3
    2022-04-09 2:10PM File4
    So the required output that we need is on 2022-04-08 3:10PM the last record that created per day is File 2 and on 2022-04-09 2:10PM the last record that created is File 4 so we need both File2 and File 4 as output.
    So please help me with the SQL Query how to print the latest created record per day.

    • @ManeshBPandu
      @ManeshBPandu 2 ปีที่แล้ว +1

      select a.create_date,a.fileid from #file a
      cross join #file b
      where a.create_date > b.create_date and CONVERT(DATE, a.create_date) = CONVERT(DATE, b.create_date)

    • @rajeshtorgal5191
      @rajeshtorgal5191 2 ปีที่แล้ว +1

      We can use rank analytical function for this type of queries.
      Generate rank partitioning by date(use cast to convert) and ordering by created_datetime in descending order. The rank will always be one for latest record for a day. Then filter using the rank value using sub query.
      select created_datetime, FileName from (
      select f.*, rank() over (partition by cast(created_datetime as DATE) order by created_datetime desc)rnk from filedetails f)d
      where rnk=1;

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว

      You can use rank function as suggested in comments below.

    • @saikrishnakatepalli8298
      @saikrishnakatepalli8298 2 ปีที่แล้ว

      @@rajeshtorgal5191 If we cast the Datetime into Date Datatype then the time will be missed right then how will the system know to partition based on time and give it a rank?

    • @ManeshBPandu
      @ManeshBPandu 2 ปีที่แล้ว

      @@saikrishnakatepalli8298 Buddy Hope you have run the query, please run it, you'll find the partitioned data and the allocated row numbers or rank please run it

  • @cockbeard
    @cockbeard 2 ปีที่แล้ว

    A case statement and then order by two different conditions, no thanks, not very good for big tables. I'd be more inclined to use a replace, case statements get used so often and are rarely particularly efficient
    ORDER BY REPLACE(Country_Name, 'India',0)

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว

      Thank you for sharing your approach 👍

  • @swamikrishnaanurag335
    @swamikrishnaanurag335 2 ปีที่แล้ว

    I want to learn some SQL topics so how could I approach you

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว

      Please do post your queries in the comments.

  • @jakubsawczuk6392
    @jakubsawczuk6392 2 ปีที่แล้ว

    Come on guys, how comes this is considered 'tricky' or 'clever', this is almost straightforward use of SQL

    • @LearnatKnowstar
      @LearnatKnowstar  2 ปีที่แล้ว +2

      Sure, it’s a simple implementation. It is just an example of a custom sorting scenario !

    • @jakubsawczuk6392
      @jakubsawczuk6392 2 ปีที่แล้ว

      @@LearnatKnowstar Oh, ok, with that assumption you can actually call it custom. For me and by definition of ORDER BY [expression[, expression[,...] it is just regular, not to surprise when I see ORDER BY (select ... from ... where ...) which is also as an example of SQL expression - still allowed :)

  • @janneslorek8064
    @janneslorek8064 2 ปีที่แล้ว

    This is not tricky, more for absolute beginners

  • @setsunaes
    @setsunaes 2 ปีที่แล้ว

    Tricky???
    Select * from Country Order by case when Country.Country_name="Japan" then 1 else 2 end, Country.Country_name
    And that's it. How is that tricky?

  • @jamesgg9950
    @jamesgg9950 2 ปีที่แล้ว

    SELECT * FROM Country LEFT JOIN (
    SELECT 'India' as 'Country_Name', 0 as 'order_first'
    UNION ALL SELECT 'Singapore', 1 ) subquery
    ON Country.Country_Name = subquery.Country_Name
    ORDER BY ISNULL( subquery.order_first, 2147483647 ), Country.Country_Name -- TSQL ISNULL(), MySQL IFNULL()
    Use a subquery to mimic a sparse column. If you use something like this in a lot of queries (or if you create a view on the ordered records) you can easily move the subquery into its own table.