TIL

[TIL] 15일차_SQL_Grammar_01

Molybdenum_j 2023. 3. 7. 14:30

▶ SQL_Grammar

  • select :  정보를 조회한다.
  • from  :  어느 테이블로부터
  • 별칭 : a as b =a를 b로
  • limit 갯수제한 => limit는 젤 끝에
  • distinct 중복 제거
select * 
from student 
where sex = Male;

 


 

  • where 어떤것(필터조건)
  • Ture = 1
  • False = 0
  • and : 곱하기, 교집합
    • True and True = True
    • True and False = False
    • False and False = False
select * from `thelook_ecommerce.users`
where id < 10000
and first_name = 'David'
  • or : 더하기, 합집합
    • True or True = True
    • True or False = True
    • False or False = False
select * from `thelook_ecommerce.users`
where age < 20
or age > 60
  • not
select * from `thelook_ecommerce.users`
where NOT(country = 'United States' or country = 'Brasil');
 

  • between 사이에
select * 
from `thelook_ecommerce.users`
where age between 20 and 30

같은 값을 가지지만 다르게 입력한 것입니다.

select * 
from `thelook_ecommerce.users`
where age>=20 and age<=30
  • in 안에
select * 
from `thelook_ecommerce.products`
where brand in ('Onia', 'Hurley', 'Matix');
  • like M% = M로 시작하는 문자
select * 
from `thelook_ecommerce.products`
where name like 'Hurley%';

like %M = M로 끝나는 문자

like %M% = 중간에 M이 껴있는 문자

like 'Da___' = 시작이 Da로 시작하는 5 글자

 

  • NULL값을 찾을 때는 is NULL
select * 
from `thelook_ecommerce.order_items`
where shipped_at IS NULL;

NULL이 아닌 값을 찾을 때는 is not NULL

select * 
from `thelook_ecommerce.order_items`
where shipped_at IS NOT NULL;
 

 

- 집계함수 : 여러 행으로부터 하나의 결과값을 반환하는 함수

  • COUNT = 레코드의 개수를 반환하는 함수
select count(id) 
from `thelook_ecommerce.users`;

 중복을 제거해서 카운팅하기도 한다.

select count(distinct city) 
from `thelook_ecommerce.users`;
  • SUM = 해당 레코드의 합게를 반환하는 함수
select sum(retail_price)
from `thelook_ecommerce.products`
  • AVG = 해당 레코드의 평균을 반환하는 함수
select avg(cost)
from `thelook_ecommerce.products`;
  • MAX = 레코드의 최대값을 반환하는 함수
select max(cost), max(retail_price)
from `thelook_ecommerce.products`;
  • MIN = 레코드의 최소값을 반환하는 함수
select min(cost), min(retail_price)
from `thelook_ecommerce.products`;
  • VARIANCE = 레코드의 분산을 반환하는 함수
select variance(retail_price)
from `thelook_ecommerce.products`
  • STDDEV = 레코드의 표준편차를 반환하는 함수
select stddev(retail_price)
from `thelook_ecommerce.products`
  • GROUP BY = 특정항목을 기준으로 그룹화하여 조회할 수 있다.
select country, count(id) 
from `thelook_ecommerce.users` 
group by country;

그룹화하여 조회할 때는 그룹화 하려는 항목이 SELECT에 들어가야 함