실제 DB 검증PostgreSQL 17.12에서 재현·해결 확인 · 2026-12-01 · 컨테이너 이미지 postgres:17
23503은 외래 키 검사에 걸렸다는 뜻이에요. 첫 줄로 방향을 알 수 있어요. 자료 추가, 갱신 작업(insert or update)이면 자식 행이 없는 부모를 가리키는 것이고, 자료 갱신, 삭제 작업(update or delete)이면 자식이 아직 쓰는 부모를 지우려는 거예요.
DETAIL 줄에 문제의 키 값이 나와요. 예: Key (customer_id)=(3) is not present in table "customers". 이 값부터 확인하세요.
01부모가 없는 값으로 자식 행 INSERT
orders.customer_id는 customers(id)를 참조해요. 고객 3번으로 주문을 넣으면 실패하고, DETAIL에 Key (customer_id)=(3) is not present in table "customers"가 나와요.
확인해 보면 고객 3번이 없어요(0 rows). 고객을 먼저 넣은 뒤 같은 주문 INSERT가 성공해요. 데이터를 옮길 때는 부모 테이블부터 넣으세요.
사전 준비
CREATE TABLE customers (id int PRIMARY KEY, name text);
CREATE TABLE orders (id int PRIMARY KEY, customer_id int REFERENCES customers(id), amount numeric);
INSERT INTO customers VALUES (1, 'Kim'), (2, 'Lee');CREATE TABLE
CREATE TABLE
INSERT 0 2INSERT INTO orders VALUES (10, 3, 15000);ERROR: 23503: insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
DETAIL: Key (customer_id)=(3) is not present in table "customers".
SCHEMA NAME: lab_a
TABLE NAME: orders
CONSTRAINT NAME: orders_customer_id_fkeySELECT id, name FROM customers WHERE id = 3; id | name
----+------
(0 rows)INSERT INTO customers VALUES (3, 'Park');INSERT 0 1INSERT INTO orders VALUES (10, 3, 15000) RETURNING id, customer_id, amount; id | customer_id | amount
----+-------------+--------
10 | 3 | 15000
(1 row)
INSERT 0 102자식 행이 남아 있는 부모 행 DELETE
고객 1번을 지우면 "customers" 테이블의 자료 갱신, 삭제 작업이 ... "orders" 테이블 - 을 위반했습니다로 실패하고, DETAIL에 Key (id)=(1) is still referenced from table "orders"가 나와요.
확인해 보면 고객 1번의 주문이 2건(10, 11) 있어요. 주문을 먼저 지우면(DELETE 2) 고객 삭제가 돼요(DELETE 1). 자식 행을 정말 지워도 되는지 먼저 확인하세요.
사전 준비
CREATE TABLE customers (id int PRIMARY KEY, name text);
CREATE TABLE orders (id int PRIMARY KEY, customer_id int REFERENCES customers(id), amount numeric);
INSERT INTO customers VALUES (1, 'Kim'), (2, 'Lee');
INSERT INTO orders VALUES (10, 1, 15000), (11, 1, 8000);CREATE TABLE
CREATE TABLE
INSERT 0 2
INSERT 0 2DELETE FROM customers WHERE id = 1;ERROR: 23503: update or delete on table "customers" violates foreign key constraint "orders_customer_id_fkey" on table "orders"
DETAIL: Key (id)=(1) is still referenced from table "orders".
SCHEMA NAME: lab_a
TABLE NAME: orders
CONSTRAINT NAME: orders_customer_id_fkeySELECT id, customer_id, amount FROM orders WHERE customer_id = 1 ORDER BY id; id | customer_id | amount
----+-------------+--------
10 | 1 | 15000
11 | 1 | 8000
(2 rows)DELETE FROM orders WHERE customer_id = 1;DELETE 2DELETE FROM customers WHERE id = 1;DELETE 103부모 없는 행이 있는 테이블에 외래 키 추가
데이터가 있는 테이블에 외래 키를 걸면 기존 행을 전부 검사해요. 직원 3번의 dept_id 30이 departments에 없어서 ALTER TABLE ... ADD CONSTRAINT가 Key (dept_id)=(30) is not present로 실패해요. ALTER TABLE인데도 메시지는 자료 추가, 갱신 작업이라고 나와요.
LEFT JOIN으로 부모 없는 행(Choi, 30)을 찾고, dept_id를 NULL로 바꾸면(NULL은 외래 키 검사 대상이 아님) 제약 조건이 추가돼요.
사전 준비
CREATE TABLE departments (id int PRIMARY KEY, name text);
CREATE TABLE employees (id int PRIMARY KEY, name text, dept_id int);
INSERT INTO departments VALUES (10, 'Sales'), (20, 'IT');
INSERT INTO employees VALUES (1, 'Kim', 10), (2, 'Lee', 20), (3, 'Choi', 30);CREATE TABLE
CREATE TABLE
INSERT 0 2
INSERT 0 3ALTER TABLE employees ADD CONSTRAINT employees_dept_fk FOREIGN KEY (dept_id) REFERENCES departments(id);ERROR: 23503: insert or update on table "employees" violates foreign key constraint "employees_dept_fk"
DETAIL: Key (dept_id)=(30) is not present in table "departments".
SCHEMA NAME: lab_a
TABLE NAME: employees
CONSTRAINT NAME: employees_dept_fkSELECT e.id, e.name, e.dept_id FROM employees e LEFT JOIN departments d ON d.id = e.dept_id WHERE e.dept_id IS NOT NULL AND d.id IS NULL; id | name | dept_id
----+------+---------
3 | Choi | 30
(1 row)UPDATE employees SET dept_id = NULL WHERE dept_id = 30;UPDATE 1ALTER TABLE employees ADD CONSTRAINT employees_dept_fk FOREIGN KEY (dept_id) REFERENCES departments(id);ALTER TABLE04자식이 쓰는 부모 키(상품 코드)를 UPDATE로 변경
상품 코드 A-100을 KB-100으로 바꾸면 "products" 테이블의 자료 갱신, 삭제 작업이 ... 위반했습니다로 실패해요. DELETE가 아니라 UPDATE인데도 같은 메시지이고, DETAIL에 Key (code)=(A-100) is still referenced from table "order_items"가 나와요.
외래 키를 ON UPDATE CASCADE로 다시 만들면 같은 UPDATE가 성공하고(UPDATE 1), 주문 2줄의 코드도 함께 KB-100으로 바뀌어요.
사전 준비
CREATE TABLE products (code text PRIMARY KEY, name text);
CREATE TABLE order_items (id int PRIMARY KEY, product_code text REFERENCES products(code), qty int);
INSERT INTO products VALUES ('A-100', 'Keyboard');
INSERT INTO order_items VALUES (1, 'A-100', 2), (2, 'A-100', 1);CREATE TABLE
CREATE TABLE
INSERT 0 1
INSERT 0 2UPDATE products SET code = 'KB-100' WHERE code = 'A-100';ERROR: 23503: update or delete on table "products" violates foreign key constraint "order_items_product_code_fkey" on table "order_items"
DETAIL: Key (code)=(A-100) is still referenced from table "order_items".
SCHEMA NAME: lab_a
TABLE NAME: order_items
CONSTRAINT NAME: order_items_product_code_fkeySELECT conname, confupdtype, confdeltype FROM pg_constraint WHERE conrelid = 'order_items'::regclass AND contype = 'f'; conname | confupdtype | confdeltype
-------------------------------+-------------+-------------
order_items_product_code_fkey | a | a
(1 row)confupdtype이 a(NO ACTION)예요. 자식이 쓰는 동안에는 부모 키를 바꿀 수 없다는 뜻이에요.
ALTER TABLE order_items DROP CONSTRAINT order_items_product_code_fkey;
ALTER TABLE order_items ADD CONSTRAINT order_items_product_code_fkey FOREIGN KEY (product_code) REFERENCES products(code) ON UPDATE CASCADE;ALTER TABLE
ALTER TABLEUPDATE products SET code = 'KB-100' WHERE code = 'A-100';
SELECT id, product_code, qty FROM order_items ORDER BY id;UPDATE 1
id | product_code | qty
----+--------------+-----
1 | KB-100 | 2
2 | KB-100 | 1
(2 rows)05서로 참조하는 두 테이블(부서장 ↔ 직원 소속 부서)
departments.manager_id는 employees를, employees.dept_id는 departments를 가리켜요. 어느 쪽을 먼저 넣어도 부모가 아직 없어요. 첫 INSERT가 Key (manager_id)=(1) is not present in table "employees"로 실패하고, 나머지는 25P02: current transaction is aborted로 무시된 뒤 COMMIT이 ROLLBACK으로 끝나요.
부서장 외래 키를 DEFERRABLE INITIALLY DEFERRED로 바꾸면 문장마다가 아니라 COMMIT 때 검사해요. 같은 트랜잭션이 커밋되고 부서장 Kim이 조회돼요.
사전 준비
CREATE TABLE departments (id int PRIMARY KEY, name text, manager_id int NOT NULL);
CREATE TABLE employees (id int PRIMARY KEY, name text, dept_id int NOT NULL REFERENCES departments(id));
ALTER TABLE departments ADD CONSTRAINT departments_manager_fk FOREIGN KEY (manager_id) REFERENCES employees(id);CREATE TABLE
CREATE TABLE
ALTER TABLEBEGIN;
INSERT INTO departments VALUES (10, 'Sales', 1);
INSERT INTO employees VALUES (1, 'Kim', 10);
COMMIT;BEGIN
ERROR: 23503: insert or update on table "departments" violates foreign key constraint "departments_manager_fk"
DETAIL: Key (manager_id)=(1) is not present in table "employees".
SCHEMA NAME: lab_a
TABLE NAME: departments
CONSTRAINT NAME: departments_manager_fk
ERROR: 25P02: current transaction is aborted, commands ignored until end of transaction block
ROLLBACKSELECT conname, conrelid::regclass AS table_name, condeferrable, condeferred FROM pg_constraint WHERE contype = 'f' AND conrelid IN ('departments'::regclass, 'employees'::regclass) ORDER BY conname; conname | table_name | condeferrable | condeferred
------------------------+-------------+---------------+-------------
departments_manager_fk | departments | f | f
employees_dept_id_fkey | employees | f | f
(2 rows)두 외래 키 모두 condeferrable이 f예요. INSERT마다 바로 검사하니 어떤 순서로도 넣을 수 없어요.
ALTER TABLE departments ALTER CONSTRAINT departments_manager_fk DEFERRABLE INITIALLY DEFERRED;ALTER TABLEBEGIN;
INSERT INTO departments VALUES (10, 'Sales', 1);
INSERT INTO employees VALUES (1, 'Kim', 10);
COMMIT;
SELECT d.id, d.name, e.name AS manager FROM departments d JOIN employees e ON e.id = d.manager_id;BEGIN
INSERT 0 1
INSERT 0 1
COMMIT
id | name | manager
----+-------+---------
10 | Sales | Kim
(1 row)06가져온 데이터의 코드가 대소문자만 다름(jp와 JP)
외래 키는 값을 정확히 비교해요. CSV 등으로 받은 임시 테이블에서 옮기면 첫 문제 행에서 Key (country_code)=(jp) is not present in table "countries"로 실패하고 한 행도 안 들어가요. countries에는 JP·KR이 있거든요.
임시 테이블 값을 upper()로 바꾸면(UPDATE 2) 같은 INSERT ... SELECT가 3행 모두 들어가요(INSERT 0 3).
사전 준비
CREATE TABLE countries (code char(2) PRIMARY KEY, name text);
CREATE TABLE customers (id int PRIMARY KEY, name text, country_code char(2) REFERENCES countries(code));
INSERT INTO countries VALUES ('KR', 'Korea'), ('JP', 'Japan');
CREATE TABLE import_customers (id int, name text, country_code char(2));
INSERT INTO import_customers VALUES (1, 'Kim', 'KR'), (2, 'Sato', 'jp'), (3, 'Lee', 'kr');CREATE TABLE
CREATE TABLE
INSERT 0 2
CREATE TABLE
INSERT 0 3INSERT INTO customers SELECT id, name, country_code FROM import_customers;ERROR: 23503: insert or update on table "customers" violates foreign key constraint "customers_country_code_fkey"
DETAIL: Key (country_code)=(jp) is not present in table "countries".
SCHEMA NAME: lab_a
TABLE NAME: customers
CONSTRAINT NAME: customers_country_code_fkeySELECT i.id, i.name, i.country_code, c.code AS parent_code
FROM import_customers i LEFT JOIN countries c ON c.code = i.country_code
WHERE c.code IS NULL ORDER BY i.id; id | name | country_code | parent_code
----+------+--------------+-------------
2 | Sato | jp |
3 | Lee | kr |
(2 rows)LEFT JOIN으로 부모 없는 행 2개(jp, kr)가 나와요. JP·KR과 대소문자만 달라요.
UPDATE import_customers SET country_code = upper(country_code) WHERE country_code <> upper(country_code);UPDATE 2INSERT INTO customers SELECT id, name, country_code FROM import_customers;
SELECT id, name, country_code FROM customers ORDER BY id;INSERT 0 3
id | name | country_code
----+------+--------------
1 | Kim | KR
2 | Sato | JP
3 | Lee | KR
(3 rows)자주 묻는 질문
PostgreSQL violates foreign key constraint 해결 방법은?
DETAIL 줄에서 없는 키 값을 보고, 부모 행을 먼저 넣거나 자식 행의 키 값을 고치세요. 데이터를 옮길 때는 부모 테이블부터 넣어요.
is still referenced from table 에러로 삭제가 안 돼요
DETAIL에 나온 테이블에서 그 키를 쓰는 자식 행을 찾아 먼저 지우거나 다른 부모로 바꾸세요. 그다음 부모를 지우면 돼요.
ALTER TABLE로 외래 키 추가할 때 23503이 나요
기존 데이터에 부모 테이블에 없는 값이 있어서예요. LEFT JOIN ... WHERE 부모.id IS NULL로 찾아서 고치거나 NULL로 바꾼 뒤 다시 추가하세요.
서로 참조하는 두 테이블에 데이터를 어떻게 넣나요?
한쪽 외래 키를 DEFERRABLE INITIALLY DEFERRED로 바꾸세요. COMMIT 때 검사하므로 한 트랜잭션 안에서 두 행을 모두 넣을 수 있어요.
기본 키를 UPDATE하면 is still referenced from table이 나와요
자식 행이 예전 키를 쓰고 있고 외래 키가 UPDATE에 대해 NO ACTION이라서예요. ON UPDATE CASCADE로 다시 만들면 자식도 새 키로 함께 바뀌어요.
검증 방법
시나리오마다 새 DB 사용자를 만들어 시작해요. 스크립트가 사전 준비 → 에러 재현(에러 코드 일치 확인) → 해결 → 원래 문장 재실행 순서로 실행하고, 화면의 출력은 DB가 실제로 낸 결과를 스크립트가 그대로 저장한 거예요.
lab_a, lab_b는 테스트용 일반 역할(같은 이름의 스키마 소유), postgres는 슈퍼유저예요. PostgreSQL 17.12