How to do Subqueries in SQL with Examples

Поділитися
Вставка
  • Опубліковано 6 вер 2024
  • Step-by-step tutorial shows you how to use SQL subqueries in your SELECT statement & FROM and WHERE clauses!
    Queries:
    1) A subquery in the SELECT statement: SELECT customerid, freight, (SELECT AVG(freight) FROM orders) FROM orders
    2) A subquery in the FROM clause: SELECT shipcountry, AVG(num_orders) FROM (SELECT customerid, shipcountry, count(*) AS num_orders FROM orders GROUP BY 1,2) sub GROUP BY 1
    3) A subquery in the WHERE clause: SELECT * FROM orders WHERE employeeid IN (SELECT employeeid FROM employees WHERE LOWER(firstname) LIKE '%b%')
    Get the Northwind Database: • How to Load a Sample P...
    Support the Channel:
    1) Subscribe:
    2) DataCamp:
    3) Udacity:

КОМЕНТАРІ • 178

  • @honeyclover5038
    @honeyclover5038 3 роки тому +81

    Finally, a break through. Finally, someone who explains the use of sub queries well.

  • @kristiankelloway127
    @kristiankelloway127 3 місяці тому +2

    The idea that a subquery in a FROM statement creates a table and starting the query process from there was a real lightbulb moment - thank you

  • @dabeast0623
    @dabeast0623 3 роки тому +15

    CANNOT EXPLAIN ENOUGH HOW MUCH YOU SAVED MY LIFE.

  • @juliakristavilladiego4425
    @juliakristavilladiego4425 3 роки тому +16

    Spending my Christmas binge watching your SQL tutorials haha so helpful. Thank you!!!!

    • @becomingADS
      @becomingADS  3 роки тому +2

      Haha, sounds like a good Christmas to me!

  • @sarahemslie6105
    @sarahemslie6105 4 роки тому +39

    This is really helpful; more so than my online course! I look forward to watching more of your videos. Thank you!

  • @Aaron-il5pk
    @Aaron-il5pk 3 роки тому +12

    Thank you for telling us that even when you first learned this it was complex, because holy cow! I cannot wrap my head around this. I can kind of grasp whats going on, but I think you know the confusion that goes through a noob's mind. Thank you for your tutorials! I plan on watching many more of your videos.

  • @EverythingData98
    @EverythingData98 Рік тому +4

    I am getting ready for an internship using SQL as a data analyst and this made a ton of sense, thanks! I will be subscribing

    • @aadhyatiwari9688
      @aadhyatiwari9688 7 місяців тому

      did you get the internship? just curious lol

  • @jorgehernandezdominguez6574
    @jorgehernandezdominguez6574 Рік тому +3

    WOW! the way you explained that is like first doing a table to then going and making a query from that table was a breakthrough for my understanding of the concept. I really admire people who can transform concepts into more digestible material. Thanks

  • @kw9303
    @kw9303 Рік тому

    Just started a Business Systems Analyst entry level position that uses SQL everyday and this video has been so helpful! You explained it better than the corporate instructor, Khan Academy and my Udemy course! THANK YOU!!!!

  • @dfgndfghdfghdfgh
    @dfgndfghdfghdfgh 3 роки тому +1

    super helpful and you explain stuff in a way where you don't rush through it but also don't take ages on it.

  • @kramoo
    @kramoo 4 роки тому +7

    Absolutely amazing explanation and you give hope that you said it took you a while, now look at you.

  • @topemorada
    @topemorada 3 роки тому +2

    Your SQL knowledge is admirable.

  • @AlexMar-r
    @AlexMar-r 9 місяців тому

    So easy to understand without broken English. Keep them coming!

  • @bhargav7476
    @bhargav7476 3 роки тому +2

    I bought a course on Udemy, you solve like 10 doubts I had in just 1 video

  • @jessibaby901
    @jessibaby901 2 роки тому

    overwhelmed?! tuh... i am terrified!
    i came to you, from my online course, for some type of clarity.
    what did I get you might ask. HUMBLED!
    tfs this video anyway, I'm hopeful I will find some gems on your channel.
    -your new (maybe in over her head) subscriber

  • @ripndipp
    @ripndipp 4 роки тому +4

    Excellent explanation, these sub queries got me messed up but this video helped. Your great and explaining and hoping you succeed with your channel, you seem like a genuine dude.

    • @becomingADS
      @becomingADS  4 роки тому

      Thanks a lot for the kind words, means a lot!

  • @basetroll1627
    @basetroll1627 3 роки тому +1

    Very helpful, some key explanation that made it "click" with me. And most of all, I like that you confess to your struggle at the beginning, beacause I have my though times right now....

  • @Peter-cx4ir
    @Peter-cx4ir 2 роки тому +2

    Really great explanations. Easy to follow and perfect variety. Very much appreciate you posting these tutorials, they're beyond helpful. Thanks!

  • @liwaygorzon
    @liwaygorzon 5 місяців тому

    hope you would keep on making SQL tutorials (or other programming language). you help me a lot in my review for my assessment. you have explained each topic very well! I'm learning a lot from you.

  • @GeloEd
    @GeloEd 3 роки тому +1

    There are also subqueries in join. It's hard to find a material as good as this. Leaving a like and comment to support your channel.

  • @ahmedopeyemi2980
    @ahmedopeyemi2980 Рік тому

    Where the heck have you been? You’re the only useful person on UA-cam!

  • @alejguz1552
    @alejguz1552 Рік тому

    Thank you for sharing, I feel stupid not understanding, but you kind of make it clearer

  • @williammandang
    @williammandang 3 роки тому

    I didn't understand the concept one bit and I didn't understand why we should use them when I was in the university, but I understand now lol. Thanks for the tutorial. It's simple, yet really helpful for me

  • @cameronp3157
    @cameronp3157 3 роки тому +3

    Great video man!
    The best explanation of sub queries that I found!
    This is helping me a lot because I'm starting with a course of T-SQL

  • @TheOrionMusicNetwork
    @TheOrionMusicNetwork 3 роки тому +2

    Brilliant explanation The online course I took had me lost at this part.

  • @jeevak840
    @jeevak840 8 місяців тому

    Actually for me this makes amazing sense. Thanks for the tutorial.

  • @ALEX86ZILBER
    @ALEX86ZILBER Рік тому +1

    Thank you, a great explanation and examples for subqueries.

  • @user-go2pt8ef4q
    @user-go2pt8ef4q Рік тому

    Thank you for explaining it the way you did, it just clicked for me. Great stuff! Keep up the good videos.

  • @davidcoley4156
    @davidcoley4156 2 роки тому

    A great, and much needed take on this subject.

  • @sopauljauck4163
    @sopauljauck4163 4 роки тому +2

    Thank you for summing up subquery. Thank you.

  • @michael95621
    @michael95621 3 роки тому +2

    Just a note for others; The first type of subselect, the way it was written will apply the aggregate of the whole table to each row. As far as I know all major versions of SQL support this.
    It's useful if you need min/max/grand total at the table level. For instance;
    select customerid, sum(freight) as subt, (select sum(freight) from orders) as grandt, subt/grandt from orders group by 1.
    This will get you the customer ID, sum of freight by customerid, and sum of freight for all customerids, and the % of the grandt each customerId makes up.
    Some versions of SQL support using this type of subselect to directly compute the subt. The modification would be;
    (SELECT AVG(freight) FROM orders as o1 where o1.customerid = o2.customerid) from orders as o2. --This should achieve the same result as sum(freight) above, but my experience is not all versions of SQL are capable of understanding how to do this and will throw errors or bad results.
    A final note. Subqueries are also very useful if your version of SQL doesn't support pivot and unpivot functions. What I have also found is almost any time you are creating a temp table you could probably be using a subquery in 1/3 the lines and a lot more clear.

  • @samuelopoku-acheampong5601
    @samuelopoku-acheampong5601 3 роки тому +2

    Thanks for the tutorials, you have being of great help on this journey...Keep them coming

  • @EK-ee4gb
    @EK-ee4gb 3 роки тому

    Awesome explanation. Thank you very much. I was completely lost on subqueries.

  • @borjonx
    @borjonx 3 роки тому +1

    This is exactly what I was looking for - thank you for sharing!

    • @borjonx
      @borjonx 3 роки тому

      Does the internal table have to be the same as the outer table? "orders" in your example.

  • @lamborghiniveneno8423
    @lamborghiniveneno8423 2 роки тому

    And The search ends here.... Perfect 💯

  • @jude3026
    @jude3026 3 роки тому +1

    you just helped me through my project in SQL, thankss a lot!

  • @Ikilledthebanks
    @Ikilledthebanks 6 місяців тому

    Great videos, if you ever update maybe consider adding a use case with each example?

  • @kayceeDis
    @kayceeDis 6 днів тому

    This is an excellent video. Thank you!

  • @ced4298
    @ced4298 2 роки тому

    Really good explanation. I will be glad to share this with developers who write "expensive" queries with complex join statements.😀

  • @anievgenieva8267
    @anievgenieva8267 3 роки тому +1

    Thank you! You look so positive and warm person :)

  • @jcopas1826
    @jcopas1826 2 роки тому

    This was very helpful. It saved me a lot of time. I understood it the first viewing and was able to apply the concepts with ease and complete my homework on time. Thank you, you do an excellent job. I will come back for future questions in SQL.

  • @mitul509
    @mitul509 3 роки тому +1

    I like how you explain, keep up the good work.

  • @VaaniMogan
    @VaaniMogan 3 місяці тому

    Thank you for this brilliant video. Please upload more :) :).

  • @manaygun
    @manaygun Рік тому

    Simple and direct. Just what I was needed.

  • @andyn6053
    @andyn6053 3 роки тому +1

    great videos! Its soo much easier too understand when watching your tutorials! Please do more advanced videos with window functions etc.

  • @jennifergonzalez6431
    @jennifergonzalez6431 3 роки тому +2

    What does the 1,2 mean in the Group By 1,2?

  • @SjeetjeMineetje
    @SjeetjeMineetje 3 роки тому +6

    All your videos are very helpful and well explained! Helps me a lot in understanding SQL better. Are you planning on doing any more on SQL soon?

  • @Virtualexist
    @Virtualexist 3 роки тому +1

    Hi there, I really liked the explanation, just a suggestion if you would give a very quick overview of the heads of the dataset so that it is easier to comprehend more how the query/subquery is extracting the data.

  • @maniijuan
    @maniijuan Рік тому

    You sir are such a great teacher. Thank you

  • @1mmoralls
    @1mmoralls 2 роки тому

    Great video! Thank you so much for bringing a clear explanation of this topic. I look forward to viewing your other videos.

  • @sandile13809
    @sandile13809 3 роки тому

    it should be a crime that universities get away with charging 50k of tuition for a shittier version of the stuff we learn for free. Really helpful!

  • @zoeteets9353
    @zoeteets9353 2 роки тому

    This is so helpful! Thank you!! Rec: time stamps for each example

  • @alexg97343
    @alexg97343 2 роки тому

    Great video easy to understand

  • @PythonArms
    @PythonArms 2 роки тому

    explained very well. thank you

  • @kbishop9360
    @kbishop9360 2 роки тому

    Thanks for this sql series

  • @akj3388
    @akj3388 2 роки тому +1

    It seems the subquery in the where clause is easiest to understand. SQ in the select statement is probably used to compare as it's gong to give only a single value irrespective of all the records. And finally SQ in the from can be used to create a temp table with aggregates; which will be used by outer query to do further aggregates.

  • @petrblue
    @petrblue Рік тому

    Thanks, great explanation!

  • @kenchin5722
    @kenchin5722 3 роки тому

    That was great Explaination.

  • @shehanguruge7025
    @shehanguruge7025 4 роки тому

    Well explained thanks a lot finally was able to get a better grasp of Sub Queries

  • @debbietownsend1673
    @debbietownsend1673 Рік тому

    I love the way you teach. You are clear and concise. How long have you been writing SQL?

  • @locke827
    @locke827 7 місяців тому

    Great explanation. Thank you :)

  • @woodynani4394
    @woodynani4394 4 роки тому +2

    Thank you for your effort, keep moving

  • @trucco16
    @trucco16 3 роки тому

    you are a champion thanks a lot..(im buying your book also!!!)

  • @lazarus8011
    @lazarus8011 2 роки тому

    Thanks helped me out heaps!

  • @jaimetirado6130
    @jaimetirado6130 2 роки тому

    Very helpful - thank you !!

  • @TheCazz10
    @TheCazz10 3 роки тому

    Thank you for this video, think subqueries is slowly starting to sink in

  • @hungrygarfield
    @hungrygarfield Рік тому

    You’re a real G

  • @FilthyGreen
    @FilthyGreen 2 роки тому

    This video saved my ass, THANK YOU.

  • @tyroneogarrojr.453
    @tyroneogarrojr.453 2 роки тому

    Great video, very comprehensive!

  • @DataNovelties
    @DataNovelties 3 роки тому

    Lovely. Thanls a lot for this great share 👌🙂

  • @gabrielhauschildt4674
    @gabrielhauschildt4674 Рік тому +1

    Average number of orders per customer is a bit ambiguous as this could mean per specific customer instead of per one general customer.

  • @inspirelegacy547
    @inspirelegacy547 2 роки тому

    Like how do WE make a Query of two cities in a STATION table with the shortest and longest CITY names, as well as their respective lengths (i.e.: number of characters in the name). If there is more than one smallest or largest city, choose the one that comes first when ordered alphabetically.

  • @Beavin_it_up
    @Beavin_it_up 2 роки тому

    thank god for this video!

  • @brandability2474
    @brandability2474 2 роки тому

    I am here wondering if another way to write the first example with freight as
    SELECT AVG(Freight), customer_id
    FROM orders
    GROUP BY customer_id
    Would give same result as the Subquery in the first example?

  • @williamredwine722
    @williamredwine722 Рік тому

    Thank you for this video

  • @jorgeduardo101
    @jorgeduardo101 2 роки тому

    Awesome vid! thanks bud :)

  • @ankitachouhan6640
    @ankitachouhan6640 3 роки тому +1

    Great explanation! Do you have a video for Correlated Subquery as well? It is super confusing

  • @rackellewilkinson-alston
    @rackellewilkinson-alston 3 роки тому +1

    loved this!!!

  • @mattk3650
    @mattk3650 4 роки тому +1

    thanks man, appreciate the explanation

  • @alvrey3390
    @alvrey3390 3 роки тому

    Amazing Explanation Thank you 🙌

  • @iced92americano
    @iced92americano 4 роки тому +1

    you'd think it'd be easy to find this info out there, but my online SQL course didn't cover it as well as you did. Thanks for the video!

    • @summer9380
      @summer9380 3 роки тому

      was it udemy BA analyst course by any chance because i though the same thing haha

  • @DanielOsw
    @DanielOsw 3 роки тому

    Isso eh curso pra não mancos THANKS!

  • @dawitworku821
    @dawitworku821 4 місяці тому

    Very helpful. Than you.

  • @paulntalo1425
    @paulntalo1425 3 роки тому

    Thank you for the video

  • @matthewday4376
    @matthewday4376 2 роки тому

    thanks for the explanations. Why wouldn't you be able to take the average directly instead of needing to first subquery? Also, in the first subquery example, why do you need the subquery instead of writing SELECT AVG(freight)?

  • @ka1r0ww
    @ka1r0ww 2 роки тому

    Quick question: what is the group by 1,2 doing? is that just ordering them by the order in which they columns were entered in the select statement?

  • @jhonpeteranduyon7247
    @jhonpeteranduyon7247 3 роки тому

    Thank you! This helps me a lot.

  • @justineasterday4695
    @justineasterday4695 4 роки тому +1

    Dude this was great.

  • @zeusignap1477
    @zeusignap1477 7 місяців тому

    comment for algorithim, cheers mate

  • @srem1971
    @srem1971 4 роки тому

    Great explanation. Thank you!

  • @heatherline_
    @heatherline_ 10 місяців тому

    I don't get it why need to use subqueries for the select clause average freight. Why can't just use avg(frieght)? Arent that the same thing?

  • @FrocketGaming
    @FrocketGaming 2 роки тому

    Question regarding the first example; could you not achieve the same result without a subquery by just adding avg(freight) as avg to the original select statement?

  • @jettecantoria
    @jettecantoria Рік тому

    Thank you again

  • @aneeshchandramouli7440
    @aneeshchandramouli7440 4 роки тому +4

    Great explanation! What do the numbers 1 and 2 represent in the command "GROUP BY 1, 2" ?

    • @summer9380
      @summer9380 3 роки тому

      what i wondered too

    • @TheIgory1
      @TheIgory1 3 роки тому +1

      @@summer9380 My guess is referring to the columns in the select. As group be the first attribute then group by the second (cant remember the exact attribute names).

  • @nijulllee
    @nijulllee Рік тому

    Thank you bro man 💥

  • @nathanbenton2051
    @nathanbenton2051 4 роки тому +1

    Great videos - keep it up!

  • @spaaaaace8952
    @spaaaaace8952 Рік тому

    Thank you, kind sir. This was essential.

  • @drillcream
    @drillcream Рік тому

    Beginner here with some experience. I don't get the group by 1 , 2. I'm used to grouping by the field name. Is Group BY 1, 2 the same as typing Group BY customerID, shipcountry ?

  • @victorleong383
    @victorleong383 3 роки тому

    Hi Sir, can you make videos on how to interpret EXPLAIN statements, how each line of explanation tallies with each query or subquery, and how the fixes translates to the new EXPLAIN statements? Thanks for making this video by the way!

  • @omarkhaled6006
    @omarkhaled6006 2 роки тому

    amazing man good job