와일드카드 사용
where name like '%dar%' //name column에 dar이 들어가는 row, 데이터 값을 정확히 모를 때 사용한다.
where name like 'intro%' //name column에 앞 글자가 intro인 row, 뒷 글자는 상관없는 경우
where name like '%comp' //name coloumn에 뒷 글자가 comp인 row, 앞 글자는 상관없는 경우
where name like '_A_T%S' //name column에 두번쨰 위치에 A를 포함하고 네번째 위치에 T를 포함하며 마지막 위치는 S로 끝나는 문자열
beteween 연산자
mysql> select customer_id, rental_date from rental where rental_date between '2005-06-14' and '2005-06-16';
조인

데카르트 곱
mysql> select c.first_name, c.last_name, a.address from customer as c join address as a;
내부 조인
mysql> select c.first_name, c.last_name, a.address from customer as c join address as a on c.address_id = a.address_id;
mysql> select c.first_name, c.last_name, a.address from customer as c join address as a using (address_id);
세개 이상 테이블 조인
mysql> select c.first_name, c.last_name, ct.city
from customer as c
inner join address as a on c.address_id = a.address_id
inner join city as ct on a.city_id = ct.city_id;
mysql> select c.first_name, c.last_name, addr.city
from customer as c
inner join (select a.address_id, ct.city from address as a
inner join city as ct
on a.city_id = ct.city_id) as addr
on c.address_id = addr.address_id;
셀프 조인
select f.tilte, f_prnt.title as prequel from film as f
inner join film as f_prnt on f_prnt.film_id = f.prequel_film_id
where f.prequel_film_id is not null;
집합 이론
합집합: union 연산, a union b
교집합: intersect 연산, a intersect b
차집합: except 연산, a except b
(a union b) except (a intersect b): a와 b의 합집합에서 교집합을 제외한 부분
두 데이터셋에 대한 집합 연산을 수행할 때는 다음 규칙을 적용해야 한다.
mysql> select 1 as num, 'abc' as str union select 9 as num, 'xyz' as str;

집합 연산자
union 연산자: union 및 union all 연산자는 여러 데이터 집합을 결합할 수 있다. union은 결합된 집합을 정렬하고 중복을 제거함 반면 union all은 그렇지 않다.
intersect 연산자: 복합 쿼리에서 두 쿼리가 겹치지 않는 데이터셋을 반환할 경우 intersect 연산의 결과는 비어있다. intersect 연산자는 중복 행을 제거한다.
except 연산자: except 연산자는 첫번째 쿼리 결과에서 두번째 쿼리 결과와 겹치는 부분을 빼고 반환한다. except 연산자와 except all 연산자에도 차이가 존재하는데 예를 들어 집합 A = {10, 11, 12, 10, 10}, 집합 B = {10, 10}이라고 하자. A except B를 실행하면 {11, 12}가 반환되고 A except all B를 실행하면 {10, 11, 12}를 반환한다. except 연산은 모든 중복 데이터를 제거하는 반면, except all 연산은 집합 B에서 집합 A에 대한 중복 데이터가 발생할 때만 해당 데이터를 제거한다는 것이다.
NULL
mysql> select rental_id, customer_id from rental where return_date is null;
그룹화의 개념
mysql> select customer_id, count(*) from rental group by customer_id;
집계함수 count()는 그룹의 행 수를 세고 별표(*) 문자는 서버가 각 그룹의 모든 행 수를 세도록 한다. 위의 결과를 많은 영화를 대여한 고객 순으로 정렬하려면 order by 2 desc 절을 끝에 추가하면 된다.
데이터를 그룹화할 때 결과셋에 원하지 않는 데이터를 필터링해야 할 수 있다. where 절이 적용된 뒤 group by 절이 실행되므로, 이러한 목적으로 where 절에 필터조건을 추가할 수는 없다. 만약 다음과 같이 쿼리를 작성하면 에러가 발생한다.
mysql> select customer_id, count(*) from rental
where count(*) >= 40 group by customer_id;
mysql> select customer_id, count(*) from rental
-> group by customer_id having count(*) >= 40;
집계 함수
mysql> select max(amount) as max_amt,
min(amount) as min_amt,
avg(amount) as avg_amt,
sum(amount) as sum_amt,
count(*) as num_payments from payment;

이 쿼리의 결과에 따르면 payment 테이블의 16049개 행에서 영화를 대여료로 지불한 최대 금액은 11.99달러, 최소는 0달러, 평균은 4.2달러, 총 대여료는 67416.51달러이다.
만약 전체가 아닌 각 고객에 대해 동일한 5개의 집계 함수를 실행하도록 위의 쿼리를 확장하려면 group by 절을 추가해야 한다.
mysql> select max(amount) as max_amt,
min(amount) as min_amt,
avg(amount) as avg_amt,
sum(amount) as sum_amt,
count(*) as num_payments from payment
group by customer_id;
고유한 값 계산(count() 함수)
mysql> select count(customer_id) as num_rows, count(distinct customer_id)
as num_customers from payment;

서브쿼리
서브쿼리는 다른 sql 구문(포함 구문)에 포함된 쿼리이다. 서브쿼리는 항상 괄호 안에 들어가며 일반적으로 포함 구문보다 먼저 실행된다.
스칼라 서브쿼리
mysql> select city_id, city from city where country_id <>
(select country_id from country where country = 'India');
in 연산자와 not in 연산자, all 연산자
mysql> select country_id from country where country in ('Canada', 'Mexico');
+------------+
| country_id |
+------------+
| 20 |
| 60 |
+------------+
in 연산자는 country 열에서 두개의 문자열을 찾을 수 있는지 여부를 확인한다. 조건이 만족되면 해당 행이 결과셋에 추가된다.
in 연산자를 사용해서 Canada 또는 Mexico에 있는 모든 도시를 반환하는 쿼리
mysql> select city_id, city from city
where country_id in (select country_id from country where country in ('Canada', 'Mexico'));
not in 연산자를 사용하면 'Canada' 또는 'Mexico'에 없는 모든 도시를 표시한다.
all 연산자는 한 집합의 모든 값과 하나의 값을 비교할 수 있다. 예를 들어 무료 영화를 대여한 적이 없는 모든 고객을 찾는 쿼리는 다음과 같다.
mysql> select first_name, last_name from customer
where customer_id <> all (select customer_id from payment where amount = 0);
mysql> select first_name, last_name from customer
where customer_id not in (select customer_id from payment where amount = 0);
상관 서브쿼리
mysql> select c.first_name, c.last_name
from customer as c
where 20 = (select count(*) from rental as r where r.customer_id = c.customer_id);
mysql> select c.first_name, c.last_name
from customer as c
where (select sum(p.amount) from payment as p where p.customer_id = c.customer_id)
between 180 and 240;
exists 연산자
mysql> select c.first_name, c.last_name
from customer as c where exists (select 1 from rental as r
where r.customer_id = c.customer_id and date(r.rental_date) < '2005-05-25');