본문 바로가기

오라클

where절(SQL)

select 절 : 일부 컬럼 반환

from 절 : 모든 데이터 반환

where 절 : 일부 레코드 반환


실행순서 : from > where > select


//where절

- select * from 테이블명 where절;

- 조건을 제시한 뒤 조건을 만족하는 레코드만을 가져오는 역할(일부 레코드 반환)

- 주로 컬럼값을 대상으로 비교 연산 or 논리 연산을 통해 해당 레코드를 가져올 지 판단


-select first,last from tblname where gender ='f';

=>

--결과 테이블, Result Table, 결과셋 , ResultSet

select first,last --3. 2번으로부터 받은 결과 테이블에 원하는 컬럼만 취한 뒤 최종 결과 테이블 반환한다.

    from tblname --1. 테이블 원본을 취한다.

        where gender ='f'; --2. 조건을 만족하는 레코드만 존재하는 테이블을 취한다.


//비교 연산에 사용되는 자료형

1. 숫자형

2. 문자형 -> 문자 코드값 비교 str.compartTo(str2)

3. 날짜 시간형 -> tick값


//비교연산 where절

select * from tblname where height > 160;

select * from tblname where last > '마';

select * from tblname where first < '재석';

select * from tblinsa where ibsadate >= '1999-08-01';


--where 절과 관계된 구문들..

//1.between

- where 절에서 사용(조건을 사용)

- 범위 조건 지정

- 가독성 향상

- 컬럼명 between 최소값 and 최대값

- between 상요 자제 > 비교(연산)연산자 사용 속도보다 느리다.


ex) 몸무게 60이상~ 80이하

select * from info where weight >=60 and weight<=80;

select * from info where weight between 60 and 80;


ex)날짜 

select * from insa wher sadate between '1998-01-01' and '1998-12-31';

select * from insa where not sadate between '1998-01-01' and '1998-12-31';


//2. in

- where 절에서 사용(조건으로 사용)

- 열거형 조건 비교(제시값 중에서 하나라도 만족하면 만족)

- 컬럼명 in(열거형 값)


ex)insa > '기획부','영업부','총무부'

>+ '부장','과장

>+ '서울','인천'

>급여 250~300만원


select * from insa

where buseo in('기획부','영업부','총무부')

and jikwi in('부장','과장')

and basicpay between 2500000 and 3000000;


//3. like

- where 절에서 사용(조건으로 사용)

- 패턴 비교(특정한 패턴을 가지는 문자열 검색

- 문자형을 대상으로 사용(숫자, 날짜 적용X)

- 정규 표현식과 유사

- 컬러명 like '패턴 문자열'


패턴 문자열 구성요소

1) _ : 임의의 문자 1개

2) % : 임의의 문자 0개 ~ 무한대


ex)

select * from insa where name like '박__';

select * from tblinsa where name like '_길_';

select * from tblinsa where name like '__동';


select * from employees where first_name like 'D%'; - D로 시작하는 모든 이름

select * from employees where first_name like '%d'; - d로 끝나는 모든 이름

select * from employees where first_name like '%d%'; - d가 들어가는 모든이름


//4. null

- 자바의 null과 유사한 표현

- 비어있는 컬럼의 상태

- SQL은 null은 연산의 대상이 될 수 없다.(피연산자 자격X)

- SQL은 null이 포함된 연산을 하면 항상 결과가 null값을 반환한다.


null조건

- where 절에서 사용

- 컬럼명 is null


ex)인구수가 아직 기재되지 않은 나라

select * from country where population is null;


ex)인구수가 기재되어있는 나라

select * from country where population is not null;


ex)인구수가 아직 기재된 나라

select * from country where not population is null;

select * from country where not population is not null;


//5. distinct

- 컬럼 리스트에서 사용

- distinct 컬럼명

- 중복값 제거

- null도 데이터의 한 종류로 인식한다 -> null가지는 레코드들도 중복값 제거가 된다.


ex) country에는 어떤대륙들이 있습니까?

select distinct(continent) from country;


ex) insa에는 어떤 부서가 있을습니까?

select distinct buseo from insa;


ex) 성별이 뭐가 있는지?

select distinct gender from info;


ex) insa 직위가 어떻게 됩니까?

select distinct jikwi from insa;


ex)info 성이 뭐뭐?

select distinct last from info;


//주의

-distinct 컬럼리스트가 같아야 중복값으로 배재시킨다.

-distinct는 컬럼리스트에 딱 1번만 적을 수 있다.

-distinct 키워드 뒤의 모든 컬럼 리스트를 합쳐서 중복값 검사를 한다.

select distinct price,qty from tblhousekeeping;


select distinct price from tblhousekeeping;


//6. case

- 컬럼 리스트에서 사용

- 조건절에서 사용

- 사용 횟수 자유

- 자바의 if문 + switch 문과 유사


ex)select last || first as name,case when gender = 'm' then '남자' when gender ='f' then '여자' end from tblname;


select las||first as name,

case

when gender ='m' then '남자'

when gedner ='f;' then '여자'

end as gender

from info


ex)

select 

    last || first as name,

    weight / (height*height)*10000 as bmi,

    case

        when weight > 80 then '과체중'

        when weight > 60 then '정상체중'

        when weight > 0 then '저체중'

        else '미정'

    end as 체중상태

from info;


ex) 완료된 일 vs 진행중인 일 : 구분

select title,

case

when completedate is not null then '완료'

when completedate is null then '진행중'

end as "완료유무"

from todo;


//정렬, Sorting

- 결과셋의 레코드의 순설르 정렬(원본테이블과는 무관하다)

- 원본 테이블의 레코드 순서는 DBMS가 알아서 한다.(신경X)

- order by 절

- order by 컬럼명 [asc/desc]

- select문에서만 사용가능(insert, update 등은 .. 적용불가)

- select 컬럼리스트 from 테이블명 where 절 order by 절

- asc : 오름차순(ascending)

a. 숫자 : 10 -> 20 -> 30

b. 문자 : '가' -> '나' -> '다'

c. 날짜시간 : 2016 -> 2017 -> 2018

-실행순서 : from > where > select > order by


ex)

select * from tblname order by first asc;

select * from tblname order by weight desc;


-연산의 결과나 함수의 반환값이 정렬의 기준이 될 수 있다.

select name,basicpay,sudang from tblinsa order by (basicpay+sudang) desc;


select name,basicpay,sudang 

from tblinsa 

where buseo='영업부' 

order by (basicpay+sudang) desc;


'오라클' 카테고리의 다른 글

서브쿼리(SubQuery)  (0) 2018.08.28
시퀀스(Sequence)  (0) 2018.08.27
Select문(DML)  (0) 2018.08.23
SQL 자료형  (0) 2018.08.23
오라클DB  (0) 2018.08.23