Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does postgres distinct assign a type to strings?

If you execute SELECT 'test', 123 the output will be two columns, the first with an unknown data type and the second with a data type of integer.

If you execute SELECT DISTINCT 'test', 123 the output will be two columns, the first with a data type of text and the second with a data type of integer.

Why does adding DISTINCT function different from running the query without DISTINCT in regards to the data type?

like image 597
Logan Avatar asked Jul 18 '26 04:07

Logan


1 Answers

This behaviour is described in Chapter 10. Type Conversion.

In 10.1. Overview you can find:

If a type is not specified for a string literal, then the placeholder type unknown is assigned initially, to be resolved in later stages.

To select distinct values Postgres has to convert string literals to a type with equality operator. The case is analogous to union:

select 'abc', 1
union
select 'def', 1

where the first column is resolved as text. The rule is described in 10.5. UNION, CASE, and Related Constructs:

  1. If all inputs are of type unknown, resolve as type text (the preferred type of the string category).
like image 105
klin Avatar answered Jul 21 '26 23:07

klin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!