[SQL] 연습

[SQL] SQL 기본(1편)

Simon Yoon 2022. 1. 29. 22:39

SELECT문

1. country 테이블에서 전체 칼럼의 데이터 가져오기

select *
from country
;

 

2. country table에서  code, name, population 가져오기

select code, name, population
from country
;

 

3. select절에서 연산한 결과 출력

surfacearea를 2로 나눈 결과를 new_area 칼럼으로 처리

select code, surfacearea / 2 as new_area
from country
;

 

ORDER BY로 정렬하기

1. 오름차순: population을 오름차순(asc)으로 정렬 (asc는 디폴트라서 안써로 자동으로 오름차순으로 정렬됨)

select code, name, population
from country
order by population asc
;

 

2. 내림차순: population을 내림차순(desc)으로 정렬

select code, name, population
from country
order by population desc
;

 

3. 혼용: continent이름은 오름차순으로 정렬, GNP는 내림차순으로 정렬

select code, continent, GNP
from country
order by continent, GNP desc
;

 

DISTINCT로 중복 제거

1. countrylanguage 테이블에서 중복값을 제거하여 언어 종류를 출력

select distinct Language
from countrylanguage
;

 

WHERE절로 조건에 맞는 데이터 출력

1. country table에서 continent가 europe인 나라 출력

select code, name, continent
from country
where continent = 'europe'
;

 

2. country table에서 continent가 europe이고 population이 5천만 초과인 나라를 이름 오름차순으로 출력

select code, name, continent, population
from country
where continent = 'europe' and population > 50000000
order by name
;

 

3. country table에서 gnp가 30000에서 50000사이인 나라만 출력

select code, name, continent, gnp
from country
where gnp between 30000 and 50000
# gnp >= 30000 and gnp <= 50000과 동일한 결과
;

 

4. country table에서 continent가 'asia', 'europe'인 나라만 출력

select code, name, continent, gnp
from country
where continent in ('asia', 'europe')
# continent = 'asia' or continent = 'europe'과 동일
;

 

5. country table에서 continent가 'a'로 시작하는 나라를 출력

select code, name, continent, gnp
from country
where continent like 'a%'
;

 

'[SQL] 연습' 카테고리의 다른 글

[DB] mysql에서 한글 포함된 쿼리 insert 안될 때  (0) 2022.06.11
[DB] MongoDB  (0) 2022.05.01
[SQL] SQL 기본(3편)  (0) 2022.02.01
[SQL] SQL 기본(2편)  (0) 2022.01.30
[SQL] 데이터 베이스 기본  (0) 2022.01.27