SQL - Structured Query Language : 구조적 질의어
Data -> CRUD
insert,delete,select,update
( 90%이상이 select )
대소문자를 구분하지 않는다 ex ) select == SELECT
주석문
/*
범위 주석문
*/
-- 한줄 주석문
자료형
<java> <MySQL>
int int, decimal(5)
double double, decimal(5,1) -- 소수점 첫째자리까지
String var char
Date date
use 구문 : 사용할 데이터베이스 지정
use 데이터베이스이름;
table 생성
create table 테이블명(
컬럼명1 자료형,
컬럼명2 자료형
:
);
table 정보 조회
-- 명령어를 통한 조회
show table status;
-- Query를 통한 조회
select *
from information_schema.tables
where table_schema= '데이터베이스이름';
column 정보 조회
desc 테이블명;
table 제거
drop table 테이블명
-- varchar == String
create table tb_varchar(
col1 varchar(10), -- 10byte
col2 varchar(20)
);
insert into tb_varchar(col1, col2)
values('abc', 'ABC');
select * from tb_varchar;
drop table tb_varvhar;
/*
결과
col1 col2
abc ABC
drop table tb_varvhar; 실행 후 제거됨
*/
-- int, double
create table tb_decimal(
col1 decimal,
col2 decimal(5),
col3 decimal(5, 2)
);
insert into tb_decimal(col1, col2, col3)
values(1234.5678, 12345.12, 123.456);
select * from tb_decimal;
drop table tb_decimal;
/*
결과
col col2 col3
1235 12345 123.46
drop table tb_decimal; 실행 후 제거됨
*/
-- 날짜
create table tb_date(
col1 date,
col2 date
);
create table board(
col1 timestamp, -- 현재날짜와 현재시간을 나타냄
col2 timestamp default now()
);
-- 현재날짜
insert into tb_date(col1, col2)
values(now(), '2022-12-25');
insert into board(col1, col2)
values(now(), default);
insert into board(col1, col2)
values(now(), now());
select * from tb_date;
select * from board;
/*
결과
col1
2023-01-02 17:07:37
col1 col2
2023-01-02 17:53:25 2023-01-02 17:53:25
2023-01-02 17:53:38 2023-01-02 17:53:38
*/
select (값, 컬럼명, 함수, sub query)
from (테이블명, sub query)
use mydb;
-- 특정테이블에 대해서 모든 데이터를 취득
select * from employees;
select * from department;
select employee_id, last_name, hire_date
from employees;
select '이름', employee_id, last_name, hire_date
from employees;
-- 컬럼의 별명(alias)
select employee_id AS "사원번호", last_name as "성", salary "월급"
from employees;
select employee_id AS 사원번호, last_name as "성", salary "월급"
from employees;
-- 산술연산자(+, -, *, /)
select first_name, last_name, salary * 12 as 연봉
from employees;
-- 문자열 합치기
select concat('이름 : ', last_name, ' ', first_name) as 이름
from employees;
-- 연도, 월, 일, 시, 분, 초
create table tb_date(
col1 timestamp
);
insert into tb_date(col1)
values(now());
select * from tb_date;
select date_format(now(), '%Y-%m-%d %H:%i:%s') as "연-월-일 시:분:초"
from tb_date;