PostgreSQL 17.12実機検証済み · 2026-11-30

PostgreSQL 42804: データ型の不一致 (datatype mismatch)

同じ型でなければならない値同士が、PostgreSQL が自動変換しない別の型になっています。

PostgreSQL 17.12
42804: 列"stock_qty"は型integerには自動的に型変換できません
42804: column "stock_qty" cannot be cast automatically to type integer

原因へ移動

  1. 01text 列を USING なしで integer に ALTER
  2. 02整数フラグ(1/0)を boolean 列に INSERT
  3. 03CASE の分岐ごとに結果の型が違う
  4. 04UNION の同じ位置の列の型が違う
  5. 05WITH RECURSIVE で varchar(n) 列を連結していく

実機検証済みPostgreSQL 17.12 で再現・解決を確認 · 2026-11-30 · コンテナイメージ postgres:17

SQLSTATE 42804(datatype_mismatch)は、列・CASE の結果・UNION の列が1つの型である必要があるのに、渡した値の型が違い自動変換もない場合に発生します。メッセージに両方の型が表示されます。

文全体が失敗し、変更される行はありません。PostgreSQL 17 で確認した5つの原因です。

01text 列を USING なしで integer に ALTER

stock_qty は text です。ALTER TABLE items ALTER COLUMN stock_qty TYPE integer は「列"stock_qty"は型integerには自動的に型変換できません」で失敗します。HINT に USING stock_qty::integer が表示されます。

事前準備
事前準備lab_a で実行
CREATE TABLE items (id int PRIMARY KEY, stock_qty text);
INSERT INTO items VALUES (1, '10'), (2, '25');
OUTPUT
CREATE TABLE
INSERT 0 2
再現lab_a で実行
ALTER TABLE items ALTER COLUMN stock_qty TYPE integer;
✕ エラー
ERROR:  42804: column "stock_qty" cannot be cast automatically to type integer
HINT:  You might need to specify "USING stock_qty::integer".
対処lab_a で実行
ALTER TABLE items ALTER COLUMN stock_qty TYPE integer USING stock_qty::integer;
OUTPUT
ALTER TABLE

USING 句を付けます: ALTER TABLE items ALTER COLUMN stock_qty TYPE integer USING stock_qty::integer。値 10、25 はそのまま残り、pg_typeof は integer になります。

対処後の再実行lab_a で実行
SELECT id, stock_qty, pg_typeof(stock_qty) FROM items ORDER BY id;
✓ 成功
 id | stock_qty | pg_typeof
----+-----------+-----------
  1 |        10 | integer
  2 |        25 | integer
(2 rows)

02整数フラグ(1/0)を boolean 列に INSERT

旧テーブルは active_flag を int(1/0)、新テーブルは is_active を boolean で持っています。INSERT ... SELECT id, active_flag は「型booleanですが、式は型integerでした」で失敗します。

事前準備
事前準備lab_a で実行
CREATE TABLE legacy_users (id int, active_flag int);
INSERT INTO legacy_users VALUES (1, 1), (2, 0);
CREATE TABLE users (id int PRIMARY KEY, is_active boolean);
OUTPUT
CREATE TABLE
INSERT 0 2
CREATE TABLE
再現lab_a で実行
INSERT INTO users (id, is_active) SELECT id, active_flag FROM legacy_users;
✕ エラー
ERROR:  42804: column "is_active" is of type boolean but expression is of type integer
LINE 1: INSERT INTO users (id, is_active) SELECT id, active_flag FRO...
                                                     ^
HINT:  You will need to rewrite or cast the expression.
確認lab_a で実行
SELECT table_name, column_name, data_type FROM information_schema.columns WHERE table_schema = 'lab_a' AND column_name IN ('active_flag', 'is_active') ORDER BY table_name;
OUTPUT
  table_name  | column_name | data_type
--------------+-------------+-----------
 legacy_users | active_flag | integer
 users        | is_active   | boolean
(2 rows)

information_schema.columns で integer と boolean を確認し、数値を条件式にします: SELECT id, active_flag = 1。t、f として挿入されます。

対処後の再実行lab_a で実行
INSERT INTO users (id, is_active) SELECT id, active_flag = 1 FROM legacy_users;
SELECT * FROM users ORDER BY id;
✓ 成功
INSERT 0 2
 id | is_active
----+-----------
  1 | t
  2 | f
(2 rows)

03CASE の分岐ごとに結果の型が違う

CASE WHEN qty > 0 THEN qty ELSE item END は一方が integer、もう一方が text を返します。CASE の結果は1つの型でなければならず、「CASEの型textとintegerを一致させることができません」になります。

事前準備
事前準備lab_a で実行
CREATE TABLE stock (item text, qty int);
INSERT INTO stock VALUES ('pen', 5), ('cup', 0);
OUTPUT
CREATE TABLE
INSERT 0 2
再現lab_a で実行
SELECT item, CASE WHEN qty > 0 THEN qty ELSE item END AS status FROM stock;
✕ エラー
ERROR:  42804: CASE types text and integer cannot be matched
LINE 1: SELECT item, CASE WHEN qty > 0 THEN qty ELSE item END AS sta...
                                            ^
確認lab_a で実行
SELECT pg_typeof(qty) AS qty_type, pg_typeof(item) AS item_type FROM stock LIMIT 1;
OUTPUT
 qty_type | item_type
----------+-----------
 integer  | text
(1 row)

pg_typeof で integer と text を確認し、すべての分岐を text にそろえます: THEN qty::text ELSE 'sold out'。5 と sold out が返ります。

対処後の再実行lab_a で実行
SELECT item, CASE WHEN qty > 0 THEN qty::text ELSE 'sold out' END AS status FROM stock ORDER BY item;
✓ 成功
 item |  status
