SQL_기본

Updated:

DB

  • 1950년대 미군이 처음 구축
  • 복수 사용자의 요구에 대응해서 데이터를 받아들이고 저장, 공급하기 위해서
    일정한 구조에 따라 편성된 데이터의 집합

  • 데이터 베이스의 구조적 특징
    • 통합성(integreted) : 동일 데이터가 중복되지 않음
    • 저장됨(stored) : 컴퓨터 기술을 바탕으로 자장 매체에 저장됨
    • 공용성(shared) : 여러 사용자가 다양한 목적으로 사용할 수 있음
    • 변화성(changeable) : 새로운 데이터의 삽입, 기존 데이터의 삭제 및 변경 가능
  • 데이터 베이스의 종류
    • 계층형DB: 트리 구조를 이용해서 상로 관계를 계층적으로 정의함
    • 네트워크형 DB : 그래프 구조를 이용해서 상호 관계를 계층적으로 정의함
    • 관계형 DB : 계층형과 네트워크형의 복잡한 구조를 단순화 시킨 모델. 단순한 표를 이용하여
      데이터의 상호 관계를 정의함.
    • 객체 지향형 DB : 객체의 개념을 도입함

sql

  • Structured Query Language
  • 관계형 데이터 베이스(RDB, Relational Data Base) 관리 체계
    1 데이터 정의(DDL) : 데이터 베이스를 정의, 생성, 변경, 삭제 하는것
    2 데이터 조작(DML) : 질의 (query)를 통해서 데이터를 불러오고 처리 하는 것
    3 데이터 제어(DCL) : 데이터의 보안, 무결성, 병행 수행 제어 등을 하는 것

  • 경량 데이터 베이스 용

    SQLite

  • 데이터 베이스 서버 구축용

    MySQL

  • 데이터 베이스의 활용

    CPM(Customer Relationship Management) “고객관계관리”라고도 한다. 고객과 관련된 내외부 자료를 분석, 톡합하여 고객 중심 자원을 극대화 하고 이를 토대로 고객 특성에 맞게 마케팅 활동을 계획, 지원, 평가하는 과정

    SCM(Supply Chain Management) 인사, 재무, 생산 등 기업의 전 분야에 걸쳐 독립적으로 운영되던 관리 시스템의 경영자원을 하나의 통합 시스템으로 재구축함으로서 생산성을 극대화 하려는 경영혁신기법을 의미한다.

    ERP(Enterprise Resource Planning) 인사, 재무, 생산 등 기업의 전 분야에 걸처 독립적으로 운영되던 관리 시스템의 경영자원을 하나의 통합 시스템으로 재구축함으로서 생산성을 극대화 하려는 경영혁신기법을 의미한다.

    BI(Business Intelligence) 기업이 보유하고 있는 수많은 데이터를 정리하고 분석해 기업의 의사결정에 활용하는 일련의 프로세스를 말함. 기업의 사용자가 더 좋은 의사결정을 하도록 데이터를 수집, 저장, 분석, 접근을 지원하는 응용 시스템과 기술이다.

    KMS(Knowledge Management System) 기업의 환경이 물품을 주로 생산하던 산업사회에서, 지적 재산의 중요성이 커지는 지식사회로 극격히 이동함에 따라, 기업 경영을 지식이라는 관점에서 새롭게 존명하는 접근방식. 의사결정의 주체인 인적 자원이 떠나면 그가 갖고 있던 지식 자원도 함께 떠난다.

  • 여러테이블로 분산하는 이유

    하나의 테이블로 통합해 놓으면 중복이 발생하며 이는 비 효율적인 방법이다.

문법

-- 주석

/* 
주석
여러줄
*/

select * from country;
-- country 테이블 전체 조회

select * from country order by continent;
-- continuent를 기준으로 오름차순

select name from country;
-- country 테이블 Name 조회

select name, surfacearea, population, gnp from country order by surfacearea desc;
-- surfacearea 를 내림차순으로 name, surfacearea, population, gnp 출력

select name, surfacearea, continent, population, gnp from country order by continent asc, population desc;
-- continent 를 오름차순으로 한후 population 내림차순 name, surfacearea, continent, population, gnp 출력

select name, lifeExpectancy as 'Life Expectancy' from country;
-- 별칭 지어주기

select name as Country, population/10000 as 'population(만)' from country order by population desc;
-- 인구수를 (만)부터 나타내기

--count
select count(*) from country;
-- country 테이블의 컬럼 수 출력

--limit
select * from country order by gnp desc limit 5;
-- limit을 사용해서 위에서 5개의 컬럼만 출력해준다

--offset
select * from country order by name limit 5 offset 5;
-- offset을 사용하면 위에서부터 5개를 건너뛰고 출력해준다

-- where

select name, population, gnp from country where population<100000 order by gnp desc;
-- 인구가 100000만보다 작은 국가의 gnp 내림차순

select name, population, gnp, surfacearea from country where population > 50000000 order by population desc;
-- 인구가 50000000 보다 많은 지역에서 population 내림차순

select name, continent, population from country where population < 100000 and continent = 'Oceania';
-- Oceania 국가 중에서 인구가 100000보다 작은 국가의 name, continent, population을 출력

