SQL

SQL - select문에서의 여러 사용법

황민준 2022. 10. 7. 11:37

*산술표현

보여지는 컬럼에 산술연산을 하여 보여줄 수도 있다.

 

*별칭(as)

컬럼에 as구문을 사용하여 원하는 문구로 별칭을 줄 수 있다.

 

*concat

컬럼의 값들을 문자열로 합칠 수 있다. -> 컬럼들 뿐만 아니라 원하는 문자열도 삽입 가능하다.

-> 숫자를 concat할 경우 원래 숫자 형태 그대로를 문자로 가져오기 때문에 연산 시에 소수점이 생길 수 있다

-> truncate()를 통해 보여지는 소수점을 지정할 수 있다.

 

*특정 조건의 데이터 조회

select [컬럼 명] from [테이블 명] where [조건];

 

*and 조건

where절에서 and를 통하여 조건 사이에 and 연산을 할 수 있다.

 

*or 조건

where절에서 or을 통하여 조건 사이에 or 연산을 할 수 있다.

 

*between and

where절에서 between A and B를 할 경우 A이상 B이하 데이터를 찾을 수 있다.

 

*중복 제거

select distinct [컬럼 명] from [테이블 명];

-> 단일 컬럼으로 사용하는 것이 효율적이다.

 

*in

where절에서 여러 조건을 or로 할 수도 있지만 in (1, 2, 3, ...) 으로 할 수도 있다.

or과 차이점으로는 in은 같은 컬럼에 대해서만 조건을 줄 수 있다.

*is null / is not null

is nullis not null은 해당 컬럼의 값이 null 값인지 아닌지 상태를 확인하는 것이다.

 

*문자열 검색 like

일부가 비슷한 내용을 검색하는 것으로 부하를 많이 준다.

where [컬럼 명] like ‘%[문자열]%’;

-> %는 와일드 카드로 몇 글자가 오든 상관없다는 뜻이다.

 

*정렬 (order by)

특정 컬럼을 기준으로 정렬

asc : 오름차순(생략 가능)

desc : 내림차순

-> 정렬은 항상 마지막에 해야한다.

-> as 별칭으로도 정렬이 가능하다.

 

*다중 정렬

정렬도 여러 컬럼으로 할 수 있다. -> 앞에서부터 차례로 정렬한다.

 

*group by

데이터를 그루핑해서 결과를 가져오는 경우 사용

select [컬럼 명] from [테이블 명] group by [그루핑할 컬럼];

-> 보여지는 컬럼은 그루핑할 컬럼이거나 값이 하나로 나오는 집계 함수(sum, avg, count)여야 한다.

-> count(*)은 모든 컬럼의 수를 세지만 count(컬럼)null값은 세지 않는다.

 

*having

group bywhere절이다. (group by 결과로부터 특정 조건을 추출할 경우 사용)

-> 원래는 having 절에 as 별칭을 사용할 수 없다. (mariaDB는 예외)

 

select * from employees;

-- 1) 특정 컬럼 조회
-- SELECT [컬럼 명, ...] FROM [테이블 명];
select * from employees;
select first_name, family_name, salary from employees;

-- 보여주는 컬럼 순서는 변경 가능하다.
select family_name, first_name, salary from employees; 

-- 산술 표현
select first_name, family_name, salary/10000 as 월급 from employees;

-- 연봉(여기서 as라는 구문으로 별칭을 줄 수 있다.)
select first_name, family_name, salary*12 as 연봉 from employees;

-- CONCAT()으로 문자열을 합칠 수 있다.
select concat(family_name, first_name) as 이름, salary from employees; 
select concat(family_name, ' ', first_name) as 이름, salary from employees; 
-- 이름, 월급(700만원)
select 
	concat(family_name,first_name) as 이름, 
	concat(truncate(salary/10000,0), '만원') as 월급  
from employees;

-- 2) 특정 조건의 데이터 조회
-- SELECT [컬럼 명] FROM [테이블 명] WHERE [조건];
select * from employees where family_name = '김';
select * from employees where salary > 3000000;

-- 2-1) AND 조건
select first_name, family_name, salary from employees e where salary >=1000000 and salary <=3000000; 

-- 2-2) OR 조건
select * from employees e where family_name = '김' or salary = 2000000;

