IT 컴퓨터/SQL・빅쿼리

SQL 문법 정리

데이터 시오 2024. 6. 28. 10:55
728x90
반응형

MySQL 기준으로 작성되었습니다

DML(Data Manipulation Language)

  • insert
  • update
  • delete
  • select

DDL(Data Definition Language)

  • create
  • alter
  • drop
  • truncate
  • rename

DCL(Data Control Language)

  • grant
  • revoke

TCL(Transaction Control Language)

  • commit
  • rollback
  • savepoint

Create

  • 테이블 생성
    create table student (
    칼럼명 타입 조건(not null 등),
    칼럼명 타입 조건(not null 등),
    칼럼명 타입 조건(not null 등),
    PRIMARY KEY ~~ );

Insert

  • 테이블에 데이터 삽입
    insert into student values(테이블에 맞는 데이터 양식);

Update

  • 데이터 내용 수정
    update 테이블 set 칼럼 = '값' where 조건;

Delete

  • 데이터 삭제
    delete from 테이블 where 조건;

select

  • 모든 컬럼 조회
    select * from student;
  • 필요한 컬럼 조회
    select age, name from student;

select 문법 순서

  1. select
  2. from
  3. where
  4. group by
  5. having
  6. order by

*쿼리의 실행 순서는 from ▶ where ▶ group by ▶having ▶ select ▶ order by

 


Where

  • 컬럼 조회의 조건
    select * from student where id = 1;
  • and, or 조건
    select * from student where sex='남자' and(or) address='서울';
  • like 조건
    % 로 표현
    select * from student where name = '김%';

Limit

  • 조회 결과 행의 수 제한
    select * from student limit 1;

Group By

  • 특정 칼럼 기준의 데이터 그룹핑
    select age from student group by age;

Order by

  • 특정 칼럼 기준으로 정렬
  • ASC : 오름차순 1 2 3 4 5
  • DESC : 내림차순 5 4 3 2 1
    select * from student order by age desc;

Distinct

  • 중복 행을 제거
    select distinct name from student;

Alias

  • 칼럼에 별칭을 주고 조회
    select age '나이' from student where id = 3;

연산자

  • 산술 연산자 : + - / *
  • 비교 연산자 : > < >= <= = != ^= <>
  • 논리 연산자 : and, or, not
  • 비교 연산자2 : between and, in, is null, like

함수

문자 조작 함수

  • UPPER(str) : 대문자 변환
  • LOWER(str) : 소문자 변환
  • INITCAP(str) : 첫 글자만 대문자로 변환
  • CONCAT(str, tmp) : 두 문자값 결합
  • SUBSTR(str,a,b) : 문자 추출 a = 시작위치, b = 개수
  • LENGTH(str) : 문자열 길이 반환
  • L/RPAD(대상,총길이,채울문자열) : 대상 문자열에 채울문자열을 총길이만큼 채워서 반환
    LPAD('001',7,'0') ▶ 0000001
  • LTRIM, RTRIM(대상, 제거할 문자열) : 대상 문자열에서 제거할 문자열을 없앤 뒤 반환
    select LTRIM('00010' , '00') ▶ 010
  • REPLACE(대상문자열,바꾸고싶은대상,바꾸고싶은내용) : 대상문자열에서 바꾸고 싶은 대상을 바꾸고 싶은 내용으로 수정한 뒤 반환
    REPLACE('ABCDEFG','DEF','XXX') ▶ ABCXXXG

계산 함수

  • max
  • min
  • count
  • avg
  • sum

select 계산함수(칼럼) from 테이블; 로 사용


JOIN

728x90