728x90

1. SQL 문장 [암기]

1.1. selection
- table1에서 찾기
1.2. join - 아직
- 관계형 데이터베이스의 특징
- 공유 테이블 양쪽의 열에 대해서 링크를 생성하여 다른 테이블에 저장되어 있는 데이터를 함께 가져오기 위해 사용
2. select 문
SELECT [DISTINCT] { * | column [[AS] alias], ... } FROM table; 구문형식에서 → 조회하고 싶은 테이블명
2.1. 구문형식
- SELECT : 하나 이상의 열을 나열
- DISTINCT : 중복 제거
- * : 모든 열을 선택
- column : 명명된 열을 선택
- AS : 열 별칭 (alias)을 지정
- alias : 선택된 열을 다른 이름으로 변경
- FROM table : 열을 포함하는 테이블을 명시
SQL> SELECT first_name , last_name, salary (특정 컬럼들) FROM employees;
- SQL 문장은 대 소문자를 구별하지 X
- SQL 문장은 한 줄 이상 - 마지막에 ; 찍어줘야 그게 맞춰 실행
- 키워드는 단축하거나 줄을 나누어 쓸 수 X
- 절은 대개 줄을 나누어서 씀
- 탭과 들여쓰기(indent) 는 읽기 쉽게 하기 위해 사용열 선택 (모든 열, 특정 열)
2.1.1. 열 선택 (전체 열, 특정 열)
SQL> SELECT * FROM departments; (전체 열)SQL> SELECT department_name , location_id FROM departments; (특정 열)
SQL> SELECT location_id , department_name FROM departments; (특정 열) - 순서가 바뀌면 바뀐 순서대로 나옴
2.1.2. 기본 표시 형식
- 디폴트 데이터 자리맞춤을 지정
- 날짜(년/월/일)와 문자 데이터는
왼쪽정렬 - 숫자 데이터는 오른쪽 정렬
- 디폴트 열은 대문자로 출력
SQL> SELECT first_name , hire_date , salary FROM employees;
2.1.3. 연산자 [ * / + - ] 우선순위
- 곱하기 나누기 >>> 더하기 빼기
- 같은 우선순위 연산자는 좌측 → 우측
- 괄호는 강제로 계산의 우선순위를 바꾸거나 문장을 명료하게 하기 위해 사용
- 나머지 aka.% 없음 = mod 사용
SQL> SELECT first_name , last_name , salary, salary+salary *0.1 FROM employees;
2.1.4. NULL 정의 = 비어있다
- 이용할 수 없거나 , 지정되지 않았거나 , 알 수 없거나 또는 적용할 수 없는 값
- Null vs 숫자 0 이나 공백과는 다름
SQL> SELECT first_name , department_id , commission_pct FROM employees;
2.1.5. 열 별칭(alias)
- 계산할 때에 유용
- 열 이름 바로 뒤에 둠. 열 이름과 별칭 사이에 키워드 AS(오라클 한정 생략 가능) 를 넣기도 함
- 공백이나 특수문자 또는 대 소문자가 있으며 이중 인용부호 (" ") 필요
SQL> SELECT first_name AS 이름 , salary (as) 급여 FROM employees;SQL> SELECT first_name "Employee Name", salary*12 (as) "Annual Salary" FROM employees;
2.1.6. 리터럴 문자 스트링, 연결 연산자
- 날짜와 문자 리터럴 값은 단일 인용부호 (' ')안
- 숫자 리터럴은 그냥 씀
- ' ' 's ' → 's
그냥 '를 사용하고 싶으면 내부에 ' ' 두번 사용 - 각각의 문자스트링은 리턴된 각 행에 대한 결과
- || : 값을 연결
SQL> SELECT first_name || ' ' || last_name || '''s salary is $' || salary AS "Employee Details" FROM employees;
2.1.7. 중복행, distinct
- DISTINCT : 중복되는 행을 제거
- column 앞에서 사용
SQL> SELECT department_id FROM employees;
SQL> SELECT DISTINCT department_id FROM employees;
2.2. ROWNUM - 중요
- 조회된 순서 (1번부터 순서대로 정렬되는 것 X)
- 쿼리에 의해 반환되는 행의 번호를 출력 = 조회되는 행의 번호를 붙여줌
SQL> SELECT ROWID, ROWNUM, employee_id , first_name FROM employees;
2.3. ROWID
- 데이터베이스에서 행의 주소를 반환
- 주소를 나타내서 쓸일은 X
2.4. 실습
더보기
<sql />
SELECT * FROM employees;
SELECT * FROM departments;
SELECT
employee_id,
first_name,
last_name
FROM employees;
SELECT email, phone_number, hire_date, salary FROM employees;
-- null
SELECT employee_id, commission_pct FROM employees;
-- 연산
SELECT
email,
phone_number,
hire_date,
salary,
salary + salary * 0.5
FROM employees;
-- 엘리어스(별칭)
SELECT
employee_id AS 아이디,
commission_pct AS 커미션,
salary AS 기본급여,
salary + salary * 0.5 AS 급여
FROM employees;
-- 문자열 연결
SELECT first_name || ' ' || last_name || '''s salary is $' || salary AS 결과
FROM employees;
-- distinct 중복제거
SELECT department_id FROM employees;
SELECT DISTINCT department_id FROM employees;
-- rownum(조회되는 행의 번호), rowid(데이터의 주소)
SELECT ROWNUM, ROWID, employee_id FROM employees;
3. 데이터 제한 - 조건절(행)
- 질의에 의해 검색되는 행을 제한
3.1. 선택된 행 제한
FROM 다음 WHERE 절 이용
별칭 사용 불가
condition(s): 열 이름 , 표현식 , 상수, 비교 연산자로 구성

