Explain Codes LogoExplain Codes Logo

Custom Order in Oracle SQL

sql
join
performance
best-practices
Nikita BarsukovbyNikita Barsukov·Aug 24, 2024
TLDR

To harness custom sorting in Oracle SQL, use a CASE expression in your ORDER BY clause. Assign a numerical hierarchy to the desired values:

--Distribute ranks like a king in his court SELECT * FROM table_name ORDER BY CASE column_name WHEN 'Value1' THEN 1 WHEN 'Value2' THEN 2 ELSE 3 END;

Replace table_name, column_name, Value1, Value2 with your actual values. 'Value1' rows will nestle at the top, followed by 'Value2', and then the commoners (read: all others).

Alternate way: DECODE your needs

DECODE to the rescue when you want a shorter expression:

--Decode messages like a secret agent SELECT * FROM table_name ORDER BY DECODE(column_name, 'USD', 1, 'EUR', 2, 3);

This command cushions USD at the top, succeeded by EUR, with the remaining currencies trailing behind, not lost, but in their natural order.

Volatile data, static code

Your currency codes change more often than a chameleon? You can use subqueries or joins to rank dynamically without hacking up a forest of hardcoded values.

The SPECIAL CHARacters

Currency codes that behave like primadonnas and demand a specific order can be managed by prefixing them with special characters in our CASE logic:

--Rowdy codes? Prefix a '!' SELECT * FROM table_name ORDER BY CASE WHEN SUBSTR(column_name, 1, 1)='!' THEN 1 ELSE 2 END, column_name;

Currency codes that come with an exclamation mark get bumped up to first class.

The OCTOPUS order

OCTOPUS isn't a sea creature here but a guide: Ordering, CTs, OPtions for UserS. When you're sorting numerical values, keep in mind not to sort octopuses (because they hate it), but to have an order that mirrors your business sensibilities. For ghost currencies (they just appear, don't they?), specify a default sort order to keep from ghostbusters (serious errors).

One size doesn't fit all

You have a dataset as global as Netflix. It, however, needs to cater to local tastes. Localization based sorting preferences might need to be stored externally or incorporated based on user region or profiles.

Be mindful of the Elephants

Going CASE or DECODE might affect performance, especially if your data resembles a herd of elephants (huge). Building function-based indexes can be your circus ringmaster guiding the performance (no elephants were harmed in writing this analogy).