Skip to content
Advertisement

Working of “between” operator for Varchar and Char datatypes in postgresql

I would like to use “between” operator on “varchar” and “char(5)” columns in a table. However, I don’t see any effect of “between” operator in the results.

Please note that “code” is the column name

I have a table with a column of type VARCHAR and I apply cast operation to convert it into “CHAR(5)” type. When I apply between operator in the query on either of the columns, it doesn’t produce a filtered result.

For VARCHAR COLUMN

For CHAR(5) COLUMN

I expect the output to have only records within this range but instead I get records which don’t meet this criteria as well. Please find a sample screenshot below

enter image description here

Advertisement

Answer

demo:db<>fiddle

The BETWEEN operator for character based types works for alphabetical order. That means it uses the order

So the output is completely correct.

If you want a numeric order you have to cast it into an appropriate data type:

Result:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement