SQL 구조와 기초 문법

Stian·2023년 6월 20일

1. SQL에서의 데이터베이스

SQL 기본 구조

  • SQL이 유용한 이유 : 많은 양의 데이터를 효과적으로 저장/수정/사용함. 매우 신속함

  • 데이터베이스는 여러 사람들이 같이 사용할 목적으로 데이터 담는 통.

  • 데이터를 잘 꺼내오기 위해 쓰는 것이 데이터베이스의 역할
    C : create
    R : read
    U : update
    D : delete

  • 테이블 : 엑셀에서의 시트와 같은 역할

  • 필드 : 테이블 안에서의 열(변수)와 같은 역할
    이미 들어있는 데이터에서
    Tables는 일종의 엑셀파일인것이고
    안에있는 tables 안에 있는 것들이 엑셀에 있는 시트인 셈이다.

  • 예시들
    show tables -> 전체 시트명이 나온다.
    select * from courses
    시트 중 courses 라는 시트의 전체 (*)를 도출시키라는 말임. 별은 전체를 의미함!
    select order_no, email from orders
    시트 중 orders라는 명칭의 시트 안에서의 변수명인 order_no와 email을 도출시키라는 말이다.

  • 이건 참고용인데 DBeaver에서 오른쪽 위 스크립트 파일 패널에 Format -> 자동줄바꿈하면 좌우 움직이는 것을 조절 할 수 있으며,

  • 레이아웃 ->결과 패널 보기/숨기기 혹은 Maximize results panel 등을 조절하면 스크립트나 결과창이 사라졌을 때 조절할 수 있다.

주요 문법들

  • 필터걸기 WHERE

select * from orders
where payment_method = 'kakaopay'

#필터걸기. payment_method 중 카카오페이로 결제한 사람들

select*from point_users
where point>=5000

select* from orders
where course_title='앱개발 종합반' and payment_method ='CARD'

select*from point_users
where point>20000

select*from users
where name="황**"

select * from orders
where course_title='웹개발 종합반'

  • 포함하지 않다 !=

    select*from orders
    where course_title !="웹개발 종합반"

    #같지않다라는 것 != ...이건 파이썬이랑 R과도 같네

  • 범위 표현하기 between A and B in

select*from orders
where created_at between '2020-07-13' and '2020-07-15'

#날짜 사이의 범위를 표현함.

select*from checkins
where week in (1,3)

#where week=1 or 3은 먹히지 않음 .왜냐면 week 안의 항목들이 순서형이라고 인식되었기 때문이라고 생각됨.

  • 패턴으로 찾기 -> Like 쓰기

    #다음 이메일만 쓰는 유저만 보고싶다.
    select * from users
    where email like'%daum.net'

    #%는 엑셀에서 @의 역할임.. 앞에 뭐가있든...여기에서 like는 including을 의미하는듯. ~~근데 왜 안먹히냐 ~~
    where email like 'a%.com'

  • 동시에 만족하는 조건들 like and

    select * from users
    where email like 's%com' and name='이**'

  • limit

    select * from orders
    where payment_method = 'kakaopay'
    limit 5

    #위에서 행 다섯개만 보이게 하기. limit 5이라고 하면 안됨.. t와 5 사이에 공백 두 개 주니까 겨우 됨.

  • distinct

select * from orders
select payment_method from orders

#중복없이 특정 변수들을 쫙 늘어놓음.

select distinct(payment_method) from orders

#중복제거하고 보기. 이거 좀 유용할듯!!!!

count 세기.

select from orders
select count(
) from orders #orders 시트의 행의 개수를 센다.

select * from users
select name from users
select distinct(name)from users
select count(distinct(name)) from users

#중복제거 후에 그 항목들이 몇개인지.

0개의 댓글