개발정보/DB

SQL 첫걸음 3장 정렬과 연산

dev김 2019. 1. 27. 19:30

select 열명 from 테이블명 where 조건식 order by 열명;

조건식에 해당하는 행들의 열을 열명으로 정렬한다

desc 내림차순(큰 값에서 내려간다) asc 오름차순(작은 값에서 올라간다) 기본asc


select 열명 from 테이블명 where 조건식 order by 열명1 [정렬], 열명2 [정렬] ...

select * from sample32 order by a,b; a 우선 정렬 그 뒤에 b 정렬

select * from sample32 order by a asc, b desc; 

널 값의 정렬순서는 DB마다 다르다 mysql에선 가장 작은값


limit mysql비표준sql

select 열명 from 테이블명 limit 행수 [offset 시작행] offset은 0부터 시작(page*size)

select * from sample33 order by no desc limit 3; 내림차순 후 상위 3건만

limit 사용불가 db에서

sql server : select top 3 * from sample33;

oracle : select * from sample33 where rownum <= 3;


산술연산

*/% 우선순위 1

+- 우선순위 2


select *,price * quantity as amount from sample34;

ascii 문자 이외에 지정시에 더블쿼트 "금액"


select *,price * quantity as amount from sample34 where price * quantity >=2000;


where->select 순서로 처리되어 select의 별명을 where에서 쓸수 없다

NULL값의 연산은 NULL이다


select *,price * quantity as amount from sample34 order by price * quantity desc;

select *,price * quantity as amount from sample34 order by amount desc;


10%3 MOD(10,3) MOD(나머지연산 mysql,oracle)

ROUND(amount) 소수점 이하 반올림 amount는 DECIMAL 타입

ROUND(amount,1) 소수점 둘째 자리 반올림 ROUND(amount,-2) 10단위를 반올림

TRUNCATE 버림 함수 SIN,COS,SQRT,LOG 등의 함수 존재


문자열 연산

'ABC' || '1234' -> 'ABC1234 oracle,db2,postgresql 

a+b sql server / CONCAT(quantity,unit) mysql

SUBSTRING('20140125001',1,4) -> '2014'

SUBSTRING('20140125001',5,2) -> '01'

TRIM('ABC     ') -> 'ABC' 앞 뒤 공백문자 제거

CHARACTER_LENGTH CHAR_LENGTH

OCTET_LENGTH는 문자를 바이트 단위로 계산 주의 필요(EUC-KR 한글2/UTF-8 한글3)


날짜연산

CURRENT_TIMESTAMP CURRENT_DATE INTERVAL

select current_timestamp;

oracle to_date('2014/01/25','YYYY/MM/DD') to_char


CASE gender

    WHEN 1 THEN 'male'

    WHEN 2 THEN 'female'

END


select a, case when a IS NULL then 0 else a end "a(null=0)" from sample37;

a가 널일 때 값을 0으로


널값 반환일 경우 COALESCE 사용

select a, COALESCE(a,0) from sample37;


검색 케이스

select a as "코드"

case 

    when a=1 then 'male'

    when a=2 then 'female'

    else 'unknown'

end as "gender" from sample37;


단순 케이스

select a as "코드"

case a

    when 1 then 'male'

    when 2 then 'female'

    else 'unknown'

end as "gender" from sample37;


else가 없으면 else null 이 되므로 지정하는게 좋다

널값체크는 검색케이스를 사용