/*
Table : colun(항목, 열), row(행)로 이루어져 있다
데이터를 담을 수 있는 틀
< data 자료형 >
string : varchar (byte) -> 한글자당 1바이트씩 들어간다 / character varing
integer :int, integer, numeric (자리수) -> ex)만 단위의 경우 5라고 적으면 된다 //numeric의 경우 오라클 가면 numberic이 된다
double, float : numeric(정수의 자리수, 소수점) ->ex) 5.2 = 10000.12
calender : date,tinestamp // 둘의 차이 : 날짜, 시간 +날짜
<object 설정시 ->
object : creat drop alter(tnwjd) // (table, view) //(table, view) -> (실제테이블, 가상테이블)
table
view
sequence
--------------
< date 설정>
insert delete select update
<table> 추가 시
1. tool 사용하는 방법
2. 쿼리문 사용하는 방법 : 사용률 높음
*/
----tool로 테이블 생성 완료
-- 자료 넣기
--insert
insert into tb_test(num,name,address,birth)
values (1,'홍길동', '부평구','2002-10-12');
select * from tb_test;
-- 테이블 삭제
drop table tb_test;
--쿼리문으로 테이블 생성하는 법
CREATE table tb_test(
num int, --qjsgh
name varchar(30),
address varchar(45),
birth timestamp DEFAULT now()
);
--데이터 넣기
/*
--insert 형식 : insert into 테이블명 (칼럼명, ...)
values(값1, ...)
*/
insert into tb_test(num,name,address,birth)
values (1,'홍길동', '부평구','2002-10-12');
insert into tb_test(num,name,address,birth)
values (2,'성춘향', '부평구',now());
insert into tb_test(num,name,address)
values (3,'일지매', '원주시');
select * from tb_test;
--이렇게 적어도 success 확인 가능
--왜? 칼럼명은 생략이 가능하기 때문이다
insert into tb_test
values (4,'홍두께', '인천시');
select * from tb_test;
--단, 아래의 경우는 에러에러
--왜? 칼럼명의 순서와 다르게 적었기 때문
--해결방법 테이블 이름 옆에 칼럼명을 같은 자료형의 순서대로 적어줄 것
insert into tb_test
values (4,'홍두께2 ', '인천시');
--이렇게 사용했는데 성공하는 이유
--컬럼명을 바꾸어도 값만 제대로 적어준다면 에러 안 난다
insert into tb_test(address,birth,num,name)
values ('춘천시', '2000-08-23', 5,'이몽룡');
--데이터 잘 들어갔는지 확인하기
select * from tb_test;
--데이터 삭제
/*
--delete 삭제
delete from 테이블명
where 조건식식
*/
--성춘향 지워보기
DELETE from tb_test
where num = 2;
--성춘향 지워졌는지 확인하기
select * from tb_test;
--num이 그리고 주소가 '인천시'인 사람 삭제하기
DELETE from tb_test
where num = 4 and address = '인천시';
--지워졌는지 확인하기
select * from tb_test;
--수정하기
/*
--update
UPDATE 테이블명
SET 수정하고 싶은 값의 식
where 조건식
*/
--이몽룡 주소 남원시로 수정
UPDATE tb_test
set address = '남원시'
WHere name = '이몽룡';
--수정확인
select * from tb_test;
--데이터 한 번에 수정하기
--조건 여러 조건 넣을 수 있다
UPDATE tb_test
set address = '인천시',birth = '2000-10-10'
WHere num = 1;
--수정확인
--수정된 건 제일 아래에 온다
select * from tb_test;
--남원시에 해당하는 사람들을 서울시로 수정하기
UPDATE tb_test
set address = '서울시'
where address = '남원시';
-- 데이터를 포함해서 테이블을 복사하는 방법
--table copy
CREATE TABLE tb_emp
as
select *
from employees;
--테이블 tb_emp 를 만들어라
--직원테이블로부터 데이터를 가져와서
--emp 테이블에 직원테이블 정보 복붙 되었는지 확인하기
select * from tb_emp;
--emp 테이블에 홍길동 정보 추가하기
INSERT INTO tb_emp(employee_id, first_name, last_name,email,phone_number, hire_date, job_id,
salary, commission_pct, manager_id,department_id)
values ( 300, '길동','홍','hgd@naver.com', '02.123.4567',
now(),'IT_PROG',20000,0.3,100,60);
--홍길동 삽입 확인
select * from tb_emp;
create table tb_jobs
as
select job_id as jid,job_title as jtitle ,min_salary, max_salary
from jobs;
--컬럼명이 마음에 들지 않아서 재정의하고 싶을 때
-- slect 에서 as 이용해서 재정의
create table tb_jobs
as
select job_id as jid, job_title as jtitle ,min_salary as minsal, max_salary as maxsal
from jobs;
select * from tb_jobs;
--join이 된 테이블을 생성하고 싶은 경우
create table emp_dept
as
select e.employee_id as empno, first_name as name,
salary as sal, e.department_id as deptno,
d.department_name as deptname,
d.location_id as locno
from employees e , departments d
where e.department_id = d.department_id;
select * from emp_dept;
--그룹으로 통계를 사원정보와 같이 검색하고 싶은 경우
create table group_dept
as
select department_id,count(*) as dcount, sum(salary) as dsum, avg(salary) as davg
from employees
group by department_id;
select e.employee_id, e.first_name, e.department_id, gd.dsum, round(gd.davg)
from employees e, group_dept gd
where e.department_id = gd.department_id;
--tb_jobs 테이블 지우기
drop table tb_jobs;
--데이터 미포함해서 테이블 복붙
-- table copy : 데이터 미포함
create table tb_jobs
as
select *
from jobs
where 1 = 2;
--where 1 = 2 처럼 성립되지 않는 조건을 달아줄 경우 데이터를 가져오지 않고 테이블 껍데기만 가져온다
select * from tb_jobs; -- 자료 없이 칼럼명만 출력 확인
--table 수정
--테이블명 수정
alter table tb_jobs
rename to new_jobs;
--컬럼 추가 (1개)
alter table new_jobs
add
abg_sal integer;
select*from new_jobs;
--컬럼 추가 (2개)
alter table new_jobs
add new_col1 numeric(3,1),
add new_col2 varchar(30);
select*from new_jobs;
--컬럼의 데이터형을 수정하고자 할 때
--자료형=데이터형이 버쳐에서 타임스탬프로 수정되었다
alter table new_jobs
alter column new_col2
type timestamp
USING new_col2::timestamp without time zone;
SELECT*from new_jobs;
--컬럼을 테이블에서 삭제 하고 싶을 때
alter table new_jobs --삭제도 변경에 해당하니 alter 사용
drop column new_col1; --drop column 구문 작성성
SELECT*from new_jobs;
-- 문제1) EMPLOYEES 테이블에서 부서별로 인원수,평균 급여,급여의 합,최소 급여,최대 급여를 포함하는
-- EMP_DEPTNO 테이블을 생성하라.
drop table emp_deptno;
create table emp_deptno
as
select department_id as deptno, count(employee_id) as cnt,
round(avg(salary), 1) as salavg, sum(salary) as salsum,
max(salary) as salmax
from employees
where department_id is not null
group by department_id
order by department_id asc;
select * from emp_deptno;
-- 문제2) EMP_DEPTNO 테이블에 ETC COLUMN을 추가하라.
-- 단 자료형은 VARCHAR(50) 사용하라.
alter table emp_deptno
add
etc varchar(50);
-- 문제3) EMP_DEPTNO 테이블에 ETC COLUMN을 수정하라.
-- 자료 형은 VARCHAR(15)로 하라.
alter table emp_deptno
alter column
etc type varchar(15);
-- 문제4) EMP_DEPTNO 테이블에 있는 ETC 을 삭제하고 확인하라.
alter table emp_deptno
drop etc;
select * from emp_deptno;
-- 문제5) 위에 생성한 EMP_DEPTNO 테이블의 이름을 EMP_DEPT로 변경하라.
drop table emp_dept;
alter table emp_deptno
rename to emp_dept;
-- 문제6) EMP_DEPT 테이블을 삭제하라.
drop table emp_dept;
-- 문제7) EMPLOYEES 테이블을 EMP 테이블을 생성하고 복제하도록 하라.
-- (데이터 포함)
-- "사원번호", "이름", "월급", "부서번호", "부서명", "부서월급순위"
drop table emp;
create table emp
as
select e.employee_id, e.first_name, e.salary,
e.department_id, d.department_name,
row_number()over(partition by e.department_id order by e.salary desc) as depttop
from employees e, departments d
where e.department_id = d.department_id;
select * from emp;
-- 문제8) EMP 테이블에 row를 추가해 봅니다.
-- 다만, 반드시 데이터를 기입을 안해도 되면, NULL로 설정하도록 한다.
insert into emp(employee_id, first_name, salary, department_id, department_name)
values(301, '춘향', 16000, 300, '인사부');
-- 문제9) EMPLOYEES 테이블에서 EMPNO, ENAME, SAL, HIREDATE, DEPARTMENT_ID의 COLUMN만 선택하여
-- EMP_10 테이블을 생성(데이터 미포함)합시다.
create table emp_10
as
select employee_id as EMPNO, first_name as ENAME, salary as SAL, hire_date as HIREDATE, department_id as DEPTNO
from employees
where 2=1;
select * from emp_10;
-- 문제10) 50번 부서만 선택하여 이에 대응하는 값을 EMP_10 테이블에 추가하라.
insert into emp_10
select employee_id as EMPNO, first_name as ENAME, salary as SAL, hire_date as HIREDATE, department_id as DEPTNO
from employees
where department_id = 50;
'PostgresSQL > PostgresSQL 개념정리' 카테고리의 다른 글
| Join (0) | 2026.06.15 |
|---|---|
| from (0) | 2026.06.12 |
| oder by , group by, group function, having sum (0) | 2026.06.12 |
| where (0) | 2026.06.12 |
| [standard function] 문자, 숫자, 날짜, 문자 <->날짜, 원하는 형식, 지정값 대체 (0) | 2026.06.10 |