--between
select name, population from country where population between 1000 and 10000 order by population desc;
-- 1000과 10000사이의 인구를 가진 국가 name, population을 인구수 내림차순으로 출력

-- %
select name, continent from country where name like '%island';
-- island로 name이 끝나는 country의 name, continent출력

select name, continent from country where name like 'ja%';
-- ja로 name이 시작하는 country의 name, continent출력

select name, continent from country where name like '%island%';
-- island를 name에 포함하는 country name, continent 출

select * from country where name like '%korea%';
-- korea를 포함하는 나라 출력

-- in
select name, continent from country where continent in('Asia', 'Europe');



--distinct(중복제거)
select distinct countrycode, name from city;

select name from (select code, name, continent from country);

select name, population / 1000 as pop_1000 from (select * from country where name like '%korea%');


--====================================================================

--다음 언어를 주요 언어로 사용하는 나라의 수

select count(*) as 'country 수', language 
from(
    select countrycode,max(percentage),language 
    from countrylanguage 
    group by countrycode) 
group by language 
order by count(*) desc
limit 10;

-- 대륙별 나라수, 인구 수, gnp평균

select continent, count(*) as '나라 수', sum(population) as '인구 수', round(avg(gnp)) as 'gnp평균' 
from country 
group by continent 
order by sum(population) desc;

--각 언어를 사용하는 인구

select round(sum(b.population * a.percentage / 100)) as '인구수', a.language from countrylanguage a, country b 
where a.countrycode == b.code 
group by language 
order by round(sum(b.population * a.percentage / 100)) desc;

-- 군주국

select name, population from country where governmentform like 'Monarchy%';

  • 2020_07_08
select * from country;
select name, region from country where region like '%Asia';
--region이 Asia로 끝나는 country의 name, region

select name, continent from country where continent like 'North%';
--region이 North로 시작하는 country의 name, continent

select name, governmentform from country where governmentform like '__o%';
--governmentform의 세번째 글자가 o인 country의 name, governmentform

select * from country where name in('south korea', 'japan', 'china');
-- name이 'south korea', 'japan', 'china'인 country

select * from city;
select name, district from city;

distinct 중복제거


select distinct district from city;
-- district의 중복을 제거하면서 출력

select surfacearea from (select * from country where name like '%Korea');

--create class6라는 테이블을 만든다
create table class6(my_name text, my_team text, score int);

--현재 db에 있는 테이블들을 조회한다
select * from sqlite_master where type = 'table';

select * from class6;

insert into class6 values('임준형','김지원',100);
-- class6 에 컬럼 추가

drop table class6;
-- class6 table 제거

insert into class6(my_name,my_team) values('임준형','김지원');
-- 지정되지 않은 속성값을 null이 된다.

select * from practice.Artist;
-- practice DB의 Artist 테이블에 접근

insert into class6(my_name, score) select name, artistid from practice.Artist limit 5;
-- practice DB에 있는 Artist테이블에서 위에서 5개의 값을 가져와서 class6테이블의 컬럼으로 추가

drop table test;
create table test(a text, b text, c int);
-- test table 생성

insert into test(a,b,c) values('text_1', 'text_11', 123);
insert into test(a,b,c) values('text_2', 'text_22', 456);
insert into test(a,b,c) values('text_3', 'text_33', 789);
-- 컬럼추가 

select * from test;

update


update test set c = 1234 where a = 'text_1';
-- a가 text_1 인 컴럼의 c를 1234로 변경

select * from test;

delete


delete from test where c is not null;
-- c가 not null이라면 컴럼 제거

select * from test;

-- test테이블을 삭제한다

drop

drop table test;

drop table test;
create table test(
id integer,
study_time real,
name var(10),
address varchar(255),
class integer,
hobby varchar(255),
comment blob);
-- 테이블 생성

select * from test;

not null

create table test_1(
a integer not null,
b varchar(255));

insert into test_1(a,b) values(1,'a');
-- 정상작동
insert into test_1(a,b) values(null,'b');
-- 에러표시

select * from test_1;

default, unique

create table test_2(
a integer default 1,
b varchar(255) unique not null);

insert into test_2(b) values('b');
-- a에 default로 1이 들어간다
insert into test_2(a,b) values(1,'b');
-- 이미 'b'가 있기 때문에 에러
insert into test_2(a,b) values(1,'c');
-- 정상작동
select * from test_2;

autoincrement(일련번호)

create table store_a(
client_id integer primary key autoincrement,
menu_1 varchar(255),
menu_2 varchar(255));

insert into store_a(menu_1,menu_2) values('밥','김치');
insert into store_a(menu_1,menu_2) values('라면','단무지');
insert into store_a(menu_1,menu_2) values('김밤','떡볶이');

select * from store_a;

ALTER

alter table store_a add column menu_3 varchar(100);

select * from store_a;

-- 다른테이블에서 값 가져오기

create table store_b as select menu_1,menu_2,menu_3 from store_a;

select * from store_b;

기본함수

select count(*) from country;
select count(population) from country;
select count(*) from country group by continent;
select count(distinct continent) from country;
select avg(population) from country where region = 'Western Europe';
select min(population), max(population) from country where region = 'Western Europe';

Leave a comment