bard@mac: ~$ psql
psql (14.7 ...)
postgres=#
새로운 유저 생성
postgres=> CREATE USER bard with encrypted password 'changethis';
DB 생성 및 권한 부여
postgres=> CREATE DATABASE bard;
postgres=> GRANT ALL PRIVILEGES on database bard TO bard;
bard@mac: ~$ psql -h localhost -U bard
Password for user bard: changethis
psql (14.7 (…))
SSL connection (protocol: TLSv1.3, …)
Type "help" for help.
bard=>
psql Command Line options-d name, --dbname name : 데이터베이스 이름-c sql, --command sql : sql 명령 실행psql Meta commands\l: 존재하는 데이터베이스 리스트\c db_name: 해당 db에 연결\d: 모든 테이블 보여줌\d table: 그 테이블에 대한 정보 보여줌\i file_name: 해당 파일을 읽어서 query buffer에 입력\q: 종료\! command: Linux 커맨드 실행Fluffy Harold cat f 1993-02-04 \N
Claws Gwen cat m 1994-03-17 \N
Buffy Harold dog f 1989-05-13 \N
Fang Benny dog m 1990-08-27 \N
Bowser Diane dog m 1979-08-31 1995-07-29
Chirpy Gwen bird f 1998-09-11 \N
Whistler Gwen bird \N 1997-12-09 \N
Slim Benny snake m 1996-04-29 \N
이 txt 파일을 입력하려면:
bard => COPY myTable FROM 'pet.txt' (FORMAT CSV, DELIMITER('\t'));
char(n) : n 고정 길이 문자열varchar(n): 최대 n 가변 길이 문자열int: 정수smallint: 작은 정수numeric(p,d): 고정소수점 실수real: 부동소수점 실수float(n): 최소 n개 숫자를 갖는 부동소수점 소수create table instructor (
ID char(5),
name varchar(20) not null,
dept_name varchar(20),
salary numeric(8,2));
not nullprimary key (A1, ..., An)foreign key (A1, ..., An) references r예)
create table instructor (
ID char(5),
name varchar(20) not null,
dept_name varchar(20),
salary numeric(8,2),
primary key (ID),
foreign key (dept_name) references department)
primary key는 자동으로 not null
drop table student: 테이블 스키마와 내용을 날려버림delete table student : 테이블 내용만 날림(DML)alter tablealter table r add A Dalter table r drop Aselect A1, A2, ... An
from r1, r2, ..., rm
where P
distinct 키워드를 select다음에 써줘야함select distinct dept_name
from instructor
select *
from instructor
+, -, *, /를 혀용함select ID, name, salary/12
from instructor
and, or, not)<, >, =, ...)select name
from instructor
where dept_name = 'Comp. Sci.'
and salary > 80000
select *
from instructor, teaches
select name, course_id
from instructor, teaches
where instructor.ID = teaches.ID
select section.course_id, semester, year, title
from section, course
where section.course_id = course.course_id
and dept_name = 'Comp. Sci.'

natural join은 공통되는 열을 딱 한 세트만 유지함
select *
from instructor
natural join teaches;


select name, title
from instructor
natural join teaches
natural join course;
select name, title
from instructor
natural join teaches, course
where teaches.course_id = course.course_id;
select ID, name, salary/12 as monthly_salary
from instructor
select ID, name, salary/12 monthly_salary
from instructor
=, like% - 어떤 부분문자열이든 가능_ - 문자 한개dar이 들어가는 instructor들의 이름을 출력select name
from instructor
where name like '%dar%'
where percentage like '100\%' escape '\'
||)UPPER(), LOWER()LENGTH(), SUBSTRING(str, position, length)select name
from instructor
order by name
betweenselect name
from instructor
where salary between 90000 and 100000
select name, course_id
from instructor, teaches
where (instructor.ID, dept_name) = (teaches.ID, ’Biology’);
union, intersect, exceptunion all, intersect all, except all(select c_id
from course
where semester = 'Fall' and year = 2024)
union
(select c_id
from course
where semester = 'Spring' and year = 2025)
is null로 null checkselect name
from instructor
where salary is null
null과의 비교연산은 항상 unknown을 반환함5 < null, null <> null, null = nullunknown을 추가함(unknown or true) = true(unknown or false) = unknown(unknown or unknown) = unknown(unknown and true) = unknown(unknown and false) = false(unknown and unknown) = unknown(not unknown) = unknownP is unknown은 P가 unknown일때만 trueunknown의 결과는 false로 처리select avg(salary)
from instructor
where dept_name= 'Comp. Sci.';
select count(distinct ID)
from teaches
where semester = 'Spring'
and year = 2014
select count(*)
from course;

