0

ERD for my simple db design: ERD

I want to order children based on their parent's last name. I am trying to use the following query:

SELECT * 
FROM children 
WHERE parent_id IN (SELECT parent_id  
                    FROM parent 
                    ORDER BY lastName ASC);

SELECT parent_id FROM parent ORDER BY lastName ASC returns the parent_ids in the order of the parent's last names (this is the intended behavior). The ordering of parent_ids according to their last names in ascending order is 154,156,155,157

However, when used as a subquery, the ordering is apparently not used correctly. The results are: query results

As you can see the results are ordered in ascending order of parent_id (not of the child's respective parent's last name).

Is there a way to correctly structure this query without changing my design?

Thank you.

1
  • I know it would probably be better to just include the last name in the Children table as well, but I don't want duplicate data in my db, so I'd like the Children's last name to simply be stored in one location (their parent's table)
    – Kapernski
    Commented Mar 7, 2022 at 23:46

1 Answer 1

1

The subselect returns a set, which has no order, the order by there is useless - it will not apply to the final result set. If you want to order "children" by their "parent"s' "last names", you'll have to project those "last names" to the outer select by joining the two relations:

SELECT c.* 
FROM children c
INNER JOIN parent p
ON c.parent_id = p.parent_id
ORDER BY lastName ASC
5
  • thank you! This does give me the correct results. Just out of curiosity, is there a way to achieve this with a subquery? Or does my db design not work well with that?
    – Kapernski
    Commented Mar 7, 2022 at 23:54
  • this has nothing to do with the database design -- only with the relational theory
    – mustaccio
    Commented Mar 7, 2022 at 23:55
  • got it. I have an easier time understanding subqueries when joining tables, would you mind sharing the subquery equivalent of what you provided?
    – Kapernski
    Commented Mar 8, 2022 at 0:01
  • 2
    there's no reasonable equivalent without using a join, so you probably want to expand your SQL vocabulary
    – mustaccio
    Commented Mar 8, 2022 at 0:25
  • 1
    @Kapernski I think your misunderstanding of the original problems relates to how ORDER BY works. While the results were in order in the subquery, the top query only checks to see the ID exists in the subquery. It does not in turn also sort it's own output based on the order those IDs were supplied. Commented Mar 8, 2022 at 14:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.