SQL 기초4~9

김태국 (ktaek94)·2023년 2월 16일

SQL

목록 보기
3/6

Order By

  • 실습 환경 만들기
create table celeb (ID int not null auto_increment primary key,NAME varchar(32) not null default '',
    -> BIRTHDAY date,
    -> AGE int,
    -> SEX char(1),
    -> JOB_TITLE varchar(32),
    -> AGENCY varchar(32));
  • celeb 테이블
desc celeb

  • 데이터 추가
insert into celeb values (1,'아이유','1993-05-16',29,'F','가수,탤런트','EDAM엔터테이먼트');
 insert into celeb values (2,'이미주','1994-09-23',28,'F','가수','울림엔터테이먼트');
insert into celeb values (3,'송강','1994-04-23',28,'M','탤런트','나무엑터스');
insert into celeb values (4,'강동원','1981-01-18',41,'M','영화배우,탤런트','YG엔터테이먼트');
insert into celeb values (5,'유재석','1972-08-14',50,'M','MC,개그맨','안테나');
insert into celeb values (6,'차승원','1970-06-07',48,'M','영화배우,모델','YG엔터테이먼트');
insert into celeb values (7,'이수현','1999-05-04',23,'F','가수','YG엔터테이먼트');
select * from celeb

  • ORDER BY: 특정 컬럼 기준으로 오름차순 혹은 내림차순 정렬
    ASC: 오름차순
    DESC: 내림차순
  1. 이름과 나이를 나이순으로 조회 (오름차순)
select age,name from celeb order by age asc;


2. 이름과 나이를 나이순으로 조회 (내림차순)

select age,name from celeb order by age desc;


