-- Physical panels may be displayed in a different order than their names.
ALTER TABLE locations_cross_fields
    ADD COLUMN IF NOT EXISTS display_order INTEGER;

WITH ordered AS (
    SELECT id, ROW_NUMBER() OVER (PARTITION BY location_id ORDER BY name, id) AS row_number
    FROM locations_cross_fields
    WHERE display_order IS NULL
)
UPDATE locations_cross_fields cf
SET display_order = ordered.row_number
FROM ordered
WHERE cf.id = ordered.id;

ALTER TABLE locations_cross_fields
    ALTER COLUMN display_order SET NOT NULL;

CREATE INDEX IF NOT EXISTS idx_cross_fields_location_display_order
    ON locations_cross_fields(location_id, display_order)
    WHERE deleted_at IS NULL;
