Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL - group by char cast

Using the a char-cast in a group-by clause results something unexpected:

select cast(col as char(2)) from (
  select 'Abc' as col from dual
  union all
  select 'Abc' as col from dual
) group by cast(col as char(10));

The result is 'Abc ' (10 characters long). Intuitively, I would have expected Oracle to return one of the following:

  • An error: 'not a group-by expression', as the group-by clause is another than the selection clause
  • A result of length 2 'Ab'.

Replacing cast(col as char(2)) with cast(col as char(3)), Oracle returns an error 'not a group-by expression'. This, again is a very strange behavior.

How can this be explained? What's the reason behind it?

I'm using Oracle SQL 11g.

like image 229
nico.ruti Avatar asked Oct 31 '22 02:10

nico.ruti


1 Answers

As was mentioned above, I think there is a misunderstanding going on. o.O

I can't explain why it's doing this, but here's the pattern for the type of query you have:

If you generalize it a bit like this, where [A] and [B] are integers, and [STRING] is whatever text you want:

select cast(col as char([A])) from (
  select '[STRING]' as col from dual
  union all
  select '[STRING]' as col from dual
) group by cast(col as char([B]));

it looks like this always fails if one of the two conditions below is true (there may be others):

  1. ( LENGTH([STRING]) < [B] OR LENGTH([STRING] > [B]) and [A] = LENGTH([STRING])
  2. ( LENGTH([STRING]) = [B] AND [A] <> LENGTH([STRING]) )

Otherwise, it'll return a row.

But if you take your example that runs and use it in a CREATE TABLE statement, it's going to fail as it sets up the column width to be the 2 and can't fit the 3 character string coming in.

To add to the oddity, if you append something at the start and the end of the string like this:

select '\*'||cast(col as char([A]))||'\*' from (
  select '[STRING]' as col from dual
  union all
  select '[STRING]' as col from dual
) group by cast(col as char([B]));

This will only work if [A] >= [B], otherwise it fails on ORA-01489: result of string concatenation is too long.

Curious...

like image 183
Patrick Marchand Avatar answered Nov 15 '22 06:11

Patrick Marchand