반응형






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/* 
    제약조건 : 데이터 저장 시 저장가능한 조건이 존
    무결성 제약조건 = 컬럼 속성
    NOT NULL : 널값이 입력되지 못하게하는 조건
    UNIQUE : 중복된 값이 입력되지 못하게하는 조건 (NULL값 허용가능)
    PRIMARY KEY : NOT NULL + UNIQUE의 의미
                : 데이터 식별 시 유일성을 가짐
    FOREIGN KEY (외래키) : 다른테이블 칼럼 참조해서 무결성을 검사하는 조건
    CHECK : 주어진값만 허용하는 조건
*/
/* NULL : 데이터가 없음을 의미 */
 
create table null_test(
    col1 varchar2(20not null,
    col2 varchar2(20null,
    col3 varchar2(20
    );
 
 
desc null_test;
 
 
insert into null_test (col1,col2)
values ('aaa','bb');
 
 
select * from null_test;
 
 
/* col1이 not null이므로 에러발생 */
 
insert into null_test (col2,col3)
values ('cc','dd');
 
 
 
/* Unique  */
 
create table unique_test(
    col1 varchar2(20unique not null,
    col2 varchar2(20unique,
    col3 varchar2(20not null,
    col4 varchar2(20not null,
    constraints temp_unique unique(col3,col4)
    );
 
 
 
/* 
    constraints : 강제로 제약을하겠다는 의미
                : col3과 col4을 조합한 값을 unique로 사용하겠다는 의미
                : temp_unique는 unique의 이름
*/
 
 
insert into unique_test (col1,col2,col3,col4)
values ('aa','bb','cc','dd');
 
 
insert into unique_test (col1,col2,col3,col4)
values ('a2','b2','c2','d2');
 
 
select * from unique_test;
 
 
/* 무결성제약조건 위배 : col1의 값은 unique해야하는데 이미 aa가 존재하므로 에러 */
 
update unique_test
set col1 = 'aa'
where col2 = 'b2';
 
 
 
/* Unique는 null을 허용하므로 에러없음 */
 
insert into unique_test (col1,col2,col3,col4)
values ('a3','','c3','d3');
 
 
insert into unique_test( col1,col2,col3,col4)
values ('a4','','c4','d4');
 
 
 
/* Primary Key : 기본키 (null허용하지 않음) */
/* 테이블 생성 시 기본 키 생성방법 */
 
create table primary_test(
    student_id number(10primary key/* 인라인 방식 */
    name varchar2(20)
);
 
 
create table primary_test(
    student_id number(10), 
    name varchar2(20),
    constraints student_pk primary key(student_id) /* 아웃라인 방식 */
);
 
 
/*  
    인라인, 아웃라인 차이
    primary key의 이름을 명시하느냐 오라클에서 자동으로 생성하느냐의 차이
*/
 
desc primary_test;
 
 
/* 테이블 생성 후 기본키 생성방법 */
 
alter table primary_test
add constraints "기본키 이름" primary key(필드명);
 
 
 
/* 
    FOREIGN KEY : 외래키
                : 부모테이블이 존재해야 자식테이블에서 외래키 사용 가능
 */
 
create table foreign_key(
    department_id constraints dept_fk 
    references departments (department_id) /* 인라인 */
    );
 
 
create table foreign_key(
    department_id
    constraints dept_fk 
    foreign key (department_id)
    references departments(department_id) /* 아웃라인 */
    );
 
 
 
/* 테이블을 생성하고 나서 외래키를 지정하는 방법 */
 
alter table foreign_key
add constraints dept_fk foreign key (department_id)
references departments(department_id);
 
 
 
/* 자식테이블에서 사용하지 않은 값은 부모테이블에서 삭제 가능 */
/* Check : 입력값을 체크해서 조건에 해당하지 않으면 입력불가 */
 
create table check_test(
    gender varchar2(10not null
    constraints check_sex check(gender in('M','F'))
    );
 
 
create table check_test(
    gender varchar2(10not null
    constraints check_sex check(gender in('남성','여성'))
    );
 
 
 
/* 체크 제약조건에 위배되므로 에러 */
 
insert into check_test
values('남자');
 
 
insert into check_test
values('여성');
 
 
select * from check_test;
cs



반응형

'프로그래밍 > SQL' 카테고리의 다른 글

[Oracle SQL] Sequence  (0) 2017.08.16
[Oracle SQL] VIEW  (0) 2017.08.16
[Oracle SQL] INSERT, UPDATE, DELETE, COMMIT, ROLLBACK  (0) 2017.08.10
[Oracle SQL] CREATE, ALTER, DROP, TRUNCATE  (0) 2017.08.10
[Oracle SQL] SubQuery 서브쿼리  (0) 2017.08.10
반응형






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/* 
    DML (Data Manipulation Language) : 데이터 조작어
    SELECT문, DELETE문, INSERT문, UPDATE문
    
    --형식--
    SELECT 컬럼명, 컬럼명2,...
    FROM 테이블1, 테이블2,...
    WHERE 조건들
    
    //테이블의 레코드(로우)를 입력
    INSERT INTO 테이블명 (컬럼명1, 컬럼명2, ...)
    VALUES (값1, 값2, ...); 
    
    UPDATE 테이블명 
    SET 컬럼명1 = 값1,
        컬럼명2 = 값2
    WHERE 조건..;
    
    
    //테이블의 레코드(로우)를 삭제
    DELETE (FROM-생략가능)테이블명
    WHERE 조건;   
*/
    
/* 테이블 생성 */
 
create table sample(
    deptNo number(20),
    deptName varchar2(15),
    deploc varchar2(15),
    depManager varchar2(10)
);
 
 
desc sample;
 
 
 
/* 데이터 입력 */
 
insert into sample(deptNo, deptName, deploc, depManager)
values(10'기획실''서울''홍길동');
 
 
select * from sample;
 
 
 
/* 모든 컬럼에 데이터를 넣을 경우 컬럼명 생략가능 */
 
insert into sample
values(20,'전산실','부산','김말동');
 
 
insert into sample
values(30,'영업부','광주',null);
 
 
 
/* 데이터 필드 수정 */
 
update sample set deptNo=50
where deptNo=30;
 
 
update sample set deploc = '인천'
where deptNo = 50;
 
 
 
/* 데이터 삭제 */
 
delete sample 
where deptNo = 50;
 
 
 
/* 테이블 내용 모두 삭제 */
 
delete sample;
 
 
 
/* commit  */
 
insert into sample
values(20,'전산실','부산','김말동');
 
 
insert into sample
values(30,'영업부','광주',null);
 
 
commit;
 
 
 
/* rollback : commit한 시점으로 돌아감*/
 
update sample set deploc = '인천'
where deptNo = 30;
 
 
select * from sample;
 
 
delete sample;
 
 
rollback;
 
select * from sample;
cs


반응형

'프로그래밍 > SQL' 카테고리의 다른 글

[Oracle SQL] VIEW  (0) 2017.08.16
[Oracle SQL] 무결성 제약조건  (0) 2017.08.12
[Oracle SQL] CREATE, ALTER, DROP, TRUNCATE  (0) 2017.08.10
[Oracle SQL] SubQuery 서브쿼리  (0) 2017.08.10
[Oracle SQL] Join  (0) 2017.08.08
반응형






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*  DDL (Data Definition Language) : Creat문, Drop문, Alter문, Truncate문 */
 
/* Create Table */
 
 create table employees2(
    employee_id number(10),
    name varchar2(20),
    salary number(7,2)
 );
 
 
select * from employees2;
 
 
 
/* 같은 테이블을 동일하게 만들 때 */
 
create table employees3 
as
select * from employees2;
 
 
select * from employees3;
 
 
 
/* Alter - add: 테이블 추가 */
 
alter table employees2 add(
    manager_id varchar2(10)
    );
 
 
select * from employees2;
 
 
 
/* Alter - modify : 테이블 수정 */
 
alter table employees2 modify(
    manager_id varchar2(20)
    );
 
 
 
 
/* Alter - drop column : 칼럼 삭제 */
 
alter table employees2 drop column manager_id;
 
 
select * from employees2;
 
 
 
/* 
    문자형 데이터 
    char, varchar, nchar, nvarchar, long 형태 존재
    long은 최대 2GB가능 
 */
 
/* Drop문 : 테이블 구조를 삭제 */
 
drop table employees2;
 
 
select * from employees2;
 
 
/* Rename */
 
Rename employees3 to employees2;
 
 
desc employees3;
desc employees2;
 
/* Truncate : 테이블 내의 모든 레코드 삭제 */
 
truncate table employees2;
 
 
select * from employees2;
cs


반응형
반응형





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/*
 서브쿼리 
    : Main Query에 반대되는 개념
    : 메인쿼리를 구성하는 소단위 쿼리
    : select / insert / delete / update 절에서 모두 사용가능
    : 서브쿼리의 결과 집합을 메인 쿼리가 중간 결과값으로 사용
    : 서브쿼리 자체는 일반 쿼리와 다를 바 없음
 */
 
 select round(avg(salary)) 
 from employees;
 
 
 select employee_id, first_name, last_name
 from employees
 where salary < 6462;
 
 
 /* Where절에서는 집계함수 사용 불가 */
 
 select employee_id, first_name, last_name
 from employees
 where salary < round(avg(salary));
 
 
 
 /* select서브쿼리 문 */
 
 select employee_id, first_name, last_name
 from employees
 where salary < (select round(avg(salary)) 
                 from employees);
 
 
 
 select location_id
 from locations
 where state_province is null;
 
 
 
 select * from departments
 where location_id in ( select location_id
                       from locations
                       where country_id = 'US' );
 
 
 
/* 월급이 가장 적은 사원 */
 
select emp.first_name, emp.last_name, job.job_title, emp.salary
from employees emp, jobs job
where emp.salary = (select min(salary) from employees)
  and emp.job_id = job.job_id;
 
 
 
/* 월급이 가장 많은 사원 */
 
select emp.first_name, emp.last_name, job.job_title, emp.salary
from employees emp, jobs job
where emp.salary = ( select max(salary) from employees)
  and emp.job_id = job.job_id;
  
 
 
/* 평균 급여보다 많이 받는 사원들의 명단 조회 */
 
select emp.first_name, emp.last_name, job.job_title
from employees emp, jobs job
where emp.salary > (select avg(salary) from employees)
  and emp.job_id = job.job_id;
 
 
 
/* any, all */
 
select salary
from employees
where department_id = 20;
 
 
 
/* department_id = 20의 최소 연봉보다 많이 받는 사람 모두 출력 */
 
select employee_id, department_id, salary
from employees 
where salary > any ( select salary
                     from employees
                     where department_id = 20 );
 
 
 
select employee_id, department_id, salary
from employees 
where salary > ( select min(salary)
                 from employees
                 where department_id = 20 );
 
 
 
/* department_id = 20의 최대 연봉보다 많이 받는 사람 모두 출력 */
 
select employee_id, department_id, salary
from employees 
where salary > all ( select salary
                     from employees
                     where department_id = 20 );
 
 
 
select employee_id, department_id, salary
from employees 
where salary > ( select max(salary)
                 from employees
                 where department_id = 20 );
 
 
 
/* department_id = 20의 연봉과 동일하게 받는 사람 모두 출력 */
 
select employee_id, department_id, salary
from employees 
where salary in ( select salary
                 from employees
                 where department_id = 20 );
cs


반응형

'프로그래밍 > SQL' 카테고리의 다른 글

[Oracle SQL] INSERT, UPDATE, DELETE, COMMIT, ROLLBACK  (0) 2017.08.10
[Oracle SQL] CREATE, ALTER, DROP, TRUNCATE  (0) 2017.08.10
[Oracle SQL] Join  (0) 2017.08.08
[Oracle SQL] GROUP BY, HAVING, ROLLUP  (0) 2017.08.08
[Oracle SQL] 날짜함수  (0) 2017.08.06
반응형






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* Inner Join : 일반적 Join */
 
select e.first_name, e.last_name, e.email, d.department_name
from employees e, departments d
where e.department_id = d.department_id;
 
 
 
select emp.first_name, emp.last_name, emp.email, emp.department_id, 
       dep.department_name, job.job_title, loc.city
from employees emp, 
     departments dep,
     jobs job,
     locations loc
where emp.department_id = dep.department_id
  and emp.job_id = job.job_id
  and dep.location_id = loc.location_id
  and loc.city = 'Seattle';
 
 
/* Self Join : 자신의 테이블에서 자신의 칼럼을 Join */
 
select emp1.employee_id, emp1.first_name, emp2.employee_id "상사ID", emp2.first_name "상사 이름"
from employees emp1, employees emp2
where emp1.manager_id = emp2.EMPLOYEE_ID;
 
 
/* 
   Outter Join
   (+) : 두개의 테이블 중 하나의 테이블 컬럼 데이터가 없을 경우 
         ROW가 누락되기 때문에 모든 데이터를 누락없이 출력하기 위해 사용
*/
 
select emp.employee_id, emp.first_name, emp.department_id, dep.department_name, loc.city
from employees emp, departments dep, locations loc
where emp.department_id = dep.department_id (+)
  and dep.location_id = loc.location_id (+);
cs


반응형

'프로그래밍 > SQL' 카테고리의 다른 글

[Oracle SQL] CREATE, ALTER, DROP, TRUNCATE  (0) 2017.08.10
[Oracle SQL] SubQuery 서브쿼리  (0) 2017.08.10
[Oracle SQL] GROUP BY, HAVING, ROLLUP  (0) 2017.08.08
[Oracle SQL] 날짜함수  (0) 2017.08.06
[Oracle SQL] 숫자함수  (0) 2017.08.04
반응형






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* Group by 절 */
 
select distinct(department_id) 
from employees;
 
 
select department_id 
from employees 
group by department_id;
 
 
 
/* 부서 별 급여 합계 */
 
select department_id, sum(salary) 
from employees 
group by department_id;
 
 
 
/* 단일 그룹이 아니므로 에러 */
 
select distinct(department_id), sum(salary) 
from employees; 
 
 
 
/* 부서 별 사원수와 급여 평균 */
 
select department_id, sum(salary), count(salary), avg(salary)
from employees
group by department_id;
 
 
 
/*  부서별 직급별 사원수와 급여 평균 */
 
select department_id, job_id, sum(salary), count(salary), avg(salary)
from employees
group by department_id, job_id
order by department_id, job_id;
 
 
 
select department_id, job_id,
   to_char(sum(salary),'999,999'"총급여",
   to_char(avg(salary),'999,999'"평균급여"
from employees
where department_id = 80
group by department_id, job_id
order by department_id, job_id;
 
 
 
/* 현재 부서 별 사원수 */
 
select department_id, count(*
from employees
where department_id is not null
group by department_id;
 
 
 
/* Where절에서는 집계함수 사용 불가 */
 
select department_id, count(*)
from employees
where department_id is not null
    and count(*< 10
group by department_id;  
 
 
 
/* Having 절 */
 
select department_id, count(*
from employees
where department_id is not null
group by department_id
Having count(*>=10;
 
 
 
/* Rollup : 그룹별 합계 정보를 추가해 보여주는 함수 */
 
select l.city, d.department_name, e.job_id,
  count(*"사원수", sum(e.salary) 총급여
from employees e, departments d, locations l
where e.department_id = d.department_id
  and d.location_id = l.location_id
group by l.city, d.department_name, e.job_id
order by l.city, d.department_name, e.job_id;
 
 
 
select l.city, d.department_name, e.job_id,
  count(*"사원수", sum(e.salary) 총급여
from employees e, departments d, locations l
where e.department_id = d.department_id
    and d.location_id = l.location_id
group by rollup(l.city, d.department_name, e.job_id)
order by l.city, d.department_name, e.job_id;
cs


반응형

'프로그래밍 > SQL' 카테고리의 다른 글

[Oracle SQL] SubQuery 서브쿼리  (0) 2017.08.10
[Oracle SQL] Join  (0) 2017.08.08
[Oracle SQL] 날짜함수  (0) 2017.08.06
[Oracle SQL] 숫자함수  (0) 2017.08.04
[Oracle SQL] 문자 함수  (0) 2017.08.03
반응형






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* 날짜 함수 */
 
/* sysdate()  : 현재날짜 (system의 날짜) */
 
select sysdate 
from dual; 
 
 
 
/* months_between(date1-최근날짜,date2-이전날짜) */
 
select first_name, last_name, months_between(sysdate,hire_date) 
from employees
where department_id = 50/* 두 날짜 사이의 개월수 차이 (고용일부터 현재까지)*/
 
 
 
/* add_months() */
 
select add_months(sysdate, 4-- 개월수를 더함
from dual; 
 
 
 
/* next_day() */
 
select next_day(sysdate,'일요일'-- 다가올 일요일에 해당하는 날짜
from dual; 
 
 
select next_day(sysdate,'월'
from dual; 
 
 
 
/* last_day() */
 
select last_day(sysdate) -- 해당 달의 마지막 일수 
from dual;
 
 
 
/* to_char() */
 
select to_char(sysdate, 'yyyy-mm-dd'-- 문자열 형태로 출력 
from dual; 
 
 
select to_char(sysdate, 'yy/mm/dd')
from dual;
 
 
 
/* to_date() */
 
select to_date('2015/03/03''yyyy/mm/dd'-- 문자열을 날짜형태로 바꿈 
from dual; 
 
 
 
/* nvl() : null값을 다른 데이터로 변경하는 함수 */
 
select first_name, last_name, nvl(commission_pct, 0) commission 
from employees;
 
 
 
/* decode() : switch문의 역할을 하는 함수 */
 
select department_id, decode(department_id, 20'마케팅부'60'IT'90'경영','부서')
from employees;
 
 
/* case() : else if 문과 같은 역할을 하는 함수 */
 
select first_name, department_id
 
    case when department_id = 20 then 'marketing'
         when departmnet_id = 60 then '전산실'
         when department_id = 90 then '경영'
         else 'Others'
         and "부서명"
 
 from employees;
cs


반응형

'프로그래밍 > SQL' 카테고리의 다른 글

[Oracle SQL] Join  (0) 2017.08.08
[Oracle SQL] GROUP BY, HAVING, ROLLUP  (0) 2017.08.08
[Oracle SQL] 숫자함수  (0) 2017.08.04
[Oracle SQL] 문자 함수  (0) 2017.08.03
[Oracle SQL] Select 문 And,OR, NOT, BETWEEN  (0) 2017.07.29
반응형






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/* Number function */
/* 
    dual : 오라클에서 제공되는 dummy table, 테이블이 없을 때 사용 
    all 
    distinct : 중복제거
*/
 
 
/* abs() : 절대값 */
 
select abs(-23
from dual;
 
 
 
/* sign() */
 
select sign(23), sign(-23), sign(0
from dual;
 
 
 
/* round(n1,n2) : 반올림 */
 
select round(0.123), round(0.543), round(0.125
from dual;
 
 
select round(0.123456789,6), round(0.543465,2), round(0.125254,4
from dual;
 
 
 
/* trunc(n1,n2) : 소수점 자르기 */
 
select trunc(1234.1234567) zero 
from dual;
 
 
select trunc(1234.1234567,0
from dual;
 
 
select trunc(1234.1234567,2
from dual;
 
 
select trunc(1234.1234567,-1
from dual;
 
 
 
/* ceil() : 올림 */
 
select ceil(32.8) ceil 
from dual;
 
 
select ceil(32.3) ceil 
from dual;
 
 
 
/* floor() : 내림 */
 
select floor(32.8) floor 
from dual;
 
 
select floor(32.3) floor 
from dual;
 
 
 
/* power(n1,n2) : 제곱 */
 
select power(4,2) power 
from dual;
 
 
 
/* mod(n1,n2) : 나머지 */
select mod(7,4) mod 
from dual;
 
 
/* sqrt() : 제곱근 */
select sqrt(2), sqrt(3
from dual;
cs


반응형

'프로그래밍 > SQL' 카테고리의 다른 글

[Oracle SQL] GROUP BY, HAVING, ROLLUP  (0) 2017.08.08
[Oracle SQL] 날짜함수  (0) 2017.08.06
[Oracle SQL] 문자 함수  (0) 2017.08.03
[Oracle SQL] Select 문 And,OR, NOT, BETWEEN  (0) 2017.07.29
[Oracle SQL] 토드 설치  (0) 2017.07.29

+ Recent posts