SQL

[SQL] DML

wwxs 2024. 9. 25. 11:33

DML (Data Manipulation Language)

  • 데이터 관리 언어
  • 데이터를 삽입, 조회, 수정, 삭제 기능 (CRUD)

 

1. 데이터 삽입 (INSERT)

  • 테이블에 행 데이터(레코드)를 입력하는 키워드
  • insert into 테이블명 (열1, 열2,...) values (값1, 값2, ...);
  • 열 이름을 생략할 경우 values 키워드 뒤 값들의 순서는 테이블 정의 시 지정한 열의 순서 & 개수와 동일
더보기
create database `company`;
use `company`;

create table `example01` (
	name varchar(100),
    age int,
    major varchar(100)
);

# 1) 컬럼명 지정 X
insert into `example01`	
values ('서호영', 23, '전공 A');

# 2) 컬럼명 지정 O
insert into `example01`	(name, major, age)
values ('최윤성', '전공 B', 28);

 

cf) 데이터 삽입 시 데이터 값 입력을 하지 않은 경우

  • Null 허용 - 자동 Null값 지정
  • NOT NULL 지정 - 오류

 

cf) auto_increment

  • 열을 정의할 때 1부터 1씩 증가하는 값을 입력
  • insert에서는 해당 열이 없다고 가정하고 입력
  • 해당 컬럼은 반드시 PK키로 지정되어야 한다 - 하나의 테이블 당 하나만 지정 가능
더보기
create table `example02` (
	-- 컬럼명 데이터타입 PRIMARY KEY auto_increment
    id int auto_increment primary key,
    name varchar(100)
);

insert into `example02`
values 
	(null, '박찬우'),
	(null, '최윤성'),
	(null, '권세혁'),
	(null, '황현지');
    
select * from `example02`;

# cf) auto_increment 최대값 확인
select max(id) from `example02`;

# cf) 시작 값 변경
alter table `example02` auto_increment=100;
insert into `example02`
values (null, '지수민');

select * from `example02`;

# cf) 다른 테이블의 데이터를 한번에 입력하는 구문
# insert into 테이블명
# select ~~

create table `example03` (
	id int,
    name varchar(100)
);

insert into `example03`
select * from `example02`;
-- >> 데이터를 받을 테이블과 전달할 테이블의 컬럼 비교가 필수!

select * from `example03`;

 

2. 데이터 수정 (UPDATE)

  • 테이블의 내용을 수정하기 위한 키워드
  • update 테이블명 set 열1=값1, 열2=값2, ... (where 조건);
더보기
select * from `example02`;

update `example02`
set name='선하영';

select * from `example03`;

-- safe update mode를 해제하는 코드
set sql_safe_updates=0;

-- safe update mode를 설정하는 코드
set sql_safe_updates=1;

update `example03`
set name='장지민'
where mod(id, 2)=1;
-- mod(a, b)함수: 나눗셈에 대한 함수
-- 위 코드에서는 id의 값을 2로 나눈 값이 1인지 여부를 확인 

select * from `example03`;

 

cf) 여러 컬럼의 값을 한번에 설정하는 경우 콤마(,)로 분리하여 나열

 

3. 데이터 삭제 (DELETE)

  • 테이블의 데이터를 삭제하기 위한 키워드
  • delete from 테이블명 (where 조건);
더보기
delete from example03;
select * from example03;

insert into example02
value (null, '정수은');

select * from example02;

delete from example02
where name='선하영';

 

cf) delete VS drop VS truncate

더보기

공통점

  • 삭제를 담당하는 키워드

차이점

  • 1) delete (DML) : 테이블의 틀은 남기면서 데이터를 삭제 → 적은 용량의 데이터 | 조건이 필요한 데이터
  • 2) drop (DDL) : 테이블 자체를 삭제
  • 3) truncate(DDL): 테이블의 틀은 남기면서 데이터를 삭제 → 대용량의 데이터
-- 대용량 테이블의 생성
create table `big1` (select * from `world`.`city`, `sakila`.`country`);
create table `big2` (select * from `world`.`city`, `sakila`.`country`);
create table `big3` (select * from `world`.`city`, `sakila`.`country`);

delete from big1; -- 2.266초 (가장 느림)
select * from big1; -- 테이블 형식은 남아있음

drop table big2; -- 0.031초 (가장 빠름)
# select * from big2; -- 테이블 자체가 삭제되었기 때문에 실행 X

truncate table big3; -- 0.031초
select * from big3; -- 테이블 형식은 남아있음