database를 만들도록 하자.
CREATE DATABASE book_shop;
USE book_shop;
이제 데이터를 준비하도록 하자.
CREATE TABLE books
(
book_id INT NOT NULL AUTO_INCREMENT,
title VARCHAR(100),
author_fname VARCHAR(100),
author_lname VARCHAR(100),
released_year INT,
stock_quantity INT,
pages INT,
PRIMARY KEY(book_id)
);
INSERT INTO books (title, author_fname, author_lname, released_year, stock_quantity, pages)
VALUES
('The Namesake', 'Jhumpa', 'Lahiri', 2003, 32, 291),
('Norse Mythology', 'Neil', 'Gaiman',2016, 43, 304),
('American Gods', 'Neil', 'Gaiman', 2001, 12, 465),
('Interpreter of Maladies', 'Jhumpa', 'Lahiri', 1996, 97, 198),
('A Hologram for the King: A Novel', 'Dave', 'Eggers', 2012, 154, 352),
('The Circle', 'Dave', 'Eggers', 2013, 26, 504),
('The Amazing Adventures of Kavalier & Clay', 'Michael', 'Chabon', 2000, 68, 634),
('Just Kids', 'Patti', 'Smith', 2010, 55, 304),
('A Heartbreaking Work of Staggering Genius', 'Dave', 'Eggers', 2001, 104, 437),
('Coraline', 'Neil', 'Gaiman', 2003, 100, 208),
('What We Talk About When We Talk About Love: Stories', 'Raymond', 'Carver', 1981, 23, 176),
("Where I'm Calling From: Selected Stories", 'Raymond', 'Carver', 1989, 12, 526),
('White Noise', 'Don', 'DeLillo', 1985, 49, 320),
('Cannery Row', 'John', 'Steinbeck', 1945, 95, 181),
('Oblivion: Stories', 'David', 'Foster Wallace', 2004, 172, 329),
('Consider the Lobster', 'David', 'Foster Wallace', 2005, 92, 343);
INSERT INTO books
(title, author_fname, author_lname, released_year, stock_quantity, pages)
VALUES ('10% Happier', 'Dan', 'Harris', 2014, 29, 256),
('fake_book', 'Freida', 'Harris', 2001, 287, 428),
('Lincoln In The Bardo', 'George', 'Saunders', 2017, 1000, 367);
성공했다면 다음의 명령어를 통해서 확인해보도록 하자.
SELECT * FROM books;
+---------+-----------------------------------------------------+--------------+----------------+---------------+----------------+-------+
| book_id | title | author_fname | author_lname | released_year | stock_quantity | pages |
+---------+-----------------------------------------------------+--------------+----------------+---------------+----------------+-------+
| 1 | The Namesake | Jhumpa | Lahiri | 2003 | 32 | 291 |
| 2 | Norse Mythology | Neil | Gaiman | 2016 | 43 | 304 |
| 3 | American Gods | Neil | Gaiman | 2001 | 12 | 465 |
| 4 | Interpreter of Maladies | Jhumpa | Lahiri | 1996 | 97 | 198 |
| 5 | A Hologram for the King: A Novel | Dave | Eggers | 2012 | 154 | 352 |
| 6 | The Circle | Dave | Eggers | 2013 | 26 | 504 |
| 7 | The Amazing Adventures of Kavalier & Clay | Michael | Chabon | 2000 | 68 | 634 |
| 8 | Just Kids | Patti | Smith | 2010 | 55 | 304 |
| 9 | A Heartbreaking Work of Staggering Genius | Dave | Eggers | 2001 | 104 | 437 |
| 10 | Coraline | Neil | Gaiman | 2003 | 100 | 208 |
| 11 | What We Talk About When We Talk About Love: Stories | Raymond | Carver | 1981 | 23 | 176 |
| 12 | Where I'm Calling From: Selected Stories | Raymond | Carver | 1989 | 12 | 526 |
| 13 | White Noise | Don | DeLillo | 1985 | 49 | 320 |
| 14 | Cannery Row | John | Steinbeck | 1945 | 95 | 181 |
| 15 | Oblivion: Stories | David | Foster Wallace | 2004 | 172 | 329 |
| 16 | Consider the Lobster | David | Foster Wallace | 2005 | 92 | 343 |
| 17 | 10% Happier | Dan | Harris | 2014 | 29 | 256 |
| 18 | fake_book | Freida | Harris | 2001 | 287 | 428 |
| 19 | Lincoln In The Bardo | George | Saunders | 2017 | 1000 | 367 |
+---------+-----------------------------------------------------+--------------+----------------+---------------+----------------+-------+
row가 unique한 특징을 가지고 있다고해도, query를 하다보면 동일한 값을 가진 row를 뽑을 수도 있다.
SELECT author_lname FROM books;
+----------------+
| author_lname |
+----------------+
| Lahiri |
| Gaiman |
| Gaiman |
| Lahiri |
| Eggers |
| Eggers |
| Chabon |
| Smith |
| Eggers |
| Gaiman |
| Carver |
| Carver |
| DeLillo |
| Steinbeck |
| Foster Wallace |
| Foster Wallace |
| Harris |
| Harris |
| Saunders |
+----------------+
잘보면 동일한 이름을 가진 결과들이 보인다.
만약, 이렇게 동일한 이름을 가진 결과를 얻고 싶지 않다면 DISTINCT
를 사용하면 된다.
SELECT DISTINCT author_lname FROM books;
+----------------+
| author_lname |
+----------------+
| Lahiri |
| Gaiman |
| Eggers |
| Chabon |
| Smith |
| Carver |
| DeLillo |
| Steinbeck |
| Foster Wallace |
| Harris |
| Saunders |
+----------------+
동일한 값을 가진 row들에 대해서 유일한 값만 뽑아준다.
SELECT released_year FROM books;
+---------------+
| released_year |
+---------------+
| 2003 |
| 2016 |
| 2001 |
| 1996 |
| 2012 |
| 2013 |
| 2000 |
| 2010 |
| 2001 |
| 2003 |
| 1981 |
| 1989 |
| 1985 |
| 1945 |
| 2004 |
| 2005 |
| 2014 |
| 2001 |
| 2017 |
+---------------+
다음의 결과도 잘보면 중복된 값들이 존재하는 것을 알 수 있다. DISTINCT
를 사용하여 유일한 값만 구해보도록 하자.
SELECT DISTINCT released_year FROM books;
+---------------+
| released_year |
+---------------+
| 2003 |
| 2016 |
| 2001 |
| 1996 |
| 2012 |
| 2013 |
| 2000 |
| 2010 |
| 1981 |
| 1989 |
| 1985 |
| 1945 |
| 2004 |
| 2005 |
| 2014 |
| 2017 |
+---------------+
유일한 값만 걸러내는 것을 볼 수 있다.
DISTINCT
는 하나의 column에만 유효한 것이 아니라, 여러 column의 값들을 합친다음 해당 결과에 대해서 DISTINCT
를 할 수 있다.
SELECT CONCAT(author_fname, ' ', author_lname) FROM books;
+-----------------------------------------+
| CONCAT(author_fname, ' ', author_lname) |
+-----------------------------------------+
| Jhumpa Lahiri |
| Neil Gaiman |
| Neil Gaiman |
| Jhumpa Lahiri |
| Dave Eggers |
| Dave Eggers |
| Michael Chabon |
| Patti Smith |
| Dave Eggers |
| Neil Gaiman |
| Raymond Carver |
| Raymond Carver |
| Don DeLillo |
| John Steinbeck |
| David Foster Wallace |
| David Foster Wallace |
| Dan Harris |
| Freida Harris |
| George Saunders |
+-----------------------------------------+
다음의 경우 이름을 합친 결과 일부가 중복된 것을 볼 수 있다. 이를 하나로 합치도록 하여 결과를 내도록 하자.
SELECT DISTINCT CONCAT(author_fname, ' ', author_lname) FROM books;
+-----------------------------------------+
| CONCAT(author_fname, ' ', author_lname) |
+-----------------------------------------+
| Jhumpa Lahiri |
| Neil Gaiman |
| Dave Eggers |
| Michael Chabon |
| Patti Smith |
| Raymond Carver |
| Don DeLillo |
| John Steinbeck |
| David Foster Wallace |
| Dan Harris |
| Freida Harris |
| George Saunders |
+-----------------------------------------+
distinct
한 결과를 얻을 수 있다.
한 가지 조심할 점은 DISTINCT
뒤에 나오는 column의 조합으로 중복 여부를 구한다는 것이다.
SELECT DISTINCT author_fname, author_lname, released_year FROM books;
+--------------+----------------+---------------+
| author_fname | author_lname | released_year |
+--------------+----------------+---------------+
| Jhumpa | Lahiri | 2003 |
| Neil | Gaiman | 2016 |
| Neil | Gaiman | 2001 |
| Jhumpa | Lahiri | 1996 |
| Dave | Eggers | 2012 |
| Dave | Eggers | 2013 |
| Michael | Chabon | 2000 |
| Patti | Smith | 2010 |
| Dave | Eggers | 2001 |
| Neil | Gaiman | 2003 |
| Raymond | Carver | 1981 |
| Raymond | Carver | 1989 |
| Don | DeLillo | 1985 |
| John | Steinbeck | 1945 |
| David | Foster Wallace | 2004 |
| David | Foster Wallace | 2005 |
| Dan | Harris | 2014 |
| Freida | Harris | 2001 |
| George | Saunders | 2017 |
+--------------+----------------+---------------+
위의 예제에서 DISTINCT
의 target이 되는 column은 author_fname
, author_lname
, released_year
이 되는 것이다. 즉, 이 3개 값의 조합으로 유일성을 본다는 것이다. DISTINCT
가 author_fname
앞에 있음에도 불구하고 중복된 값들이 반복해서 사용되는 것만 봐도 알 수 있다.
table에 있는 row들은 기본적으로 순서가 없다. 이는 table이 집합의 개념을 차용하고 있기 때문에 순서가 보장되지 않는다. 따라서, 순서에 맞게 정렬하는 방법이 매우 중요하다.
ORDER BY
를 사용하면 되는데, 사용방법은 다음과 같다.
SELECT <column>
FROM <table_name>
WHERE <condition>
ORDER BY <criteria_column>
criteria_column
을 기준으로 정렬하겠다는 것이다. 단, 주의할 것은 WHERE
은 어차피 선택사항이지만, SELECT ~ FROM
은 필수이므로, SELECT ~ FROM ~
이후에 ORDER BY
를 써야한다. 만약 SELECT ~ ORDER BY ~ FROM ~
으로 쓰면 에러가 발생한다. 또한, 기본적으로 오름차순이다.
SELECT <column>
FROM <table_name>
WHERE <condition>
ORDER BY <criteria_column> ASC
이렇게 된 것이다. ASC
대신에 DESC
로 쓰면 된다.
SELECT <column>
FROM <table_name>
WHERE <condition>
ORDER BY <criteria_column> DESC
이제 예제를 살펴보자, 원래 다음의 data가 있다고 하자.
SELECT book_id, author_fname, author_lname FROM books;
+---------+--------------+----------------+
| book_id | author_fname | author_lname |
+---------+--------------+----------------+
| 1 | Jhumpa | Lahiri |
| 2 | Neil | Gaiman |
| 3 | Neil | Gaiman |
| 4 | Jhumpa | Lahiri |
| 5 | Dave | Eggers |
| 6 | Dave | Eggers |
| 7 | Michael | Chabon |
| 8 | Patti | Smith |
| 9 | Dave | Eggers |
| 10 | Neil | Gaiman |
| 11 | Raymond | Carver |
| 12 | Raymond | Carver |
| 13 | Don | DeLillo |
| 14 | John | Steinbeck |
| 15 | David | Foster Wallace |
| 16 | David | Foster Wallace |
| 17 | Dan | Harris |
| 18 | Freida | Harris |
| 19 | George | Saunders |
+---------+--------------+----------------+
book_id
로 정렬되어 출력된 것을 볼 수 있다.
author_lname
으로 정렬해보도록 하자.
SELECT book_id, author_fname, author_lname FROM books ORDER BY author_lname;
+---------+--------------+----------------+
| book_id | author_fname | author_lname |
+---------+--------------+----------------+
| 12 | Raymond | Carver |
| 11 | Raymond | Carver |
| 7 | Michael | Chabon |
| 13 | Don | DeLillo |
| 5 | Dave | Eggers |
| 6 | Dave | Eggers |
| 9 | Dave | Eggers |
| 16 | David | Foster Wallace |
| 15 | David | Foster Wallace |
| 2 | Neil | Gaiman |
| 10 | Neil | Gaiman |
| 3 | Neil | Gaiman |
| 17 | Dan | Harris |
| 18 | Freida | Harris |
| 4 | Jhumpa | Lahiri |
| 1 | Jhumpa | Lahiri |
| 19 | George | Saunders |
| 8 | Patti | Smith |
| 14 | John | Steinbeck |
+---------+--------------+----------------+
알파벳 순서로 정렬되는 것을 볼 수 있다.
author_fname
으로 정렬할 수도 있다.
SELECT book_id, author_fname, author_lname FROM books ORDER BY author_fname;
+---------+--------------+----------------+
| book_id | author_fname | author_lname |
+---------+--------------+----------------+
| 17 | Dan | Harris |
| 5 | Dave | Eggers |
| 6 | Dave | Eggers |
| 9 | Dave | Eggers |
| 16 | David | Foster Wallace |
| 15 | David | Foster Wallace |
| 13 | Don | DeLillo |
| 18 | Freida | Harris |
| 19 | George | Saunders |
| 4 | Jhumpa | Lahiri |
| 1 | Jhumpa | Lahiri |
| 14 | John | Steinbeck |
| 7 | Michael | Chabon |
| 10 | Neil | Gaiman |
| 3 | Neil | Gaiman |
| 2 | Neil | Gaiman |
| 8 | Patti | Smith |
| 12 | Raymond | Carver |
| 11 | Raymond | Carver |
+---------+--------------+----------------+
오름차순으로 정렬되었는데, 내림차순으로 하고 싶다면 ORDER BY ~
뒤에 DESC
를 추가해주면 된다.
SELECT book_id, author_fname, author_lname FROM books ORDER BY author_fname DESC;
+---------+--------------+----------------+
| book_id | author_fname | author_lname |
+---------+--------------+----------------+
| 12 | Raymond | Carver |
| 11 | Raymond | Carver |
| 8 | Patti | Smith |
| 2 | Neil | Gaiman |
| 10 | Neil | Gaiman |
| 3 | Neil | Gaiman |
| 7 | Michael | Chabon |
| 14 | John | Steinbeck |
| 4 | Jhumpa | Lahiri |
| 1 | Jhumpa | Lahiri |
| 19 | George | Saunders |
| 18 | Freida | Harris |
| 13 | Don | DeLillo |
| 15 | David | Foster Wallace |
| 16 | David | Foster Wallace |
| 6 | Dave | Eggers |
| 5 | Dave | Eggers |
| 9 | Dave | Eggers |
| 17 | Dan | Harris |
+---------+--------------+----------------+
내림차순으로 정렬된 것을 볼 수 있다.
ORDER BY
로 선택한 column이 굳이 SELECT
에 있을 필요는 없다.
SELECT title, pages FROM books ORDER BY released_year;
+-----------------------------------------------------+-------+
| title | pages |
+-----------------------------------------------------+-------+
| Cannery Row | 181 |
| What We Talk About When We Talk About Love: Stories | 176 |
| White Noise | 320 |
| Where I'm Calling From: Selected Stories | 526 |
| Interpreter of Maladies | 198 |
| The Amazing Adventures of Kavalier & Clay | 634 |
| fake_book | 428 |
| American Gods | 465 |
| A Heartbreaking Work of Staggering Genius | 437 |
| Coraline | 208 |
| The Namesake | 291 |
| Oblivion: Stories | 329 |
| Consider the Lobster | 343 |
| Just Kids | 304 |
| A Hologram for the King: A Novel | 352 |
| The Circle | 504 |
| 10% Happier | 256 |
| Norse Mythology | 304 |
| Lincoln In The Bardo | 367 |
+-----------------------------------------------------+-------+
released_year
로 정렬하였지만 그 SELECT
문에는 released_yead
이 없는 것을 볼 수 있다. 그러나, 추천하진 않는다. 디버깅이 어려워지기 때문이다.
특정 SELECT
문에 있는 특정 위치의 column을 ORDER BY
의 기준으로 선정할 수도 있는데, 다음과 같다.
SELECT title, author_fname, author_lname
FROM books
ORDER BY 2;
+-----------------------------------------------------+--------------+----------------+
| title | author_fname | author_lname |
+-----------------------------------------------------+--------------+----------------+
| 10% Happier | Dan | Harris |
| A Hologram for the King: A Novel | Dave | Eggers |
| The Circle | Dave | Eggers |
| A Heartbreaking Work of Staggering Genius | Dave | Eggers |
| Consider the Lobster | David | Foster Wallace |
| Oblivion: Stories | David | Foster Wallace |
| White Noise | Don | DeLillo |
| fake_book | Freida | Harris |
| Lincoln In The Bardo | George | Saunders |
| Interpreter of Maladies | Jhumpa | Lahiri |
| The Namesake | Jhumpa | Lahiri |
| Cannery Row | John | Steinbeck |
| The Amazing Adventures of Kavalier & Clay | Michael | Chabon |
| Coraline | Neil | Gaiman |
| American Gods | Neil | Gaiman |
| Norse Mythology | Neil | Gaiman |
| Just Kids | Patti | Smith |
| Where I'm Calling From: Selected Stories | Raymond | Carver |
| What We Talk About When We Talk About Love: Stories | Raymond | Carver |
+-----------------------------------------------------+--------------+----------------+
2라는 값은 SELECT
문에 있는 두번째 column을 말하는 것으로 author_fname
기준으로 정렬하라는 것이다. 결과를 보면 author_fname
기준으로 정렬된 것을 볼 수 있다.
ORDER BY
는 또한, 두 개 이상의 column값 정렬 기준으로 삼을 수 있다. 두 개 이상의 column이 ORDER BY
에 걸릴 경우 순서대로 정렬한다고 생각하면 된다.
SELECT author_fname, author_lname
FROM books
ORDER BY author_lname, author_fname;
+--------------+----------------+
| author_fname | author_lname |
+--------------+----------------+
| Raymond | Carver |
| Raymond | Carver |
| Michael | Chabon |
| Don | DeLillo |
| Dave | Eggers |
| Dave | Eggers |
| Dave | Eggers |
| David | Foster Wallace |
| David | Foster Wallace |
| Neil | Gaiman |
| Neil | Gaiman |
| Neil | Gaiman |
| Dan | Harris |
| Freida | Harris |
| Jhumpa | Lahiri |
| Jhumpa | Lahiri |
| George | Saunders |
| Patti | Smith |
| John | Steinbeck |
+--------------+----------------+
author_lname
기준으로 먼저 정렬하고, author_fname
으로 정렬하는 것이다. 따라서 Harries
의 경우 Dan
이 먼저나오게 되는 것이다.
단, 주의할 것은 ORDER BY
에 여러 column을 기준으로 정렬할 경우, ASC
, DESC
기준은 각 column마다 적용된다는 것이다.
SELECT author_lname, released_year, title
FROM books
ORDER BY author_lname, released_year DESC;
author_lname
은 여전 오름차순으로 정렬되었지만 released YEAR
은 내림차순으로 정렬된 것을 볼 수 있다.
합성한 column을 기준으로도 정렬이 가능하다.
SELECT CONCAT(author_fname, ' ', author_lname) AS author FROM books;
+----------------------+
| author |
+----------------------+
| Jhumpa Lahiri |
| Neil Gaiman |
| Neil Gaiman |
| Jhumpa Lahiri |
| Dave Eggers |
| Dave Eggers |
| Michael Chabon |
| Patti Smith |
| Dave Eggers |
| Neil Gaiman |
| Raymond Carver |
| Raymond Carver |
| Don DeLillo |
| John Steinbeck |
| David Foster Wallace |
| David Foster Wallace |
| Dan Harris |
| Freida Harris |
| George Saunders |
+----------------------+
다음과 같이 작가의 이름을 합성한 author
결과를 ORDER BY
로 정렬시킬 수 있다.
SELECT CONCAT(author_fname, ' ', author_lname) AS author FROM books ORDER BY author;
+----------------------+
| author |
+----------------------+
| Dan Harris |
| Dave Eggers |
| Dave Eggers |
| Dave Eggers |
| David Foster Wallace |
| David Foster Wallace |
| Don DeLillo |
| Freida Harris |
| George Saunders |
| Jhumpa Lahiri |
| Jhumpa Lahiri |
| John Steinbeck |
| Michael Chabon |
| Neil Gaiman |
| Neil Gaiman |
| Neil Gaiman |
| Patti Smith |
| Raymond Carver |
| Raymond Carver |
+----------------------+
별칭인 author
라는 속성을 이용하여 오름차순으로 정렬이 가능한 것이다.
결과의 수를 LIMIT을 통해 제한할 수 있다. 주로 ORDER BY
와 함께 나오게되어 출력되는 갯수를 조정할 수 있다. 즉, 정렬했을 때 처음 5개만 가져오도록 할 수 있는 것이다.
SELECT <columns...>
FROM <table_name>
WHERE <condition>
ORDER BY <criteria_column>
LIMIT <limit_count>
limit_count
갯수만큼 출력되는 결과의 수를 제한하는 것이다.
SELECT book_id, title, released_year FROM books ORDER BY released_year LIMIT 5;
+---------+-----------------------------------------------------+---------------+
| book_id | title | released_year |
+---------+-----------------------------------------------------+---------------+
| 14 | Cannery Row | 1945 |
| 11 | What We Talk About When We Talk About Love: Stories | 1981 |
| 13 | White Noise | 1985 |
| 12 | Where I'm Calling From: Selected Stories | 1989 |
| 4 | Interpreter of Maladies | 1996 |
+---------+-----------------------------------------------------+---------------+
released_year
을 기준으로 오름차순 정렬한 다음 LIMIT
에 있는 5가지만 가져오는 것이다.
최신순으로 정렬하고 싶다면 DESC
를 써서 쓸 수도 있다.
SELECT book_id, title, released_year FROM books ORDER BY released_year DESC LIMIT 10;
+---------+----------------------------------+---------------+
| book_id | title | released_year |
+---------+----------------------------------+---------------+
| 19 | Lincoln In The Bardo | 2017 |
| 2 | Norse Mythology | 2016 |
| 17 | 10% Happier | 2014 |
| 6 | The Circle | 2013 |
| 5 | A Hologram for the King: A Novel | 2012 |
| 8 | Just Kids | 2010 |
| 16 | Consider the Lobster | 2005 |
| 15 | Oblivion: Stories | 2004 |
| 10 | Coraline | 2003 |
| 1 | The Namesake | 2003 |
+---------+----------------------------------+---------------+
LIMIT
은 range로도 가져올 수도 있다.
LIMIT start,length;
start
부터 length
만큼 가져오는 것이다. 단, start는 0부터이다.
SELECT book_id, title, released_year FROM books ORDER BY released_year DESC LIMIT 0,5;
+---------+----------------------------------+---------------+
| book_id | title | released_year |
+---------+----------------------------------+---------------+
| 19 | Lincoln In The Bardo | 2017 |
| 2 | Norse Mythology | 2016 |
| 17 | 10% Happier | 2014 |
| 6 | The Circle | 2013 |
| 5 | A Hologram for the King: A Novel | 2012 |
+---------+----------------------------------+---------------+
0부터 5개를 가져온 것을 볼 수 있다. 여기서 start부분이 1이면 결과가 달라진다.
SELECT book_id, title, released_year FROM books ORDER BY released_year DESC LIMIT 1,5;
+---------+----------------------------------+---------------+
| book_id | title | released_year |
+---------+----------------------------------+---------------+
| 2 | Norse Mythology | 2016 |
| 17 | 10% Happier | 2014 |
| 6 | The Circle | 2013 |
| 5 | A Hologram for the King: A Novel | 2012 |
| 8 | Just Kids | 2010 |
+---------+----------------------------------+---------------+
book_id
2부터 5개를 가져온 것을 볼 수 있다. 조금 헷갈릴 수 있는데, LIMIT
에서의 start
는 0부터 시작이라고 생각하거나, start
은 포함하지 않고 다음꺼부터 length
만큼 가져온다고 생각하면 된다. 이렇게 된 이유는 사실 LIMIT 3
이라고 하는 것은 LIMIT 0,3
과 같아야 하기 때문에 만든 룰이다.
length
값을 실제의 row길이보다 넘는 값을 써도 문제 없다.
SELECT book_id, title, released_year FROM books ORDER BY released_year DESC LIMIT 3,12312321;
+---------+-----------------------------------------------------+---------------+
| book_id | title | released_year |
+---------+-----------------------------------------------------+---------------+
| 6 | The Circle | 2013 |
| 5 | A Hologram for the King: A Novel | 2012 |
| 8 | Just Kids | 2010 |
| 16 | Consider the Lobster | 2005 |
| 15 | Oblivion: Stories | 2004 |
| 10 | Coraline | 2003 |
| 1 | The Namesake | 2003 |
| 3 | American Gods | 2001 |
| 9 | A Heartbreaking Work of Staggering Genius | 2001 |
| 18 | fake_book | 2001 |
| 7 | The Amazing Adventures of Kavalier & Clay | 2000 |
| 4 | Interpreter of Maladies | 1996 |
| 12 | Where I'm Calling From: Selected Stories | 1989 |
| 13 | White Noise | 1985 |
| 11 | What We Talk About When We Talk About Love: Stories | 1981 |
| 14 | Cannery Row | 1945 |
+---------+-----------------------------------------------------+---------------+
에러없이 query되는 것을 알 수 있다.
기본 검색을 더 쉽게 만들어주는 연산자이다.
가령 작가의 첫번째 이름이 David
인 row를 얻어오자고 하자.
SELECT title, author_fname, author_lname FROM books WHERE author_fname='David';
+----------------------+--------------+----------------+
| title | author_fname | author_lname |
+----------------------+--------------+----------------+
| Oblivion: Stories | David | Foster Wallace |
| Consider the Lobster | David | Foster Wallace |
+----------------------+--------------+----------------+
그런데 검색은 사실 이렇게 정확히 이루어지는 것보다, 좀 더 유사한 값을 검색함으로서 이루어지는 경우가 많다. 갈ㅇ David
가 아니라 Dav
나 Dave
, Dan
같은 경우이다.
이때 사용하는 것이 LIKE
인데, WHERE
과 함께 사용된다.
WHERE <column> LIKE <condition>;
column
에 LIKE
의 condition을 적용하는 것이다.
LIKE
에는 정규 표현식을 사용할 수 있는데, 가령 작가의 첫번째 이름에 da
라는 글자가 있어야 한다면 다음과 같이 쓸 수 있다.
WHERE author_fname LIKE '%da%';
%
는 wildcard라는 것으로 어떤 문자, 숫자도 0개 이상이 오면 된다는 말이다. 즉, 앞 뒤로 무슨 글자가 오든 da
가 있어야 한다는 것을 의미한다.
SELECT title, author_fname, author_lname FROM books;
+-----------------------------------------------------+--------------+----------------+
| title | author_fname | author_lname |
+-----------------------------------------------------+--------------+----------------+
| The Namesake | Jhumpa | Lahiri |
| Norse Mythology | Neil | Gaiman |
| American Gods | Neil | Gaiman |
| Interpreter of Maladies | Jhumpa | Lahiri |
| A Hologram for the King: A Novel | Dave | Eggers |
| The Circle | Dave | Eggers |
| The Amazing Adventures of Kavalier & Clay | Michael | Chabon |
| Just Kids | Patti | Smith |
| A Heartbreaking Work of Staggering Genius | Dave | Eggers |
| Coraline | Neil | Gaiman |
| What We Talk About When We Talk About Love: Stories | Raymond | Carver |
| Where I'm Calling From: Selected Stories | Raymond | Carver |
| White Noise | Don | DeLillo |
| Cannery Row | John | Steinbeck |
| Oblivion: Stories | David | Foster Wallace |
| Consider the Lobster | David | Foster Wallace |
| 10% Happier | Dan | Harris |
| fake_book | Freida | Harris |
| Lincoln In The Bardo | George | Saunders |
+-----------------------------------------------------+--------------+----------------+
위의 예제에서 author_fname
에서 da
값을 가진 이름을 추출해내보자.
SELECT title, author_fname, author_lname
FROM books
WHERE author_fname
LIKE '%da%';
+-------------------------------------------+--------------+----------------+
| title | author_fname | author_lname |
+-------------------------------------------+--------------+----------------+
| A Hologram for the King: A Novel | Dave | Eggers |
| The Circle | Dave | Eggers |
| A Heartbreaking Work of Staggering Genius | Dave | Eggers |
| Oblivion: Stories | David | Foster Wallace |
| Consider the Lobster | David | Foster Wallace |
| 10% Happier | Dan | Harris |
| fake_book | Freida | Harris |
+-------------------------------------------+--------------+----------------+
Dave
, David
, Dan
, Freida
가 나오는 것을 볼 수 있다.
다음으로 제목에 :
기호가 있는 row가 있는 지 확인해보도록 하자.
SELECT title FROM books WHERE title LIKE '%:%';
+-----------------------------------------------------+
| title |
+-----------------------------------------------------+
| A Hologram for the King: A Novel |
| What We Talk About When We Talk About Love: Stories |
| Where I'm Calling From: Selected Stories |
| Oblivion: Stories |
+-----------------------------------------------------+
title column에서 :
을 가진 text들만 가져온 것을 볼 수 있다.
추가적으로 %
는 wildcard로 0개 이상의 문자, 숫자를 의미하여 그냥 뭐든 와도된다는 것을 의미하지만, _
는 정확히 단 1개의 문자만을 의미한다.
가령, author_fname
이 4개의 문자로만 구성된 것을 찾고 싶다면 다음과 같이 쓸 수 있다.
SELECT * FROM books WHERE author_fname LIKE '____';
+---------+-------------------------------------------+--------------+--------------+---------------+----------------+-------+
| book_id | title | author_fname | author_lname | released_year | stock_quantity | pages |
+---------+-------------------------------------------+--------------+--------------+---------------+----------------+-------+
| 2 | Norse Mythology | Neil | Gaiman | 2016 | 43 | 304 |
| 3 | American Gods | Neil | Gaiman | 2001 | 12 | 465 |
| 5 | A Hologram for the King: A Novel | Dave | Eggers | 2012 | 154 | 352 |
| 6 | The Circle | Dave | Eggers | 2013 | 26 | 504 |
| 9 | A Heartbreaking Work of Staggering Genius | Dave | Eggers | 2001 | 104 | 437 |
| 10 | Coraline | Neil | Gaiman | 2003 | 100 | 208 |
| 14 | Cannery Row | John | Steinbeck | 1945 | 95 | 181 |
+---------+-------------------------------------------+--------------+--------------+---------------+----------------+-------+
wildcard escape를 원할 수도 있다. 즉, LIKE를 통해서 %
문자를 검색하고 싶었는데, %
가 wildcard로 동작되어서는 안된다. 따라서, 이를 위해서 wildcard escape를 사용하는 것이다. \%
로 쓰면 된다.
SELECT * FROM books WHERE title LIKE '%\%%';
+---------+-------------+--------------+--------------+---------------+----------------+-------+
| book_id | title | author_fname | author_lname | released_year | stock_quantity | pages |
+---------+-------------+--------------+--------------+---------------+----------------+-------+
| 17 | 10% Happier | Dan | Harris | 2014 | 29 | 256 |
+---------+-------------+--------------+--------------+---------------+----------------+-------+
%/%%
는 앞 뒤에 무슨 문자든 %
만 있으면 된다라는 의미이다.