Skip to main content

Avoid TO_CHAR in an ORDER BY clause

ZPA rule for PL/SQL and Oracle SQL · ToCharInOrderBy

TO_CHAR turns a number or a date into text, and text sorts character by character: '15' comes before '5', and '02-10-2018' before '10-10-2017'. An ORDER BY on TO_CHAR of a number or a date therefore sorts the rows in an order that matches neither the numbers nor the dates, which the code rarely means.

This rule reports a TO_CHAR call as an ORDER BY expression, and an ORDER BY position (ORDER BY 2) that refers to a selected TO_CHAR call. Sort by the value itself, and format it only in the select list.

Examples​

Noncompliant Code Example
select c.code, to_char(c.created_at, 'DD-MM-YYYY') as created
from crate c
order by to_char(c.created_at, 'DD-MM-YYYY'); -- Noncompliant
Compliant Solution
select c.code, to_char(c.created_at, 'DD-MM-YYYY') as created
from crate c
order by c.created_at;