------+----------
 cup  | sold out
 pen  | 5
(2 rows)

04UNION の同じ位置の列の型が違う

1つ目の SELECT は customers.id(integer)、2つ目は同じ位置に suppliers.code(text)を返します。UNION ALL は「UNIONの型integerとtextを一致させることができません」で失敗します。

事前準備
事前準備lab_a で実行
CREATE TABLE customers (id int, name text);
CREATE TABLE suppliers (code text, name text);
INSERT INTO customers VALUES (1, 'Kim');
INSERT INTO suppliers VALUES ('S-01', 'Acme');
OUTPUT
CREATE TABLE
CREATE TABLE
INSERT 0 1
INSERT 0 1
再現lab_a で実行
SELECT id, name FROM customers
UNION ALL
SELECT code, name FROM suppliers;
✕ エラー
ERROR:  42804: UNION types integer and text cannot be matched
LINE 3: SELECT code, name FROM suppliers;
               ^
確認lab_a で実行
SELECT table_name, column_name, data_type FROM information_schema.columns WHERE table_schema = 'lab_a' AND column_name IN ('id', 'code') ORDER BY table_name;
OUTPUT
 table_name | column_name | data_type
------------+-------------+-----------
 customers  | id          | integer
 suppliers  | code        | text
(2 rows)

information_schema.columns で integer と text を確認し、片方を変換します: SELECT id::text AS id, ...。2行(1、S-01)とも返ります。

対処後の再実行lab_a で実行
SELECT id::text AS id, name FROM customers
UNION ALL
SELECT code, name FROM suppliers;
✓ 成功
  id  | name
------+------
 1    | Kim
 S-01 | Acme
(2 rows)

05WITH RECURSIVE で varchar(n) 列を連結していく

経路の列を非再帰項では name(varchar(20))で始め、再帰項で tree.path || ' > ' || d.name と連結しました。「再帰問い合わせ"tree"の列2の型は、非再帰項の内ではcharacter varying(20)になっていますが全体としてはcharacter varyingです」で失敗し、HINT は非再帰項をキャストするよう示しています。

name::text AS path に変えると HQ、HQ > IT、HQ > IT > Infra が返りました。

事前準備
事前準備lab_a で実行
CREATE TABLE dept (id int PRIMARY KEY, parent_id int, name varchar(20));
INSERT INTO dept VALUES (1, NULL, 'HQ'), (2, 1, 'IT'), (3, 2, 'Infra');
OUTPUT
CREATE TABLE
INSERT 0 3
再現lab_a で実行
WITH RECURSIVE tree AS (
  SELECT id, name AS path FROM dept WHERE parent_id IS NULL
  UNION ALL
  SELECT d.id, tree.path || ' > ' || d.name
  FROM dept d JOIN tree ON d.parent_id = tree.id
)
SELECT * FROM tree;
✕ エラー
ERROR:  42804: recursive query "tree" column 2 has type character varying(20) in non-recursive term but type character varying overall
LINE 2:   SELECT id, name AS path FROM dept WHERE parent_id IS NULL
                     ^
HINT:  Cast the output of the non-recursive term to the correct type.
原因の確認lab_a で実行
SELECT pg_typeof(name) AS name_type, pg_typeof(name || ' > ') AS concat_type FROM dept LIMIT 1;
OUTPUT
     name_type     | concat_type
-------------------+-------------
 character varying | text
(1 row)

pg_typeof を見ると name || ' > ' は元の列の型ではなく text です。そのため 2 つの項の型が一致しません。

確認lab_a で実行
SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = 'dept' AND column_name = 'name';
OUTPUT
 column_name |     data_type     | character_maximum_length
-------------+-------------------+--------------------------
 name        | character varying |                       20
(1 row)

最初の(非再帰の)SELECT の列を、再帰項が作る型(通常は ::text)にキャストします。

対処後の再実行lab_a で実行
WITH RECURSIVE tree AS (
  SELECT id, name::text AS path FROM dept WHERE parent_id IS NULL
  UNION ALL
  SELECT d.id, tree.path || ' > ' || d.name
  FROM dept d JOIN tree ON d.parent_id = tree.id
)
SELECT * FROM tree ORDER BY id;
✓ 成功
 id |      path
----+-----------------
  1 | HQ
  2 | HQ > IT
  3 | HQ > IT > Infra
(3 rows)

よくある質問

cannot be cast automatically to type integer を解消するには?

ALTER COLUMN TYPE に USING 列::integer を付けます。エラーの HINT にそのまま使える文が表示されます。

PostgreSQL の boolean 列に 0/1 を入れるには?

flag = 1 のような条件式にして入れます。実行すると int 列は直接入らず、active_flag = 1 は成功しました。

CASE types text and integer cannot be matched とは?

THEN と ELSE の結果の型が違います。qty::text のように1つの型にそろえます。

UNION types integer and text cannot be matched とは?

各 SELECT の同じ位置の列は型が合っている必要があります。id::text のように片方を型変換します。

recursive query column has type ... in non-recursive term but type ... overall の解決方法は?

非再帰項の列を name::text AS path のようにキャストします。検証ではこれで経路の問い合わせが実行できました。

検証方法

シナリオごとに新しいDBユーザーを作成して開始します。スクリプトが事前準備 → エラー再現(エラーコードの一致を確認)→ 対処 → 元の文の再実行の順に実行し、表示している出力はDBが実際に返した結果をスクリプトがそのまま保存したものです。

lab_a・lab_b はテスト用の一般ロール(同名のスキーマを所有)、postgres はスーパーユーザーです。 PostgreSQL 17.12