brunch

You can make anything
by writing

C.S.Lewis

by 쩐시 Jul 27. 2021

SQL 구문 정리

1. 데이터 조회와 필터링

SCMer로 성장하기 위해 배우기 두달 된 SQL/R언어, 역시 돌아서면 까먹고 또 까먹네요.

온라인 학습의 한계가 있기 때문에, 다시 복습하며 감각을 익혀야겠습니다.


+ 저는 fastcampus 에서 학습했는데, 사실 막히거나 어려운 부분 질문도 못해서, 만약 시간이 진짜 여유롭다면 국비지원 6개월 하고 싶습니다 :(


+ SQLD는 msSQL, Oracle 위주라 도전 포기하려고 합니다 



* PostgreSQL - DBeaver


1. 데이터 조회


Select 추출하기

select * 
 from
           customer  ;         
select 
            first_name, 
            last_name,
            Email
from
             customer :            


order by 정렬하기

select
            first_name,
            last_name
from
            customer
 order by
            first_name (ASC) ;

 -- DESC 내림차순, NULL 최상값
select
        first_name,   
        last_name
    from
            customer
    order by
                     first_name, last_name DESC ;


create table - insert values 테이블 생성 및 값 부여

** 아래의 세 단계에 익숙해지자

create table T1 (
 ID serial not null primary key,
bcolor varchar,
fcolor varchar
) ;
insert into T1 ( bcolor, fcolor)
values
         ('red', 'red')
       , ('red', 'red')
        , ('red', NULL)
       , (NULL, 'red')
       , ('red', 'green')
       , ('red', 'blue')
       , ('green', 'red')
       , ('green', 'blue')
       , ('green', 'green')
       , ('blue', 'red')
       , ('blue', 'green')
       , ('blue', 'blue')
;
select *
        from T1 ;


select distinct 중복값 제외

select 
        distinct bcolor -- bcolor 컬럼에서의 중복된 행 제거
from
        T1
order by
           bcolor  ;
select
        distinct bcolor, fcolor -- bcolor + fcolor 컬럼에서의 공통 중복된 행 제거
from
            T1
order by
            bcolor, fcolor ; 


select 
            distinct on (bcolor) bcolor, -- bcolor 중복값 제거하고 컬럼 두개 추출
                                                fcolor
from
        T1
order by
            bcolor, fcolor ;


2. 필터링


연산자

 = 같음
> ~보다 큰
< ~보다 작은
>= ~이상
<= ~이하
<> , != ~가 아닌
and 그리고
or 혹은


where 조건 부여

select
        last_name,
        first_name
from
        customer
where
        first_name = 'Jamie' 
and last_name = 'Rice' ;
select
        customer_id,
        amount,
         payment_date
from
        payment
where amount <= 1
        or amount >= 8 ;


limit 행수 제한

select
            film_id,
            title,
            release_year
from
            film
order by film_id
limit 5 ;
select
        film_id,
        title,
        release_year
from film
order by film_id
limit 4
offset 3 ; -- 4번째 행부터 4개 추출
select
        film_id,
        title,
        rental_rate
from
        film
order by
            rental_rate DESC -- rental rate 가장 높은 순으로 10개행 추출
limit 10 ;


fetch (limit과 유사)

select 
            film_id,
             title
from
            film
order by title
fetch first row only ; -- limit 1, fetch first 1 row only
select
            film_id,
             title
from
            film
order by title
offset 5 rows
fetch first 5 row only ; -- 6번째 행부터 5개행 추출


in 서브쿼리

select
        customer_id,
         rental_id,
          return_date
from rental
where
        customer_id in (1, 2) -- where customer_ID=1 or customer_ID=2
order by return_date DESC ; -- returen date가 최근인 ID 1 혹은 2 손님 추출
select
        customer_id,
        rental_id,
        return_date
from rental
where
            customer_id not in (1, 2) -- where customer_id != 1 or customer_id != 2
order by return_date DESC ;
select
        customer_id
from rental
where
        cast (return_date as date ) = '2005-05-25' ; -- return_date가 특정 날짜인 경
select
            first_name,
             last_name
from customer
where customer_id in (
                                            select 
                                                        customer_id
                                              from rental
                                              where
                                                          cast(return_date as date) '2005-05-25'
) ;
-- 특정날짜에 해당하는 고객ID를 구한 후, 그 고객의 이름을 추출
-- 서브쿼리는 where customer_id in() 으로 연결해야 한다.
-- where custoemr_id = () 안됨


between

select
            customer_id,
            payment_id,
            amount
from
          payment
where amount between 8 and 9 ; 
select
            customer_id,
            payment_id,
            amount
from
        payment
where amount not between 8 and 9 ; -- amount >=8 and amount <= 9
select
            customer_id,
             payment_id,
            amount,
            payment_date
from
        payment
where cast(payment_date as date) between '2007-02-07' and ' 2007-02-15' ;
select
            customer_id,
            payment_id,
             amount,
            payment_date,
            to_char(payment_date, 'yyyy-mm-dd'),
            cast(payment_Date as date)
from 
        payment
where to_char(payment_Date, 'yyyy-mm-dd') between '2007-02-07' and '2007-02-15' ;

-- to_char은 원하는 형식으로 바꿔줌


like 유사한 패턴의 집합 출력

select
            first_name,
            last_name
from
           customer
where 
            first_name like 'Jen%' ;
 
-- '%er%'  앞뒤 무한
-- '_her%' 앞의 한자리 수, 뒤 무한
select
            'FOO' like 'FOO', --T
            'FOO' like 'F%', --T
            'FOO' like  '_O_', --T
            'BAR' like 'B_' ; --F


is null

create table contacts (
id int generated by default as identity,
first_name varchar(50) not null,
last_name varchar(50) not null,
email varchar(255) not null,
phone varchar(255) not null,
primary key (id)
) ;
insert
            into contacts(fisrt_name, last_name, email, phone)
values
( 'John', 'Doe', 'john.doe@example.com', null),
( 'Lilly', 'Bush', 'lily.bush@example.com', '(408-234-2764)' ;

commit;
select *
            from contacts;


select
            ID,
            first_name,
             last_name,
            email,
            phone
from
            contacts
where phone = null ; -- where phone is null ;


Quiz 1


--PAYMENT 테이블에서 단일 거래의 AMOUNT의 액수가 가장 많은 고객들의 CUSTOMER_ID를 추출하라. 

--단, CUSTOMER_ID의 값은 유일해야 한다.

1. 전체 거래 중 amount 액수가 가장 큰 값 구하기

select
            amount
from
        payment
order by amount DESC
limit 1 ;
2. payment 테이블에서 가장 큰 amount를 가진 customer_id를 구하고 중복 제거

select distinct
                        customer_id
from payment
where amount = (
                                select amount
                                 from payment
                                order by amount DESC
                                limit 1
);


Quiz 2


--고객들에게 단체 이메일을 전송 하고자 한다. 

--CUSTOMER 테이블에서 고객의 EMAIL주소를 추출하고, 이메일 형식에 맞지 않는 이메일 주소는 제외시켜라. 

--(이메일 형식은 ‘@’가 존재해야 하고 ‘@’로 시작하지 말아야 하고 ‘@’로 끝나지 말아야 한다.)

--dbmsexpert@naver.com 


select email
from customer
wher email not like '@%'
   and email not like '%@'
   and email like '%@%'
;
작가의 이전글 우리가 중국기업에 관심 없는 이유

작품 선택

키워드 선택 0 / 3 0

댓글여부

afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari