{"record":{"id":"399f733d69d9380f","repo":"hibernate/hibernate-orm","slug":"cannot-order-by-element-element-there-are","errorCode":null,"errorMessage":"Cannot order by element \" + element + \" (there are only \" + items + \" select items)","messagePattern":"Cannot order by element \" \\+ element \\+ \" \\(there are only \" \\+ items \\+ \" select items\\)","errorType":"exception","errorClass":"IllegalQueryOperationException","httpStatus":null,"severity":"error","filePath":"hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmUtil.java","lineNumber":968,"sourceCode":"\t\tfinal int element = order.element();\n\t\tif ( element < 1) {\n\t\t\tthrow new IllegalQueryOperationException(\"Cannot order by element \" + element\n\t\t\t\t\t+ \" (the first select item is element 1)\");\n\t\t}\n\t\tfinal var querySpec = sqm.getQuerySpec();\n\t\tfinal var selectionItems = querySpec.getSelectClause().getSelectionItems();\n\t\tfinal int items = selectionItems.size();\n\t\tif ( items == 0 && element == 1 ) {\n\t\t\tif ( order.entityClass() == null || querySpec.getRootList().size() > 1 ) {\n\t\t\t\tthrow new IllegalQueryOperationException(\"Cannot order by element \" + element\n\t\t\t\t\t\t+ \" (there is no select list)\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn querySpec.getRootList().get(0);\n\t\t\t}\n\t\t}\n\t\telse if ( element > items ) {\n\t\t\tthrow new IllegalQueryOperationException( \"Cannot order by element \" + element\n\t\t\t\t\t+ \" (there are only \" + items + \" select items)\");\n\t\t}\n\t\telse {\n\t\t\treturn selectionItems.get( element - 1 );\n\t\t}\n\t}\n\n\tpublic static boolean isSelectionAssignableToResultType(SqmSelection<?> selection, Class<?> expectedResultType) {\n\t\tif ( expectedResultType == null ) {\n\t\t\treturn true;\n\t\t}\n\t\telse if ( selection != null && selection.getSelectableNode() instanceof SqmParameter<?> sqmParameter ) {\n\t\t\tfinal BindableType<?> anticipatedType = sqmParameter.getAnticipatedType();\n\t\t\tfinal var anticipatedClass = anticipatedType != null ? anticipatedType.getJavaType() : null;\n\t\t\treturn anticipatedClass != null && expectedResultType.isAssignableFrom( anticipatedClass );\n\t\t}\n\t\telse if ( selection == null\n\t\t\t\t|| !isHqlTuple( selection ) && selection.getSelectableNode().isCompoundSelection() ) {","sourceCodeStart":950,"sourceCodeEnd":986,"githubUrl":"https://github.com/hibernate/hibernate-orm/blob/fad1729dce015f908198d57a8d80274a30f905a5/hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmUtil.java#L950-L986","documentation":"Thrown as IllegalQueryOperationException by SqmUtil.selectedNode when Order.element() exceeds the number of selection items in the query's select clause. The order tries to sort by a select-list element that does not exist (e.g. element 3 in a two-item select list), which Hibernate detects before building the SQL order-by expression.","triggerScenarios":"Order.by(3, direction) on 'select p.name, p.age from Person p'; a sort-column index computed from an external spec while the query was later changed to fewer select items; ordering by element 2 on a single-item projection; count queries (one item) receiving an order built for a wider list query.","commonSituations":"Shared order objects reused across queries whose select lists differ in width; refactoring a projection from three columns to two while the UI still sends column index 3; DataTables-style grid sorting where the visible column list and the query's select list drift apart.","solutions":["Clamp or validate the element index against the actual select-list size before addOrder","Update the order to an existing element or to an entity-anchored Order.asc(Class, attribute)","Map UI column indexes to explicit HQL order-by paths instead of raw positions","Add the missing select item if the order intentionally references it"],"exampleFix":"// before (query selects 2 items, order asks for element 3)\nquery.addOrder(Order.by(3, SortDirection.ASCENDING));\n// after\nif (orderIndex >= 1 && orderIndex <= selectItemCount) {\n    query.addOrder(Order.by(orderIndex, SortDirection.ASCENDING));\n}","handlingStrategy":"validation","validationCode":"static Order<?> clampOrValidate(Order<?> order, int selectItemCount) {\n    int element = order.element();\n    if (order.entityClass() == null && (element < 1 || element > selectItemCount)) {\n        throw new IllegalArgumentException(\n            \"Sort element \" + element + \" outside select list of \" + selectItemCount + \" items\");\n    }\n    return order;\n}\n// call clampOrValidate(order, selectItemCount) before query.addOrder(order)","typeGuard":null,"tryCatchPattern":"try {\n    query.addOrder(order).getResultList();\n} catch (IllegalQueryOperationException e) {\n    // element out of range: degrade to default deterministic ordering\n    query.addOrder(Order.by(1, SortDirection.ASCENDING)).getResultList();\n}","preventionTips":["Track the select-list width next to every order spec","Validate external sort indexes against the current select list at the controller boundary","Drop stale sort columns when shrinking a projection"],"tags":["hibernate","order-by","index-out-of-bounds","query-api"],"backgroundTag":"invalid-order-by-clause","analyzedSha":"fad1729dce015f908198d57a8d80274a30f905a5","analyzedAt":"2026-08-22T04:13:57.527Z","schemaVersion":2},"datasetVersion":"2026-08-22T09:17:25.309Z"}