SQL에서 Triger란?


  • 데이터베이스에서 어떤 이벤트가 발생되었을 때 자동적으로 실행되는 프로시저(procedure)을 의미합니다. 예를들어서 insert, update, delete가 발생했을 때 이것이 계기가 되어 자동적으로 실행되는 프로시저(procedure)를 의미합니다.




trigger 사용법


사용자의 닉네임 변경 이력을 저장하는 트리거


delimiter $$
create trigger log_user_nickname_trigger
before update
-- users 테이블을 대상
on users for each row
begin
    -- old는 update 되기 전의 tuple을 가리킴
    -- 또는 delete된 tuple을 가리킴
    insert into users_log values(old.id, old.nickname, now());
end
$$
delimiter ;




사용자가 마트에서 상품을 구매할 때마다 지금까지 누적된 구매 비용을 구하는 트리거


delimiter $$
create trigger sum_by_prices_trigger
after insert
on buy for each row
begin
    declare total int;

    -- new는 insert된 tuple을 가리킴
    -- 또는 update된 후의 tuple을 가리킴
    declare user_id int default new.user_id;

    select sum(price) into total from buy where user_id = user_id;
    update user_buy_stats set price_sum = total where user_id = user_id;
end
$$
delimiter ;




trigger 사용 시 주의사항


  • 서버 소스 코드에 있지 않고 RDBMS에 등록하여 해당하는 이벤트가 발생되었을 때 자동으로 호출되는 방식이기 때문에 어떤 동작이 일어나는지 파악하기 어렵고 문제가 생겼을 때 대응하기 어렵습니다.

  • 등록한 trigger가 많아지면 trigger에 의해 또 다른 trigger가 호출되는 복잡한 상황이 발생될 수 있습니다.

  • 과도한 trigger 사용은 DB 서버의 CPU 사용률을 증가시켜 부하가 발생될 수 있습니다.




relational data model에서의 용어

 

 

domain

 

  • "set of atomic values"로서 attribute가 가질 수 있는 원자적인 값의 집합을 의미힙니다.




demain name

 

  • domain 이름을 의미합니다.




attribute

 

  • domain이 relation에서 맡은 역할 이름으로서 테이블에서 데이터들의 속성 이름입니다.




tuple

 

  • 각 attribute의 값으로 이루어진 리스트 즉, 테이블에서 하나의 행(row) 입니다.




relation

 

  • tuple들의 집합을 relation을 의미하며 즉, 테이블으로도 불립니다.




relation name

 

  • relation의 이름을 의미합니다.




relation schema

 

  • relation의 구조를 나타내며, relation 이름과 attributes 리스트로 표기됩니다.




degree of a relation

 

  • relation schema에서 attribute의 수를 의미합니다.




relational database

 

  • relational data model에 기반하여 구조화된 database를 의미하며, relational database는 여러 개의 relations로 구성됩니다.




relational database schema

 

  • relation schemas들의 집합과 relations간의 무결성 제약조건(integrity constraints set)으로 구성된 schema를 의미합니다.




relation의 특징

 

  • relation은 중복된 tuple을 가질 수 없습니다.

 

  • relation의 tuple을 식별하기 위해 attribute의 부분 집합을 key로 설정합니다.

 

  • relation에서 tuple의 순서는 중요하지 않습니다. 순서가 바뀐다고하여 relation의 의미가 바뀌지 않기 때문입니다.

 

  • 하나의 relatino에서는 attribute의 이름은 중복돼선 안됩니다. 또한 attribute의 순서도 중요하지 않습니다.

 

  • attribute는 atomic 해야됩니다.




relation의 key의 의미

 

super key

 

  • relation에서 tuple을 unique하게 식별할 수 있는 attributes set을 말합니다. 즉, super 키는 하나의 attribute 또는 여러 개의 attributes가 될 수 있습니다.

 

  • 슈퍼키는 릴레이션을 구성하는 모든 튜플에 대해 유일성을 만족시키지만, 최소성은 만족시키지 못할 수 있습니다. 즉, super key의 attribute 일부를 가지고 튜플을 식별할 수도 있습니다.




candidate key

 

  • 어느 한 attribute라도 제거하면 unique하게 tuples를 식별할 수 없는 super key를 의미합니다. candidate key는 minimal super key로도 불립니다. 즉, candidate key는 유일성과 최소성을 만족하는 key 입니다.




primary key

 

  • relation에서 tuple을 unique하게 식별하기 위해 선택된 candidate key를 의미합니다. 한 relation에서 특정 튜플을 유일하게 식별할 수 있으며 NULL을 가질 수 없습니다.




unique key

 

  • unique key는 primary key가 아닌 candidate key를 의미합니다. 혹은 alternate key라고도 불립니다.




foreign key

 

  • 다른 relation의 primary key를 참조하는 attribute를 말합니다.




constraint(제약 조건)

 

  • relatinoal database의 relations들이 언제나 항상 지켜줘야 하는 제약 사항을 의미힙니다.




implicit contraints

 

  • relational data model 자체가 가지는 constraint를 의미합니다. relation내에서 중복되는 tuple 또는 중복되는 attribute 가질 수 없다는 제약 사항이 있습니다.




schema-based constraints(or explicit constraints)

 

  • 주로 DDL을 통해 schema에 직접 명시할 수 있는 constraints를 의미합니다. 예를들어 제약 사항을 통해서 attribute의 value를 domain에 속한 value로 제한하거나 서로 다른 tuple이 동일한 key 값을 가질 수 없게 하거나 NULL 값을 가질 수 없게 지정할 수 있습니다.




+ Recent posts