1. ๋ฐ์ดํฐ๋ฒ ์ด์ค ์์ฑํ๊ณ ์ฌ์ฉํ๊ธฐ (create)
create database product_db;
use product_db;
2. ํ ์ด๋ธ ๋ง๋ค๊ธฐ (create)
ํ
์ด๋ธ์ ์์ฑํ ๋๋
์ด์ด๋ฆ๊ณผ ๋ฐ์ดํฐํ์
nullํ์ฉ์ฌ๋ถ (PK);
๋ก ์ ์ด์ฃผ๋ฉด ๋๋ค.
create table product (
product_name char(20) not null primary key,
product_price int not null,
product_made char(10),
product_company char(20),
product_num int
);
๋ง์ฝ ์ด์ ์ด๋ฆ์ด๋ ๋ฐ์ดํฐํ์
์ ๋ณ๊ฒฝํ๊ณ ์ถ๋ค๋ฉด
alter table ํ
์ด๋ธ๋ช
change ์์ ์ด์ด๋ฆ ์๋ก์ด์ด์ด๋ฆ ์๋ก์ด๋ฐ์ดํฐํ์
(nullํ์ฉ์ฌ๋ถ) (PK);
๋ก ๋ณ๊ฒฝํ ์ ์๋ค.
alter table product change product_made product_made date not null;
alter table product change product_num product_num tinyint unsigned not null;
date ํ์ ์ ์ซ์ 8์๋ฆฌ๊ฐ YYYY-MM-DD๋ก ๋ฐ์ดํฐ๊ฐ ์ ๋ ฅ๋๋ค. ์ด๋ ๋์ค์ ๊ฒ์(SELECT)ํ ๋ ๋ฒ์๋ฅผ ์ง์ ํ ์ ์์ด์ ํธ๋ฆฌํ๋ค.
tinyint ํ์ ์ 1byte๋ก -128~128์ ์ซ์ ๋ฒ์๊น์ง ์ฌ์ฉ ๊ฐ๋ฅํ๋ค. ๋ง์ฝ ์์๋ฅผ ์ฐ๊ณ ์ถ์ง ์๋ค๋ฉด, tinyint unsigned๋ก 0~255๊น์ง ์ฌ์ฉํ ์๋ ์๋ค.
๋ฐ์ดํฐ ํ์ ์ ๋ํ ๊ธ ๋งํฌ
3. ํ ์ด๋ธ์ ๋ฐ์ดํฐ ์ ๋ ฅ/์์ /์ญ์ ํ๊ธฐ (insert into / delete from / update)
๋ฐ์ดํฐ ์
๋ ฅ์
insert into ํ
์ด๋ธ์ด๋ฆ values (๋ฐ์ดํฐ);
์ด๋, ์
๋ ฅ๋๋ ๋ฐ์ดํฐ๋ primary key ์์ผ๋ก ์๋์ ๋ ฌ๋๋ค. ์๋์ ๋ ฌ๋๋ ์ด์ ๋ PK๋ ์ง์ ๋๋ ์๊ฐ ์ธ๋ฑ์ค๊ฐ ์์ฑ๋์ด ์ ๋ ฌ๋๊ธฐ ๋๋ฌธ์ด๋ค.
insert into product values('๋ฐ๋๋', 1500, '2023-04-07', '๋ธ๋ชฌํธ', 17);
insert into product values('์ฐธ์น๋ง์ ์ผ๊ฐ๊น๋ฐฅ', 900, '2023-04-06', '', 3);
insert into product values('์ง๋ผ๋ฉด ๋งค์ด๋ง', 600, 20230320, '์ค๋๊ธฐ', 37);
insert into product values('ํฌ์ผ๋ชฌ์คํฐ ์คํฐ์ปค', 500, '20230402', '', 1);
์
๋ ฅํ ๋ฐ์ดํฐ๋ฅผ ์ญ์ ํ๊ณ ์ถ๋ค๋ฉด
delete from ํ
์ด๋ธ์ด๋ฆ where PK๊ฐ;
์ ์ฌ์ฉํด์ฃผ๋ฉด ๋๋๋ฐ, PK๊ฐ์ ์ฌ์ฉํด์ผ ์ํ๋ ๋ฐ์ดํฐ๊ฐ ๋ฑ ํ๋๋ง ์ญ์ ๋๋ค.
delete from product where product_name='ํฌ์ผ๋ชฌ์คํฐ ์คํฐ์ปค';
์
๋ ฅํ ๋ฐ์ดํฐ๋ฅผ ์์ ํ๊ณ ์ถ๋ค๋ฉด
update ํ
์ด๋ธ์ด๋ฆ set ์์ ํ๊ณ ์ถ์์ด์ด๋ฆ='์์ ํ๋ฐ์ดํฐ' where ์์ ํ๊ณ ์ถ์์ด์ด๋ฆ='์์ ์ ๋ฐ์ดํฐ';
update product set product_num = 35
WHERE product_name = '์ง๋ผ๋ฉด ๋งค์ด๋ง';
4. ๋ฐ์ดํฐ ์กฐํํ๊ธฐ (show / select)
์ด์ ๋ํ ์ ๋ณด๋ฅผ ๋ณด๊ณ ์ถ๋ค๋ฉด
show columns from ํ
์ด๋ธ์ด๋ฆ;
show columns from product;
๋ฐ์ดํฐ๋ฅผ ์กฐํํ๊ณ ์ถ๋ค๋ฉด
select ๋ฐ์ดํฐ์ด์ด๋ฆ from ํ
์ด๋ธ์ด๋ฆ where ์กฐ๊ฑด์ group by ์ด์ด๋ฆ order by ์ด์ด๋ฆ;
select * from product;
select product_name from product;
select product_name, product_price from product
where product_price < 1000;
select * from product
where product_name like '%๋ผ๋ฉด%';
-- char์ด ์๋ date๋ฅผ ์ฐ๋ ์ด์ : ๋ค์๊ณผ ๊ฐ์ด ๋ ์ง๋ฅผ ํ์ฉํ ๊ฒ์์ด ๊ฐ๋ฅํ๋ค.
select * from product where date(product_made)='2023-04-06';
select * from product where date(product_made) between '20230401' and '20230421';
'๐ฅ๏ธ > DBMS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
SQL Select ํ์ฉ(์๋ธ์ฟผ๋ฆฌ, group by, join) (0) | 2023.04.10 |
---|---|
SQL ์ ์ฝ์กฐ๊ฑด (PK, FK, Unique, Check, Default) (0) | 2023.04.10 |
DB์ค๊ณ) ํ์ ํ ์ด๋ธ๊ณผ ์ฑ์ ํ ์ด๋ธ ์ค๊ณํ๊ธฐ (0) | 2023.04.09 |
[SQL Server] ํ ์ด๋ธ ๋ง๋ค๊ธฐ (0) | 2023.04.07 |
SQL ๋ฐ์ดํฐ ํ์ ์ ๋ฆฌ (0) | 2023.04.07 |