본문 바로가기
프로그래밍/SQL

[MySQL] Auto Increment 설정하기

by 김뎀뎀 2023. 2. 24.

sql에서 테이블에 데이터가 추가될 때, 특정 컬럼은 자동으로 1씩 증가되는 설정을 줄 수 있다.

테이블을 생성할 때 컬럼에 Auto Increment 옵션을 주면 된다.

 

fruit라는 테이블을 생성하고, id 컬럼에 auto_increment 옵션을 넣는다

CREATE TABLE fruit (
    id int NOT NULL AUTO_INCREMENT,
    name varchar(12),
    PRIMARY KEY (id)
);

DESC fruit;

 

fruit 테이블에 name 컬럼 데이터만 넣어주면, id는 자동으로 값이 매겨진다.

INSERT INTO fruit (name) VALUES ('apple');
INSERT INTO fruit (name) VALUES ('lemon');
INSERT INTO fruit (name) VALUES ('grape');

select * from fruit;

 

 

※ 참고 : https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=goddlaek&logNo=221005664911