Why do I need to use a subquery for this SQL query?
-
Here are some assumptions: 2) Lets consider the student_details table which we have used earlier. If you know the name of the students who are studying science subject, you can get their id's by using this query below, SELECT id, first_name FROM student_details WHERE first_name IN ('Rahul', 'Stephen'); but, if you do not know their names, then to get their id's you need to write the query in this manner, SELECT id, first_name FROM student_details WHERE first_name IN (SELECT first_name FROM student_details WHERE subject= 'Science'); If I don't know there names, can I just use this query: SELECT id, first_name FROM student_details WHERE subject = 'Science';
-
Answer:
Just to be clear, the second query and the third query are NOT the same. Consider this data set (ID, FirstName, Last Name, Subject) (2, Rahul, Gandhi, Physics) (3, Stephen, Colbert, Comedy) (4, Stephen, Hawking, Science) The query: SELECT id, first_name FROM student_details WHERE first_name IN (SELECT first_name FROM student_details WHERE subject= 'Science'); will return 3, Stephen 4, Stephen While the fourth will return only 4, Stephen In cases where there are multiple records with the same first name, the second query and the third query will return different results.
Amrith Kumar at Quora Visit the source
Other answers
Your question is a little confusing but it does appear that the subquery in the 2nd example is pointless. The schema seems strange thoughâwhy would a student be associated with only one subject?
Toby Thain
Related Q & A:
- What paper do I need to use?Best solution by Yahoo! Answers
- What do I need to use an electric scooter?Best solution by Yahoo! Answers
- Why do I have to use snowboard wax?Best solution by Yahoo! Answers
- Why do I have to use mail classic to reply or forward e-mails?Best solution by support.office.com
- What do I need to use Xbox on my PC monitor?Best solution by superuser.com
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.