I'm working with two entities: Item
and Attribute
, which look something like the following:
Item
----
itemId
Attribute
---------
attributeId
name
An Item
has Attributes
, as specified in an association table:
ItemAttribute
--------------
itemId
attributeId
When this data gets to the client, it will be displayed with a row per Item
, and each row will have a list of Attribute
s by name. For example:
Item Attributes
---- ----------
1 A, B, C
2 A, C
3 A, B
The user will have the option to sort on the Attributes
column, so we need the ability to sort the data as follows:
Item Attributes
---- ----------
3 A, B
1 A, B, C
2 A, C
At present, we're getting one row of data per ItemAttribute
row. Basically:
SELECT Item.itemId,
Attribute.name
FROM Item
JOIN ItemAttribute
ON ItemAttribute.itemId = Item.itemId
JOIN Attribute
ON Attribute.attributeId = ItemAttribute.attributeId
ORDER BY Item.itemId;
Which produces a result like:
itemId name
------ ----
1 A
1 B
1 C
2 A
2 C
3 A
3 B
The actual ORDER BY
clause is based on user input. It's usually a single column, so the ordering is simple, and the app-side loop that processes the result set combines the Attribute
names into a comma-separated list for presentation on the client. But when the user asks to sort on that list, it'd be nice to have Oracle sort the results so that -- using the example above -- we'd get:
itemId name
------ ----
3 A
3 B
1 A
1 B
1 C
2 A
2 C
Oracle's LISTAGG
function can be used to generate the attribute lists prior to sorting; however Attribute.name
can be a very long string, and it is possible that the combined list is greater than 4000 characters, which would cause the query to fail.
Is there a clean, efficient way to sort the data in this manner using Oracle SQL (11gR2)?
ORDER BY Attributes
to your query achieve what you are looking for?Attributes
as a string: that's simply how it will be displayed on the client after the comma-separated list is built by the application. I'd have to use something likeLISTAGG
to build that list within the query, but as soon as there is a list of more than 4000 characters (Oracle's maximum size for aVARCHAR2
), the query will fail entirely.listagg
can only return 4000 chars, and you might exceed that; so you need something to replacelistagg
that isn't subject to that limit?