hibernate/hibernate-orm · error · IllegalQueryOperationException

Cannot order by element " + element + " (the first select it

Error message

Cannot order by element " + element + " (the first select item is element 1)

What it means

Thrown as IllegalQueryOperationException by SqmUtil.selectedNode when Order.element() is less than 1. Select-list element positions used for ordering are 1-based: element 1 is the first select item. An Order built with element 0 or a negative number (or a default like -1 leaking from a record that never set a real position) is invalid before anything else is checked.

Source

Thrown at hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmUtil.java:952

					while ( tokens.hasMoreTokens() ) {
						path = path.get( tokens.nextToken() );
					}
					return builder.sort( path, order.direction(), order.nullPrecedence(), !order.caseSensitive() );
				}
				else {
					throw new IllegalQueryOperationException("Select item was not an entity type");
				}
			}
			else {
				throw new IllegalQueryOperationException("Query has multiple items in the select list");
			}
		}
	}

	private static SqmSelectableNode<?> selectedNode(AbstractSqmSelectQuery<?> sqm, Order<?> order) {
		final int element = order.element();
		if ( element < 1) {
			throw new IllegalQueryOperationException("Cannot order by element " + element
					+ " (the first select item is element 1)");
		}
		final var querySpec = sqm.getQuerySpec();
		final var selectionItems = querySpec.getSelectClause().getSelectionItems();
		final int items = selectionItems.size();
		if ( items == 0 && element == 1 ) {
			if ( order.entityClass() == null || querySpec.getRootList().size() > 1 ) {
				throw new IllegalQueryOperationException("Cannot order by element " + element
						+ " (there is no select list)");
			}
			else {
				return querySpec.getRootList().get(0);
			}
		}
		else if ( element > items ) {
			throw new IllegalQueryOperationException( "Cannot order by element " + element
					+ " (there are only " + items + " select items)");
		}

View on GitHub (pinned to fad1729dce)

Solutions

  1. Use 1-based element positions: the first select item is element 1
  2. Convert external 0-based indexes: Order.by(externalIndex + 1, direction)
  3. If the order spec may be unset, skip addOrder when the index is not a positive number
  4. Prefer entity-anchored Order.asc(Class, attributeName) when you know the attribute name

Example fix

// before (uiColumnIndex is 0-based)
query.addOrder(Order.by(uiColumnIndex, ascending ? SortDirection.ASCENDING : SortDirection.DESCENDING));
// after
query.addOrder(Order.by(uiColumnIndex + 1, ascending ? SortDirection.ASCENDING : SortDirection.DESCENDING));
Defensive patterns

Strategy: validation

Validate before calling

static int toHibernateElementIndex(int zeroBasedIndex) {
    if (zeroBasedIndex < 0) {
        throw new IllegalArgumentException("Column index must be >= 0 (0-based): " + zeroBasedIndex);
    }
    return zeroBasedIndex + 1; // Hibernate select elements are 1-based
}

Try / catch

try {
    query.addOrder(Order.by(element, direction)).getResultList();
} catch (IllegalQueryOperationException e) {
    if (element < 1) throw new IllegalArgumentException("Sort element must be >= 1, got " + element, e);
    throw e;
}

Prevention

When it happens

Trigger: Order.by(0, SortDirection.ASCENDING) or Order.by(-1, ...); mapping a 0-based sort-column index from a UI/API (DataTables, GraphQL order spec) straight into Order.by(index) without adding 1; a NamedAttributeOrder whose element() sentinel (-1) is passed through because no attribute name was set either.

Common situations: Frontend grid sorting sends 0-based column indexes; order specifications deserialized from JSON where the index field defaults to 0; glue code between a 0-based spec and Hibernate's 1-based element model.

Related errors


AI-assisted analysis of hibernate/hibernate-orm@fad1729dce (2026-08-22). Data as JSON: /api/errors/3ddf3d606ec96da0. Report an issue: GitHub.