Order parent records by child record count Order parent records by child record count sqlite sqlite

Order parent records by child record count


You could join it with an aggregate query on the child records and sort according to that:

SELECT   p.*FROM     pages pJOIN     (SELECT   parent, COUNT(*) AS cnt          FROM     pages          GROUP BY parent) c ON p.id = c.parentORDER BY c.cnt


You could compute the count of children with a correlated subquery and sort according to that:

SELECT id, nameFROM pagesORDER BY (SELECT count(*)          FROM pages AS p2          WHERE p2.parent = pages.id);