Endless Motivation

SQL 기본 쿼리 정리 본문

IT/Web & DB

SQL 기본 쿼리 정리

Renesys 2016. 9. 26. 07:47

- DB directory 생성

Create database <dir_name>;


- Directory 사용

use <dir_name>;




- 테이블 생성

create table <table_name>(

<col_name> <data type> <defalut> [not null],

<col_name> <data type> <defalut> [not null],

......

constraint <PK_name> primary key(<col_name>),

constraint <FK_name> foreign key(<col_name>) references <table_name>(<col_name>)

);


- select를 사용한 테이블 생성(기존 테이블에서 컬럼별로 가져오기)

create table <new_table_name> as select <col_name> from <table_name>;


- 테이블 이름 변경

rename table <src_table> to <dest_table>;


- 테이블 구조 확인

desc <table_name>;


- 테이블 내 전체 컬럼(Attribute) 검색

show full columns from <table_name>;


- 테이블 내 컬럼 추가

alter table <table_name> add <col_name> <data type>;


- 테이블 내 컬럼 삭제

alter table <table_name> drop <col_name> <data type>;


- 태이블 내 컬럼 수정

alter table <table_name> modify(

<col1_name> <data type> <default> [not null],

<col2_name> <data type> <default> [not null]

);


- 테이블 생성&복사

create table <dest_table_name> select * from <src_table_name>;


- 테이블 복사

insert into <dest_table_name> select * from <src_table_name>;


- 다른 DB에서 테이블 복사

insert into <dest_DB_name>.<dest_table_name> select * from <src_DB_name>.<src_table_name>;


- 테이블 삭제

drop table <table_name> [cascade constraint];




- 테이블 PK 지정

alter table <table_name> add primary key(<col1>, <col2>, ....);


- 테이블 PK 삭제

alter table <table_name> drop primary key;


- 테이블 FK 지정

alter table <table_name> add foreign key(<col>) references <parent_table>(<PK_col>) [on delete/update cascade];


- 테이블 내 중복 투플 제거

create table <table_name> select from <table_name> group by <col_name>;



- 기본 검색문

select <col_name> from <table_name> where <col_name>=<value>;


- 기본 삭제문

delete from <table_name> where <col_name>=<value>;


- 기본 삽입문

insert into <table_name> values(<value1>, <value2>, ...);




Comments