본문 바로가기
언어/SQL

[postgreSQL] 사용자, DB, schema, table 생성 및 문법

by 코딩맛집 2024. 5. 20.

1. 사용자 생성

create user {user_id} password {pw} {superuser/nosuperuser};

 

2. DB 생성

create database {local_db} owner {user_id};

User_id 계정으로 DB 오너 만들기.

 

3. Schema 생성

create schema {local_schema};

 

4. Table 생성

create table {local_schema}.{table_name}
(
	id Integer primary key,
    type Varchar(50) not null,
    reg_date Timestamp not null,
    start_time Timestamp,
    end_time Timestamp
    constraint start_end check(start_time < end_time)
);
commit;

// 제약조건 정의는 constrain 키워드로 시작한다.
// 확인 제약조건 정의는 check 키워드와 ()로 묶인 표현식으로 구성된다. 시작 시간이 끝나느 시간 이전인지 확인하는 제약 조건.

 

5. 테이블 생성시 컬럼의 제약 조건

NOT NULL : null값이 저장될 수 없다. 

UNIQUE : 테이블 내에 유일한 값이어야 한다.
PRIMARY KEY : 테이블 내에 유일한 값이어야하고 null값이 저장될 수없다.

CHECK : 지정하는 조건에 맞는 값이 들어가야 한다.

REFERENCES : 참조하는 테이블의 특정 컬럼에 값이 존재해야 한다.

 

5. 문법

// 조회
select * from {table};

// insert - 1. 모든 컬럼에 insert할 때
insert into {table} values({값1}, {값2});
// insert - 2. 특정 컬럼에 insert할 때
insert into {table} ({col_1}, {col_2}) values({val_1}, {val_2});

// update
update {table} set {col} = {val};

// delete
delete from {table};


commit;