LoginSignup
1
0

PostgreSQL UNION、UNION ALLのデータ型不一致エラー

Last updated at Posted at 2024-06-12

業務中に出会ったエラー。

テーブル

student、parentテーブル

No 物理名 データ型
1 name text

teacherテーブル

No 物理名 データ型
1 name text
2 age numeric

エラーが発生するSQL

select name, null as age from student
union all
select name, null as age from parent
union all
select name, age from teacher

エラー内容

UNION types text and numeric cannot be matched
型が一致していないよ、というエラー。
UNION、もしくは、UNION ALLを使用する場合、結合されるすべてのSELECT文の対応する列のデータ型が一致している必要がある。
が、nullの型が指定されていない場合、textと判断される模様。

対処法

select name, null::numeric as age from student
union all
select name, null as age from parent
union all
select name, age from teacher

null::numeric as ageと明示的に型を指定することで、型不一致のエラーが回避できる。

ちなみに

  • 型が明示的なselect文を2番目までに記載している場合
select name, age from teacher
union all
select name, null as age from student
union all
select name, null as age from parent

または

select name, null as age from student
union all
select name, age from teacher
union all
select name, null as age from parent

この場合はエラーが発生しない。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0