
SQL Query
데이터베이스에서 데이터를 가져오는 문법
DDL(Data Definition Language, 정의어)
- DB(table의 집합), Table(data의 집합)의 생성, 읽기, 변경, 삭제 명령어
- CRUD(create, read, update, delete)
- C(create) R(show, desc) U(alter) D(drop)
DML(Data Manipulation Language, 조작어)
- Table data의 생성, 읽기, 변경, 삭제 명령어
- CRUD(create, read, update, delete)
- C(insert into) R(select from) U(update set) D(delete from)
DCL(Data Control Language, 제어어)
- 권한설정, 보안, 병행 수행 제어 등 DB를 관리하는 명령어
- commit, rollback, grant, revoke
Read(읽기)
in DDL
- SHOW, SELECT
예시
# 데이터베이스 목록 조회
show databases;
# 현재 선택중인 데이터베이스 조회
select database();
# 테이블 리스트 조회
show tables;
in DML
- SELECT FROM
- WHERE, ORDER BY, LIMIT 등과 같이 사용할 수 있음
SELECT 기본예시
- 'world' database의 'country' table에 있는 데이터를 전부 출력하기
select * from world.country;
# 또는
use world; # 데이터베이스 선택
select * from country;
AS
- alias
- as를 통해 컬럼명 변경
select code, name as country\_name, population as pop
from country;
연산자
- 산술, 비교, 논리
- 산술연산자 : +, -, *, /, %
- 비교연산자 : =, !=, >, <, >=, <=
- 논리연산자 : and, or, not, xor
산술연산자 예시
* country 테이블에서 국가코드, 국가이름, 국가면적, 국가인구수, 인구밀도 출력하는 과정은 다음과 같다.
#인구밀도 = 국가인구수/국가면적
select Code, Name, SurfaceArea, Population
, Population / SurfaceArea as Population_Density
from country;
* world 데이터베이스에서 국가코드, 국가이름, 1인당 GNP 출력하는 과정은 다음과 같다.
select * from country;
select Code, Name, 1000000 * GNP/Population as GNPp1
from country;
비교연산자 예시
- 데이터 (비교) 데이터 -> 논리값(bool:True, False)
- True = 1, False = 0
- WHERE(조건문)문으로 많이 활용한다.
* 국가이름, 대륙이름, 아시아대륙이면 1 출력하는 과정은 다음과 같다.
select Name, Continent, Continent = 'Asia' as is_Asia
from country;
# where절 활용하기
select Name, Continent, GNP
from country
where Continent = 'Asia';
논리연산자 예시
- AND, OR, NOT
* 국가코드, 인구수, 기대수명, 인구수 5천만 이상이고 기대수명 70세 이상이면 1 출력
select * from country;
select Code, Name, Population, LifeExpectancy, Population >= 50000000 and LifeExpectancy >= 70 as cond
from country;
반응형
'Skill Set > SQL' 카테고리의 다른 글
[SQL] MySQL Workbench 사용하기(for windows) (0) | 2022.09.28 |
---|---|
[SQL] MySQL Query의 기초 - 3 (1) | 2022.09.20 |
[SQL] MySQL Query 기초 - 2 (1) | 2022.09.20 |
[SQL] AWS EC2 - Mysql 설치하기 (0) | 2022.09.17 |
[SQL] DB의 이해 (0) | 2022.09.16 |