3. 이름과 나이를 나이와 이름 순으로 정렬하여 조회 (ASC 생략해도 기본은 오름차순

select name,age from celeb order by age,name;


4. 이름과 나이를 나이는 내림차순 이름은 오름차순으로 정렬하여 조회

select name,age from celeb order by age desc,name asc;

비교연산자 (comparison operator)

  • 실습 환경 만들기
use zerobase;
desc celeb;
select * from celeb;
  • 비교 연산자 (=,>,<,>=,<=,<>(크거나 작은),!=)
  1. 나이가 29세인 데이터
select name,age from celeb where age=29 order by age;


2. 나이가 29세가 아닌 데이터

select name,age from celeb where age!=29 order by age;


3. 나이가 29세 보다 큰 데이터 검색

select name,age from celeb where age>29 order by age;


4. 나이가 29세 보다 작은 데이터 검색

select name,age from celeb where age<29 order by age;

논리 연산자 (Logical Operator)

  • 실습 환경
use zerobase;
desc celeb;
select * from celeb
  • 논리 연산자 (AND, OR, NOT, BETWEEN, IN LIKE)
  1. AND : 조건 모두 만족하는 경우 TRUE

나이가 29세이고 성별이 여성인 데이터

select * from celeb where age=29 and sex='F';


남자이고 40세 보다 큰 데이터의 이름의 역순으로 정렬

select * from celeb where age>40 and sex='M' order by name ;


2. OR : 조건을 하나라도 만족하는 경우 TRUE

나이가 25세 보다 작거나 30세보다 큰 데이터

select * from celeb where age<25 or age>30 order by age;

나이가 29세보다 작고 여자이거나, 나이가 30세보다 크고 남자인 데이터를 나이와 성별 순으로 정렬

select * from celeb where (age<29 and sex='F') or (age>30 and sex='M') order by age,sex;

YG엔터 소속이거나 나무엑터스 소속인 연예인 중 나이가 30세 보다 작은 데이터

select * from celeb where ((AGENCY='YG엔터테이먼트') or (AGENCY='나무엑터스')) and age<30;

연습

  1. YG소속이거나 안테나소속인 데이터를 소속사 순으로 정렬
select * from celeb where AGENCY='YG엔터테이먼트' or AGENCY='안테나' order by AGENCY;


2. 남자이면서 YG 소속이거나 30세보다 작은 데이터를 나이,소속사 순으로 정렬

select* from celeb where (sex='M' and AGENCY='YG엔터테이먼트') or age<30 order by age,AGENCY;


3. 아이디가 홀수면서 성별이 남자거나, 아이디가 짝수면서 소속사가 YG인 데이터를 나이순 정렬

select * from celeb where (id%2=1 and sex='M') or (id%2=0 and agency='YG엔터테이먼트') order by age ;


3. NOT : 조건을 만족하지 못하는 경우 TRUE

성별이 여자가 아닌 데이터

select * from celeb where not sex='F';

소속사가 YG면서 남자가 아니거나 직업이 가수면서 소속사가 YG가 아닌 데이터 검색

select * from celeb where (agency='YG엔터테이먼트' and not sex='M') or (job_title='가수' and not agency='YG엔터테이먼트');

생일이 1990년 이후면서 여자가 아니거나, 생일이 1979이전이면서 소속사가 안테나가 아닌 데이터 검색

select * from celeb where (birthday>19891231 and not sex='F') or (birthday<19790101 and not agency='안테나');

연습

  1. 소속사가 YG 가 아니고 나이가 40세 이하인 데이터 이름순으로 정렬
select* from celeb where not agency='YG엔터테이먼트' and age<=40 order by name;


2. 성별이 남자가 아니거나 나이가 30세 이상인 데이터를 나이의 역순으로 정렬

select * from celeb where not sex='M' or age>=30 order by age desc;


3. 직업이 가수가 아니면서 성별이 여자이거나, 나이가 40보다 작지 않으면서 아이디가 홀수인 데이터

select * from celeb where (not job_title='가수' and sex='F') or (not age<40 and id%2=1);

  • BETWEEN : 조건값이 범위 안에 있으면 TRUE

나이가 20세에서 40세 사이의 데이터 검색

select * from celeb where age between 20 and 40;
select * from celeb where age>=20 and age<=40; # 이거랑 같음.

생년월일이 1980년에서 1995년 사이가 아니면서 여자이거나, 소속사가 YG면서 나이가 20세에서 45세 사이가 아닌 데이터 검색

select * from celeb where (not birthday between 19800101 and 19951231 and sex='F') or (agency='YG엔터테이먼트' and not age between 20 and 45);

연습

  1. 30세에서 60세 사이이고 남자인 데이터를 나이순으로 정렬
select* from celeb where age between 30 and 60 and sex='M';


2. 30세에서 60세 사이가 아니거나 YG엔터테이먼트 소속인 데이터를 나이의 역순 정렬

select* from celeb where not age between 30 and 60 or agency='YG엔터테이먼트' order by age desc;

  1. 아이디가 1에서 5사이의 값이면서 여자거나, 아이디가 홀수 면서 남자면서 20세에서 30세 사이인 데이터 조회
select * from celeb where (id between 1 and 5 and sex='F') or (id%2=1 and sex='M' and age between 20 and 30);

  • IN : 목록 안에 조건이 존재하는 경우 True

나이가 28세, 48세 중 하나인 데이터 검색

select * from celeb where age in (28,48);
select * from celeb where age=28 or age=48; 과 같다.


소속사가 나무엑터스,안테나, 울림엔터테이먼트가 아니면서, 성별이 여자거나 나이가 45세 이상

select * from celeb where not agency in ('나무엑터스','안테나','울림엔터테이먼트') and (sex='F' or age>=45);

연습

  1. 아이유,이미주,유재석,송강 중에 소속사가 '나무엑터스' 인 데이터
select * from celeb where name in ('아이유','이미주','유재석','송강') and agency='나무엑터스';


2. 소속사가 안테나,YG엔터테이먼트 중 하나가 아니고, 성별이 여자인 데이터

select * from celeb where not agency in ('안테나','YG엔터테이먼트') and sex='F';


3. 아이유,송강,강동원,차승원 중에 YG엔터 소속이 아니거나 나이가 40세에서 50세 사이인 사람

select * from celeb where name in ('아이유','송강','강동원','차승원') and( not  agency='YG엔터테이먼트' or age between 40 and 50);

  • LIKE : 조건값이 패턴에 맞으면 True

소속사 이름이 YG엔터테이먼트 인 데이터 검색

select * from celeb where agency like 'YG엔터테이먼트';
select * from celeb where agency='YG엔터테이먼트';

'YG'로 시작하는 소속사 이름을 가진 데이터 검색

select * from celeb where agency like 'YG%';

'엔터테이먼트'로 끝나는 소속사 이름을 가진 데이터 검색

select * from celeb where agency like '%엔터테이먼트';

직업에 가수가 포함된 데이터 검색

select * from celeb where job_title like '%가수%';

소속사 이름의 두번째 글자가 G인 데이터 검색 ('_G%') (세번째 글자 시 __G%)

select * from celeb where agency like '_G%';

직업명이 '가'로 시작하고 최소 2글자 이상인 데이터 검색 (가_ 최소 두글자)

select * from celeb where job_title like '가_%';

직업명이 '가'로 시작하고 최소 5글자 이상인 데이터 검색

select * from celeb where job_title like '가____%';

직업명이 '영'으로 시작하고 모델로 끝나는 데이터 검색

select * from celeb where job_title like '영%모델';

영화배우와 탤런트를 병행하는 연예인 검색

select * from celeb where job_title like '%영화배우%' and job_title like '%탤런트%';

직업이 하나 이상인 연예인 중 영화배우 혹은 탤런트가 아닌 연예인

select * from celeb where job_title like '%,%' and not (job_title like '%영화배우%' or job_title like '%탤런트%');

연습

  1. 직업중 가수가 포함되어 있고 성이 이씨인 데이터
select * from celeb where job_title like '%가수%' and name like '이%';


2. 성별이 남자이거나 직업명이 탤런트로 끝나면서 최소 5글자 이상인 데이터

select * from celeb where sex='M' or job_title like '%__탤런트';


3. 이름이 두글자인 데이터

select* from celeb where name like '__';


4. 나이가 30세 이상 50세 이하면서 개그맨이 아닌 데이터

select * from celeb where age between 30 and 50 and not job_title like '%개그맨%';


5. 아이유,이미주,유재석,송강 중에 소속사 이름이 나무 로 시작하는 데이터

select * from celeb where name in ('아이유','이미주','유재석','송강') and agency like '나무%';

  1. 아이유,이미주,송강,이수현 중에서 가수만 직업으로 가졌거나, 가수를 병행하지않고 탤런트를 하는 사람
select * from celeb where name in ('아이유','이미주','송강','이수현') and job_title like '가수' or (not job_title like '%가수%' and job_title like '%탤런트%');

0개의 댓글