order by
-- salary를 기준으로 오름 차순 정렬 default는 오름 차순
select * from employee order by salary;
-- salary를 기준으로 내림 차순 정렬
select * from employee order by salary desc;
-- dept_id 별로 오름 차순 정렬 후 salary 기준으로 내림 차순 정렬
select * from employee order by dept_id, salary desc;
- 조회 결과를 특정 attribute 기준으로 정렬하여 가져오고 싶을 때 사용합니다.
- 오름차순 정렬은 ASC로 표기합니다.
- 내림 차순 정렬은 DESC로 표기합니다.
- order by의 default 정렬 방식은 오름차순
aggregate function
-- 전체 employee 수
-- count(*)은 전체 튜플의 개수를 구할 때 사용합니다.
select count(*) from employee;
-- 직원 수, 최대 연봉, 최소 연봉, 연봉 평균
select count(*), max(salary), min(salary), avg(salary) from employee;
- 여러 tuple들의 정보를 요약해서 하나의 값으로 추출하는 함수입니다.
- 대표적으로 count, sum, max, min, avg 함수가 있습니다.
- null 값들은 제외하고 요약 값을 추출합니다.
group by
select position, count(*), max(salary), min(salary), avg(salary) from employee group by position;
- 관심있는 attribute를 기준으로 그룹을 나눠서 그룹별로 aggregate function을 적용하고 싶을 때 사용합니다.
- grouping attribute는 여러개가 될 수 있습니다.
- grouping attribute에 null 값이 있을 때는 null 값을 가지는 tuple끼리 묶입니다.
having
select position, count(*), max(salary), min(salary), avg(salary) from employee group by position having count(*) < 3;
select dept_id, avg(salary) as salary_avg
from employee
where position != 'CEO'
group by dept_id
having avg(salary) < (
select avg(salary)
from employee
)
order by salary_avg desc;
- having은 group by와 함께 사용됩니다.
- aggregate function의 결과값을 바탕으로 그룹을 필터링하고 싶을 때 사용합니다.
- having절에 명시된 조건을 만족하는 그룹만 결과에 포함됩니다.
select 문법 최종 정리
- select 문에서 개념적인 실행 순서는 위 이미지에서와 같습니다. 하지만, 실제 실행 순서는 RDBMS마다 내부적으로 어떻게 구현했는지에 따라 다릅니다.
'데이터 베이스 > RDBMS' 카테고리의 다른 글
stored procedure란? 그리고 장.단점 (0) | 2023.02.03 |
---|---|
SQL의 stored function이란? (0) | 2023.02.03 |
SQL join의 의미와 사용법 ( with MySQL ) (1) | 2023.02.01 |
RDBMS에서 null 비교 연산 사용법 (0) | 2023.02.01 |
subquery를 이용한 select 사용법 (1) | 2023.02.01 |