SQL> SELECT first_name , job_id , department_id FROM employees 3 WHERE job_id ='IT_PROG';
3.2. 문자 스트링, 날짜
- 단일 인용부호 (‘ ') 로 둘러싸여 있음
- 문자 값은 대 소문자를 구분 / 날짜 값은 날짜 형식을 구분
- 디폴트 날짜 형식은 'DD MON YY' --?
SQL> SELECT first_name, last_name , hire_date FROM employees 3 WHERE last_name = 'King';
3.3. 비교 연산자
연산자 | 설명 |
= | 같음 |
> | 보다 큼 |
>= | 보다 크거나 같음 |
< | 보다 작음 |
<= | 보다 작거나 같음 |
<> | 같지 않음 |
3.4. BETWEEN + AND 연산자
- 값(숫자)의 범위에 해당하는 행을 출력 ( ~이상 ~이하 )
- 수직선 상에서 만나는 숫자 적기
- 하한 값을 먼저 명시
- 하한 값과 상한 값을 모두 포함
SQL> SELECT first_name , salary FROM employees WHERE salary BETWEEN 10000 AND 12000;
3.5. IN 연산자
- 목록에 있는 값들과 비교 ( 하나부터 ~ 여러개 )
SQL> SELECT employee_id , first_name , salary, manager_id FROM employees WHERE manager_id
IN(101, 102, 103); - 매칭되는 데이터 다 나옴SQL> SELECT first_name , last_name , job_id , department_id FROM employees WHERE job_id
IN('IT_PROG', 'FI_MGR', 'AD_VP'); - 띄어쓰기에 언더바(_) 사용 필수
3.6. LIKE 연산자
- 검색 스트링 값에 대한 와일드카드 검색
포함 되어 있으면 다 찾아줌 - 검색 조건은 리터럴 문자나 숫자를 포함
- %(percent): 문자가 없거나 또는 하나 이상
- _(under score): 하나의 문자, 정확한 위치 나타냄
3.7. IS NULL 연산자
- Null 값을 테스트
- Null이 아닌 컬럼을 검색할 때: IS NOT NULL
3.8. 논리 연산자
- AND: 양쪽의 조건이 참이어야 TRUE 리턴
- OR: 한쪽의 조건이 참이면 TRUE 리턴
NOT: 연산자는 뒤의 조건에 반대되는 결과 리턴- AND가 OR 보다 연산 우선순위가 빠름 - 괄호 사용해서 순서 정함
3.9. 실습
더보기
<sql />
select * from employees;
select first_name, last_name, hire_date from employees
where hire_date = '03/06/17';
-- where
-- job_id = 'IT_PROG'
select employee_id, job_id from employees where job_id = 'IT_PROG';
select * from employees where department_id = 90;
select * from employees where salary >= 12000;
select * from employees where hire_date = '04/10/01'; -- 날짜
select * from employees where hire_date >= '04/10/01'; -- 날짜 부등호 가능
select * from employees where department_id <> 90;
-- between ~ and ~
select * from employees where salary between 15000 and 20000;
-- 입사년도 03
select * from employees where hire_date between '03/01/01' and '03/12/31';
-- in
select * from employees where manager_id in (101, 102, 103, 104);
select first_name, last_name, job_id, department_id from employees where job_id in('IT_PROG', 'FI_MGR', 'AD_VP');
-- like (검색에 활용)
select * from employees where job_id like 'IT%';
select * from employees where job_id like '%PROG';
select * from employees where job_id like '%IT%'; -- IT가 포함된
select * from employees where hire_date like '03%'; -- 03년도로 시작하는
select * from employees where hire_date like '%15'; -- 15일로 끝나는
select * from employees where hire_date like '___05%'; -- 05월로 시작하는 (언더바는 위치)
-- null 데이터 조회
select * from employees where commission_pct = null; -- 조회가 안 됨
select * from employees where commission_pct is null; -- null인 데이터
select * from employees where commission_pct is not null; -- null이 아닌 데이터
-- end, or
select * from employees where job_id = 'IT_PROG' or salary >= 5000;
-- select * from employees where job_id = 'IT_PROG' and salary >= 5000
-- and가 of보다 우선순위
select * from employees where job_id = 'IT_PROG' or job_id = 'FI_MGR' and salary >= 6000;
select * from employees where (job_id = 'IT_PROG' or job_id = 'FI_MGR') and salary >= 6000;
-- 데이터 정렬 (구문의 마지막)
select * from employees order by hire_date asc;
select * from employees order by hire_date desc;
-- job_id = it_prog인 사람들 first_name 기준으로 이름 desc
select * from employees where job_id = 'IT_PROG' order by first_name desc;
-- manager_id가 120 이상인 사람들 중 salary 내림차순
select * from employees where manager_id >= 120 order by salary desc;
-- 여러 컬럼 정렬
select * from employees order by department_id desc, manager_id asc;
-- 엘리어스명 으로 정렬 (안되도 크게 상관X)
select employee_id, salary * 12 as 연봉 from employees order by 연봉 desc;
4. 데이터 정렬
- 원하는 데이터 검색하고 정렬
- SELECT 문장의 가장 뒤 ORDER BY 절
- 질의에 의해 검색되는 행을 정렬
- ASC: 오름차순, 기본값
DESC: 내림차순 - ORDER BY 절에 열 별칭을 사용 가능
SQL> SELECT first_name , salary*12 AS annsal FROM employees ORDER BY annsal;
4.1. 실습
더보기
<sql />
-- 문제
-- 1. 모든 사원의 사원번호 , 이름 , 입사일 , 급여를 출력하세요
select employee_id, first_name, last_name, hire_date, salary from employees ;
-- 2. 모든 사원의 이름과 성을 붙여 출력하세요 . 열 별칭은 name 으로 하세요
select first_name || ' ' || last_name as name from employees;
-- 3. 50 번 부서 사원의 모든 정보를 출력하세요
select * from employees where department_id = 50;
-- 4. 50 번 부서 사원의 이름 , 부서번호 , 직무아이디를 출력하세요
select first_name, last_name, department_id, job_id from employees where department_id = 50;
-- 5. 모든 사원의 이름 , 급여 그리고 300 달러 인상된 급여를 출력하세요
select first_name, last_name, salary, salary + 300 as 인상된급여 from employees;
-- 6. 급여가 10000 보다 큰 사원의 이름과 급여를 출력하세요
select first_name, last_name, salary from employees where salary > 10000;
-- 7. 보너스를 받는 사원의 이름과 직무 , 보너스율을 출력하세요
select first_name, last_name,job_id, commission_pct from employees where commission_pct is not null;
-- 8. 2003 년도 입사한 사원의 이름과 입사일 그리고 급여를 출력하세요 .(BETWEEN 연산자 사용)
select first_name, last_name, hire_date, salary from employees where hire_date between '03/01/01' and '03/12/31';
-- 9. 2003 년도 입사한 사원의 이름과 입사일 그리고 급여를 출력하세요 .(LIKE 연산자 사용)
select first_name, last_name, hire_date, salary from employees where hire_date like '03%';
-- 10. 모든 사원의 이름과 급여를 급여가 많은 사원부터 적은 사원순서로 출력하세요
select first_name, last_name, salary from employees order by salary desc;
-- 11. 위 질의를 60 번 부서의 사원에 대해서만 질의하세요 . 컬럼 : department_id
select first_name, last_name, salary from employees where department_id = 60 order by salary desc;
-- 12. 직무아이디가 IT_PROG 이거나 , SA_MAN 인 사원의 이름과 직무아이디를 출력하세요
select first_name, last_name, job_id from employees where job_id = 'IT_PROG' or job_id = 'SA_MAN'; -- or 사용
select first_name, last_name, job_id from employees where job_id in ('IT_PROG', 'SA_MAN'); -- in 사용
-- 13. Steven King 사원의 정보를 “Steven King 사원의 급여는 24000 달러 입니다 ” 형식으로 출력하세요
select first_name || ' ' || last_name || ' 사원의 급여는 ' || salary || ' 달러 입니다' as info -- as info 사용
from employees
where first_name = 'Steven' and last_name = 'King';
-- 14. 매니저 ( 직무에 해당하는 사원의 이름과 직무아이디를 출력하세요 . 컬럼 job_id
select first_name, last_name, job_id from employees where manager_id is not null; -- 틀림
select first_name, last_name, job_id from employees where job_id like '%MAN';
-- 15. 매니저 ( 직무에 해당하는 사원의 이름과 직무아이디를 직무아이디 순서대로 출력하세요
select first_name, last_name, job_id from employees where manager_id is not null order by job_id asc; -- 틀림
select first_name, last_name, job_id from employees where job_id like '%MAN' order by job_id asc;
오늘 하루
더보기
기억에 남는 부분
- 데이터 제한 시키는 where 절
- 데이터 정렬시키는 order 절
어려운 부분
- 암기 부분인 점 빼고는 딱히 없음
문제 해결 부분
- where 에서 in이나 or 사용해서 풀 수 있음
728x90
'프로그래밍 언어 > SQL-Oracle' 카테고리의 다른 글
[SQL] DML 데이터조작어(insert, update, delete, merge, ctas), TCL(트랜잭션) (0) | 2022.11.15 |
---|---|
[SQL] 서브쿼리(단일행, 다중행, 스칼라), 인라인뷰, rownum (0) | 2022.11.11 |
[SQL] 그룹함수 count(~별!), Join (inner,outer,cross,self) (0) | 2022.11.10 |
[SQL] SQL 함수 (문자, 숫자, 날짜, 형변환, 집합, 분석) (0) | 2022.11.09 |
[SQL] RDBMS 데이터베이스, oracle SQL developer (0) | 2022.11.08 |