Datebase

SQL 문법 - SELECT 문

엘호리스 2018. 1. 24. 10:37

문법


SELECT 컬럼명1, 컬럼명2

[FROM 테이블명]

[WHERE 조회조건]

[GROUP BY 칼럼명]

[ORDER BY 칼럼명 [ASC | DESC]]

[LIMIT offset, 조회 할 행의 수]


조건절


SELECT 컬럼명1, 컬럼명2

[FROM 테이블명]

[WHERE 조건절]


WHERE    salary        >=            500;

WHERE   컬럼명      연산자      비교대상값


SELECT 예제

WHERE 활용
1
2
3
//급여가 400미만이거나 500초과인 사원출력
SELECT * FROM employee
WHERE salary<400 OR salary>500;
cs


DISTINCT 중복처리

1
2
3
4
//중복을 뺀 도시 출력
SELECT DISTINCT Country FROM Customers;
//중복을 뺀 도시 컬럼 갯수 
SELECT COUNT(DISTINCT Country) FROM Customers;
cs


TOP 활용

1
2
3
4
5
6
7
//상위 3개 행값을 출력
SELECT TOP 3 * FROM Customers
WHERE Country='Germany';
//LIMIT 
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;
cs


BETWEEN 활용

1
2
3
//입사일이 2003년도인 사원 출력
SELECT * FROM employee
WHERE hiredate between '2003/01/01' and '2003/12/31';
cs

IN, NOT IN 활용

1
2
3
4
5
6
7
8
9
//커미션이 80,200,300인 사원 출력
SELECT * FROM employee
WHERE commission=80 OR commission=200 OR commission=300;
//IN 연산자를 활용한 예제
SELECT * FROM employee
WHERE commission IN(80,100,200);
//NOT IN 연산자
SELECT * FROM employee
WHERE commission NOT IN(80,100,200);
cs


LIKE 활용

1
2
3
4
5
6
//사원명의 세번째 글자가 '성'이고 뒤에는 뭐든 관계없는 사원 출력
SELECT * FROM employee
WHERE ename LIKE '__성%';
//사원명 중간에 '성'이 들어가는 사원 출력
SELECT * FROM employee
WHERE ename NOT LIKE '__성%';
cs


NULL 조건

1
2
3
4
5
6
//커미션 컬럼이 NULL인 사원 출력
SELECT * FROM employee
WHERE commission IS NULL;
//커미션 컬럼이 NULL이 아닌 사원 출력
SELECT * FROM employee
WHERE commission IS NOT NULL;
cs


ORDER BY 정렬 (ASC : Ascending 오름차순, DESC : Descending 내림차순)

1
2
3
//정렬 방식에 여러 조건 제시
SELECT * FROM employee
ORDER BY salary DESC, ename ASC;
cs


GROUP BY 그룹핑

1
2
3
4
5
//부서별 사원수 내림차순으로 출력
SELECT COUNT(ename), deptno
FROM employee
GROUP BY deptno
ORDER BY COUNT(ename) DESC;
cs




JOIN

이미지 출처 : https://commons.wikimedia.org/wiki/File:SQL_Joins.svg


1
2
3
4
5
6
7
//가장 많이 사용되는 조인의 형태
 
SELECT s.name, s.location_id, l.name AS address, l.distance FROM student AS s
LEFT JOIN location AS l ON s.location_id = l.id;
 
SELECT s.name, s.location_id, l.name AS address, l.distance FROM student AS s
INNER JOIN location AS l ON s.location_id = l.id;
cs



참고 자료

https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

https://www.w3schools.com/sql/default.asp