select dept_name, avg(salary)
from instructor
group by dept_name;

group by 뒤에도 있어야 함./* erroneous query */
select dept_name, ID, avg(salary)
from instructor
group by dept_name;
select dept_name, avg(salary)
from instructor
group by dept_name
having avg(salary) > 42000;
select sum(salary), avg(salary)
from instructor

count(*)를 제외한 operation들은 null이 있는 tuple을 무시함set membership test(in, not in)
set comparison (some, all)
set cardinality
Find IDs of students who take DB class
select student_id
from Take
where course_id IN
(select course_id
from Course
where title = 'DB')
select student_name
from Student
where student_id NOT IN
(select student_id
from Take
where course_id IN
(select course_id
from Course
where title = 'DB'))
select count(distinct ID)
from takes
where c_id IN
(select course_id
from teaches
where teaches.ID = 10101);
select distinct T.name
from instructor as T, instructor as S
where T.salary > S.salary
and S.dept_name = 'Biology';
이건 some 문을 이용해서 다음과 같이 쓸 수 있음
select name
from instructor
where salary > some
(select salary
from instructor
where dept_name = 'Biology');
select name
from instructor
where salary > all
(select salary
from instructor
where dept_name = 'Biology');
select distinct name
from Student s
where exists
(select 1
from Take t
where t.ID = s.ID);
select distinct S.ID, S.name
from student as S
where not exists
((select course_id
from course
where dept_name = 'Biology')
except
(select T.course_id
from takes as T
where S.ID = T.ID));
select T.course_id
from course as T
where unique
(select R.course_id
from section as R
where T.course_id = R.course_id
and R.year = 2009);
select dept_name, avg_salary
from (select dept_name,
avg(salary) as avg_salary
from instructor
group by dept_name)
where avg_salary > 42000;
with max_budget(value) as
(select max(budget)
from department)
select budget
from department, max_budget
where department.budget = max_budget.value;
with dept_total(dept_name, value) as
(select dept_name, sum(salary)
from instructor
group by dept_name),
dept_total_avg(value) as
(select avg(value)
from dept_total)
select dept_name
from dept_total, dept_total_avg
where dept_total.value >= dept_total_avg.value;
select dept_name,
(select count(*)
from instructor
where department.dept_name = instructor.dept_name) as num_instructors
from department;
delete from instructor
delete from instructor
where dept_name = 'Finance';
delete from instructor
where dept_name in
(select dept_name
from department
where building = 'Watson');
delete from instructor
where salary <
(select avg(salary)
from instructor);
위 케이스에서 tuple을 삭제할때마다 평균 salary가 변화하게됨.
SQL은 이를 해결하기 위해
- 우선 avg salary를 사용해서 삭제할 모든 tuple을 검색하고
- 그 이후에 위에서 찾은 tuple을 제거함
insert into course
values ('CS-437', 'Database Systems', 'Comp. Sci.', 4);
이는 아래와 동치
insert into course (course_id, title, dept_name, credits)
values ('CS-437', 'Database Systems', 'Comp. Sci.', 4);
insert into student
select ID, name, dept_name, 0
from instructor
update instructor
set salary = salary * 1.03
where salary > 100000;
update instructor
set salary = salary * 1.05
where salary <= 100000;
update instructor
set salary = case
when salary <= 100000 then salary * 1.05
else salary * 1.03
end
update student S
set tot_cred =
(select sum(credits)
from takes
natural join course
where S.ID = takes.ID
and takes.grade <> 'F'
and takes.grade is not null);
update student S
set tot_cred =
(select case
when sum(credits) is not null then sum(credits)
else 0
end
from takes
natural join course
where S.ID = takes.ID
and takes.grade <> 'F'
and takes.grade is not null);