*
: allWHERE
: 조건에 부합하는 데이터 조회열1 and 열2
가 아니라, 열1, 열2
로 가져오자MOD(X, Y)
: X에서 Y를 나눈 나머지값을 반환하는 함수DISTINCT
또는 GROUP BY
COUNT({컬럼명})
^
SUBSTRING(문자열, 시작할 자리위치, 가져올개수)
COUNT(city)
이 아닌SELECT COUNT(*)-COUNT(DISTINCT(city)) FROM station;
로 하면, city 컬럼에 결측치가 존재하는 경우에 답이 COUNT(city)
에서 뺀 값과 값이 달라지지 않을까? 혹은 상관이 없으려나?
COUNT(*)
: 결측치를 포함한 총 행의 수COUNT(column)
: 결측치를 제외한 행의 수DISTINCT(city)
를 할 경우 null을 포함하지만 COUNT(DISTINCT(city))
을 할 경우 null을 제외한 수를 셈SELECT CITY, LENGTH(CITY)
FROM STATION
ORDER BY LENGTH(CITY)
# limit 1; 일때
Roy 3
# limit 2; 일때
Roy 3
Amo 3
# limit 3;일 때
Amo 3
Lee 3
Roy 3
REGEXP
와 REGEXP_LIKE
의 차이점도 궁금합니다. 우선 찾아보겠습니다.Query all columns for all American cities in the CITY table with populations larger than 100000. The CountryCode for America is USA.
SELECT * FROM CITY WHERE POPULATION > 100000 AND COUNTRYCODE = 'USA';
Query the NAME field for all American cities in the CITY table with populations larger than 120000. The CountryCode for America is USA.
SELECT NAME FROM CITY WHERE POPULATION > 120000 AND COUNTRYCODE = 'USA';
Scottsdale
Corona
Concord
Cedar Rapids
Query all columns (attributes) for every row in the CITY table.
SELECT * FROM CITY;
Query all columns for a city in CITY with the ID 1661.
SELECT * FROM CITY WHERE ID = '1661';
SELECT *
FROM CITY
WHERE ID = 1661;
Query all attributes of every Japanese city in the CITY table. The COUNTRYCODE for Japan is JPN.
SELECT * FROM CITY WHERE COUNTRYCODE = 'JPN'
Query the names of all the Japanese cities in the CITY table. The COUNTRYCODE for Japan is JPN.
SELECT NAME FROM CITY WHERE COUNTRYCODE = 'JPN';
Query a list of CITY and STATE from the STATION table.
SELECT CITY, STATE FROM STATION;
SELECT CITY AND STATE FROM STATION;
하면 틀린다!Query a list of CITY names from STATION for cities that have an even ID number. Print the results in any order, but exclude duplicates from the answer.
SELECT DISTINCT CITY FROM STATION WHERE MOD(ID, 2) = 0;
'^[AEIOU]$
으로 작성했던것. 그런데 쿼리에 오류가 떠서 문자열 시작과 끝을 각각 and로 나누니, 성공!Find the difference between the total number of CITY entries in the table and the number of distinct CITY entries in the table.
if there are three records in the table with CITY values 'New York', 'New York', 'Bengalaru', there are 2 different city names: 'New York' and 'Bengalaru'. The query returns.
SELECT COUNT(CITY) - COUNT(DISTINCT(CITY)) FROM STATION;
SELECT COUNT(CITY) - COUNT(DISTINCT CITY)
FROM STATION;
Query the two cities in STATION with the shortest and longest CITY names, as well as their respective lengths (i.e.: number of characters in the name). If there is more than one smallest or largest city, choose the one that comes first when ordered alphabetically.
CITY has four entries: DEF, ABC, PQRS and WXY.
ABC 3
PQRS 4
You can write two separate queries to get the desired output. It need not be a single query.
SELECT CITY, LENGTH(CITY)
FROM STATION
ORDER BY LENGTH(CITY), CITY
limit 1;
SELECT CITY, LENGTH(CITY)
FROM STATION
ORDER BY LENGTH(CITY) DESC, CITY
limit 1;
Query the list of CITY names starting with vowels (i.e., a, e, i, o, or u) from STATION. Your result cannot contain duplicates.
SELECT DISTINCT CITY
FROM STATION
WHERE CITY LIKE 'a%' or CITY LIKE 'e%' or CITY LIKE 'i%' or CITY LIKE 'o%' or CITY LIKE 'u%';
SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP '^[aeiou]';
SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP '^[AEIOU]';
SELECT DISTINCT CITY
FROM STATION
WHERE REGEXP_LIKE (CITY, '^[aeiou]');
'^[aeiou]'
[]
: [] 안에 나열된 패턴에 해당하는 문자열을 찾음.^
: 시작하는 문자열을 찾음.SELECT DISTINCT CITY
FROM STATION
WHERE LEFT(CITY, 1) IN ('a', 'e', 'i', 'o', 'u');
Query the list of CITY names ending with vowels (a, e, i, o, u) from STATION. Your result cannot contain duplicates.
SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP '[AEIOU]$';
SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP ('[aeiou]$');
$
: 끝나는 문자열을 찾음Query the list of CITY names from STATION which have vowels (i.e., a, e, i, o, and u) as both their first and last characters. Your result cannot contain duplicates.
SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP '^[AEIOU]$';
SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP '^[AEIOU]' AND CITY REGEXP '[AEIOU]$';
SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP ('^[aeiou].*[aeiou]$');
.*
로 연결가능하다..*
: 아무런 문자든(.
)가 0번 이상(*
) 반복되는 패턴 찾기.^[aeiou].*[aeiou]$
[aeiou]
)로 시작하고(^
).*
)[aeiou]
)로 끝나는($
) 문자열을 찾는것..*
때문에 문자열의 길이가 2 이상이어야만 해당이 되는데, 여기서는 도시명이니까 괜찮았다.Query the list of CITY names from STATION that do not start with vowels. Your result cannot contain duplicates.
SELECT DISTINCT CITY
FROM STATION
WHERE NOT CITY REGEXP '^[AIEOU]';
SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP ('^[^aeiou]');
^
가 두번 들어가서 헷갈리지만.. 자세히 살펴보면,^X
: 시작하는 문자열을 찾고,[]
: 괄호 안의 문자열 중 포함하는 문자열을 찾고,[^X]
: 괄호 안의 문자를 포함하지 않는 문자열을 찾는다.^
를 넣고, 괄호 밖에 ^
를 쓴다.Query the list of CITY names from STATION that do not end with vowels. Your result cannot contain duplicates.
not
을 사용SELECT DISTINCT CITY
FROM STATION
WHERE NOT CITY REGEXP '[AIEOU]$';
^
을 사용SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP '[^AIEOU]$';
Query the list of CITY names from STATION that either do not start with vowels or do not end with vowels. Your result cannot contain duplicates.
문제에서 요구하는건, "do not start with vowels or do not end with vowels". 즉 모음으로 시작하지 않거나, 모음으로 끝나지 않아야 한다.
정규표현식
^[aeiou]
: aeiou(모음)으로 시작하는 단어 찾기[aeiou]$
: aeiou(모음)으로 끝나는 단어 찾기^
을 넣으면, not의 의미SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP '^[^AEIOU]' OR CITY REGEXP '[^AEIOU]$';
^
대신에 NOT을 사용
NOT을 CITY 앞에 써도 실행되긴 하는데, CITY NOT REGEXP 순서로 쓰는게 맞는 것 같다!
SELECT DISTINCT CITY
FROM STATION
WHERE CITY NOT REGEXP ('^[aeiou]') OR CITY NOT REGEXP ('[aeiou]$');
만약 left와 right를 사용한다면, 모음 문자열 나열이 길어서 WHERE절이 조금 길어진다.
SELECT DISTINCT CITY
FROM STATION
WHERE LEFT(CITY, 1) NOT IN ('a', 'e', 'i', 'o', 'u')
OR RIGHT(CITY, 1) NOT IN ('a', 'e', 'i', 'o', 'u');
만약 like를 사용한다면 이렇게나 길고 가독성이 좋지 않은 쿼리문이 되므로, 정규표현식이나 left, right를 쓰자!
SELECT DISTINCT CITY
FROM STATION
WHERE
(CITY NOT LIKE 'a%' AND CITY NOT LIKE 'e%' AND CITY NOT LIKE 'i%' AND CITY NOT LIKE 'o%' AND CITY NOT LIKE 'u%') OR
(CITY NOT LIKE '%a' AND CITY NOT LIKE '%e' AND CITY NOT LIKE '%i' AND CITY NOT LIKE '%o' AND CITY NOT LIKE '%u');
정규표현식
Query the list of CITY names from STATION that do not start with vowels and do not end with vowels. Your result cannot contain duplicates.
.*
로 전체 표시SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP '^[^AEIOU].*[^AEIOU]$';
AND
로 and 표시SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP '^[^AEIOU]' AND CITY REGEXP '[^AEIOU]$';
Query the Name of any student in STUDENTS who scored higher than Marks. Order your output by the last three characters of each name. If two or more students both have names ending in the same last three characters (i.e.: Bobby, Robby, etc.), secondary sort them by ascending ID.
The Name column only contains uppercase (A-Z) and lowercase (a-z) letters.
Ashley
Julia
Belvet
the last three characters of each of their names, there are no duplicates and 'ley' < 'lia' < 'vet'.
SUBSTRING
활용SELECT Name
FROM STUDENTS
WHERE Marks > 75
ORDER BY SUBSTRING(Name, -3, 3), ID;
SELECT NAME
FROM STUDENTS
WHERE Marks > 75
ORDER BY RIGHT(NAME, 3), ID;
Write a query that prints a list of employee names (i.e.: the name attribute) from the Employee table in alphabetical order.
Angela
Bonnie
Frank
Joe
Kimberly
Lisa
Michael
Patrick
Rose
Todd
SELECT name
FROM Employee
ORDER BY name;
Write a query that prints a list of employee names (i.e.: the name attribute) for employees in Employee having a salary greater than $2000 per month who have been employees for less than 10 months. Sort your result by ascending employee_id.
Angela
Michael
Todd
Joe
SELECT name
FROM Employee
WHERE salary > 2000 AND months < 10;