@Override
    public int compare(Object a, Object b) {

        SubQuery sqa = (SubQuery) a;
        SubQuery sqb = (SubQuery) b;

        if (sqa.parentView == null && sqb.parentView == null) {
            return sqb.level - sqa.level;
        } else if (sqa.parentView != null && sqb.parentView != null) {
            int ia = database.schemaManager.getTableIndex(sqa.parentView);
            int ib = database.schemaManager.getTableIndex(sqb.parentView);

            if (ia == -1) {
                ia = database.schemaManager.getTables(
                    sqa.parentView.getSchemaName().name).size();
            }

            if (ib == -1) {
                ib = database.schemaManager.getTables(
                    sqb.parentView.getSchemaName().name).size();
            }

            int diff = ia - ib;

            return diff == 0 ? sqb.level - sqa.level
                             : diff;
        } else {
            return sqa.parentView == null ? 1
                                          : -1;
        }
    }
@ Override public int compare ( Object a , Object b ) { SubQuery sqa = ( SubQuery ) a ; SubQuery sqb = ( SubQuery ) b ; if ( sqa . parentView == null && sqb . parentView == null ) { return sqb . level - sqa . level ; } else if ( sqa . parentView != null && sqb . parentView != null ) { int ia = database . schemaManager . getTableIndex ( sqa . parentView ) ; int ib = database . schemaManager . getTableIndex ( sqb . parentView ) ; if ( ia == - 1 ) { ia = database . schemaManager . getTables ( sqa . parentView . getSchemaName ( ) . name ) . size ( ) ; } if ( ib == - 1 ) { ib = database . schemaManager . getTables ( sqb . parentView . getSchemaName ( ) . name ) . size ( ) ; } int diff = ia - ib ; return diff == 0 ? sqb . level - sqa . level : diff ; } else { return sqa . parentView == null ? 1 : - 1 ; } }
This results in the following sort order:

view subqueries, then other subqueries

view subqueries:
views sorted by creation order (earlier declaration first)

other subqueries:
subqueries sorted by depth within select query (deep == higher level)