-- 2-3) BETWEEN AND
-- salary가 50만원보다 크거나 같고 400만원보다 작거나 같은 사람들의 first_name, family_name, salary를 구하세요
select first_name, family_name, salary from employees e where salary >= 500000 and salary <= 4000000;
-- 부등호의 경우 특수문자로 인식되는 경우가 있어 이를 최소화하기 위해 사용된다.
select first_name, family_name, salary from employees e where salary between 500000 and 4000000;

-- 3) 중복 제거
-- SELECT DISTINCT [컬럼 명] FROM [테이블 명];
-- 이 때 단일 컬럼으로 사용하는 것이 가장 효율적이다.
select salary,family_name from employees e where salary = 2000000;
select distinct salary,family_name from employees e where salary = 2000000;

-- 4) IN(OR조건과 같은데 더 간결하고 속도도 빠르다.)
-- WHERE family_name = '김' OR family_name = '이' OR family_name = '박'
-- IN은 조건에서 사용하는 컬럼이 모두 같아야 한다.
select * from employees e WHERE family_name in ('김', '이', '박');

-- IS NULL / IS NOT NULL
select * from employees e where commission is null;
select * from employees e where commission is not null;

-- 6) 문자열 검색 LIKE
-- 일부가 비슷한 내용을 검색한다.
-- DB에 부하를 많이 준다.
-- WHERE [컬럼 명] LIKE '%[문자열]%';

-- ze% -> ze로 시작하는...
-- %com -> com으로 끝나는...
-- %se% -> se를 포함하는...
-- %s%e% -> s와 e를 포함하는...

select email from employees e where email like 'ze%';
select email from employees e where email like '%com';
select email from employees e where email like '%se%';
select email from employees e where email like '%s%e%';

-- 7) 정렬(ORDER BY)
-- 특정 컬럼을 기준으로 정렬
-- ASC(생략 가능) | DESC 
-- SELECT [컬럼 명] FROM [테이블 명] ORDER BY [컬럼 명][ASC|DESC];
select * from employees e order by salary;
select * from employees e order by salary desc;
-- 별칭으로도 정렬이 가능하다.
select family_name, first_name, salary*12 as 연봉 from employees e order by 연봉 desc;

-- 다중 정렬
select * from employees e order by first_name, salary desc;

-- salary가 200만원 이상인 사람을 family_name 오름차순으로 정렬해서 보여주세요
-- 정렬은 항상 마지막에 해야한다.
select * from employees e where salary >= 2000000 order by family_name asc;

-- 8) GROUP BY
-- 데이터를 그루핑해서 결과를 가져오는 경우
-- SELECT [컬럼명,...] FROM [테이블 명] GROUP BY [그룹핑할 컬럼];
select depart_no, sum(salary) from employees e group by depart_no; -- 그룹별 급여 합계
select depart_no, avg(salary) from employees e group by depart_no; -- 그룹별 급여 평균
select depart_no, count(*) from employees e group by depart_no; -- 그룹별 멤버 수
-- COUNT(*) 경우에는 NULL까지 세지만 COUNT(컬럼 명) 경우에는 NULL은 빼고 센다.

-- SELECT 뒤에 나오는 컬럼은 GROUP BY의 컬럼 또는 집계 함수여야 한다.
-- 각 그룹의 첫 값이 나온다.(에러 방지용으로 제공)
-- select * from employees where depart_no = 'dev001';
select depart_no, salary from employees e group by depart_no ;
-- GROUP BY는 특정 컬럼을 묶어서 하나로 가져와야 하는데 salary는 그룹에 여러 개이다.
-- 그래서 가져오고 싶다면 하나로 표현할 수 있는 집계를 해야한다.

-- depart_no을 기준으로 묶어서 depart_no, salary, commission을 모두 가져와보자.
select depart_no, sum(salary) as 급여합계, avg(commission) as 인센평균 from employees e group by depart_no;

-- 9) HAVING
-- GROUP BY 결과로부터 특정 조건을 추출할 경우 사용
select depart_no, sum(salary) as 급여합계, avg(commission) as 인센평균 
from employees e group by depart_no order by 급여합계 desc;

-- HAVING은 일반 SELECT 문에 WHERE라고 생각하면 된다.
select depart_no, sum(salary) as 급여합계, avg(commission) as 인센평균 
from employees e group by depart_no having 급여합계 > 10000000 order by 급여합계 desc;

-- HAVING절에는 별칭을 쓸 수 없다.(몇몇 DB에서는 허용)
select depart_no, sum(salary) as 급여합계, avg(commission) as 인센평균 
from employees e group by depart_no having sum(salary) > 10000000 order by 급여합계 desc;