백엔드 개발에서 매우 중요한 데이터베이스를 학습합니다.
Learn SQL, Designing Schema
SQL(Structured Query Language)을 학습하면, 관계형 데이터베이스를 자유자재로 다룰 수 있습니다. 대표적인 관계형 데이터베이스(RDBMS)인 MySQL로 Schema를 설계하고, SQL을 사용하여 데이터를 영속성있게(persistently) 저장하는 방법을 학습합니다.
Learn SQL
SQL은 구조화된 쿼리 언어입니다.
하나의 언어인 Structured Query Language (SQL)은 데이터베이스 언어로, 주로 관계형 데이터베이스에서 사용합니다. 예를 들어 MySQL, Oracle, SQLite, PostgreSQL 등 다양한 데이터베이스에서 SQL 구문을 사용할 수 있습니다.
SQL이란 데이터베이스 용 프로그래밍 언어
입니다.
데이터베이스에 쿼리를 보내 원하는 데이터를 가져오거나 삽입할 수 있습니다.
그리고 이름에서 유추할 수 있듯이,
SQL은 (relation 이라고도 불리는) 데이터가 구조화된(structured) 테이블을 사용하는 데이터베이스에서 활용할 수 있습니다.
SQL을 사용할 수 있는 데이터베이스와 달리, 데이터의 구조가 고정되어 있지 않은 데이터베이스를 NoSQL이라고 합니다.
관계형 데이터베이스와는 달리, 테이블을 사용하지 않고 데이터를 다른 형태로 저장합니다.
NoSQL의 대표적인 예시는 MongoDB 와 같은 문서 지향 데이터베이스입니다.
이처럼 데이터베이스 세계에서 SQL은 데이터베이스 종류를 SQL이라는 언어 단위로 분류할 정도로 중요한 자리를 차지하고 있습니다. 그리고 SQL을 사용하기 위해서는 데이터가 구조가 고정되어 있어야 합니다.
SQL(구조화 쿼리 언어) vs. NoSQL(비구조화 쿼리 언어)
데이터베이스는 크게 관계형 데이터베이스와 비관계형 데이터베이스로 구분합니다.
관계형 데이터베이스는 SQL
비관계형 데이터베이스는 NoSQL로 데이터를 다룹니다.
SQL과 NoSQL은
SQL 관계형 데이터베이스
열
은 하나의 속성에 대한 정보를 저장하고, 행
에는 각 열의 데이터 형식에 맞는 데이터가 저장됩니다.쿼리
할 수 있습니다.스키마가 뚜렷하게 보인다는 말
과 같습니다.직관적
으로 파악할 수 있습니다.대표적인 관계형 데이터베이스는 MySQL, Oracle, SQLite, PostgresSQL, MariaDB 등이 있습니다.
SQL 기반의 관계형 데이터베이스를 사용하는 케이스
NoSQL
입력할 때
스키마에 맞게 입력해야 하는 반면, NoSQL에서는 데이터를 읽어올 때
스키마에 따라 데이터를 읽어 옵니다.('schema on read')대표적인 NoSQL은 몽고DB, Casandra 등이 있습니다.
NoSQL 기반의 비관계형 데이터베이스를 사용하는 케이스
SQL 기반의 데이터베이스와 NoSQL 데이터베이스의 차이점
데이터 저장(Storage)
스키마(Schema)
쿼리(Querying)
확장성(Scalability)
(1) Select(SELECT는 데이터셋에 포함될 특성을 특정합니다.)
From (테이블과 관련한 작업을 할 경우 반드시 입력해야 합니다. FROM 뒤에는 결과를 도출해낼 데이터베이스 테이블을 명시합니다.)
Q) Insert the missing statement to get all the columns from the Customers table.
A) SELECT * FROM Customers;
Q) Write a statement that will select the City column from the Customers table.
A) SELECT CITY FROM Customers;
Q)Select all the different values from the Country column in the Customers table.
A) SELECT DISTINCT Country FROM Customers;
DISTINCT : 유니크한 값을 받고 싶을 때에는 SELECT DISTINCT 를 사용할 수 있습니다.
특성_1을 기준으로 유니크한 값들만 선택합니다.
SELECT DISTINCT 특성_1
FROM 테이블_이름
특성_1, 특성_2, 특성_3의 유니크한 '조합' 값들을 선택합니다.
SELECT
DISTINCT
특성_1
,특성_2
,특성_3
FROM 테이블_이름
(2) Where (필터 역할을 하는 쿼리문입니다. WHERE은 선택적으로 사용할 수 있습니다.) (3) And, Or, Not
특정 값과 동일한 데이터 찾기
SELECT 특성_1, 특성_2
FROM 테이블_이름
WHERE 특성_1 = "특정 값"
특정 값을 제외한 값을 찾기
SELECT 특성_1, 특성_2
FROM 테이블_이름
WHERE 특성_2 <> "특정 값"
특정 값보다 크거나 작은 데이터를 필터할 때에는 '<', '>', 비교하는 값을 포함하는 '이상', '이하' 값은 '<=', '>=' 을 사용합니다.
SELECT 특성_1, 특성_2
FROM 테이블_이름
WHERE 특성_1 > "특정 값"
SELECT 특성_1, 특성_2
FROM 테이블_이름
WHERE 특성_1 <= "특정 값"
문자열에서 특정 값과 비슷한 값들을 필터할 때에는 'LIKE'와 '\%' 혹은 '\*' 를 사용합니다.
SELECT 특성_1, 특성_2
FROM 테이블_이름
WHERE 특성_2 LIKE "%특정 문자열%"
리스트의 값들과 일치하는 데이터를 필터할 때에는 'IN' 을 사용합니다.
SELECT 특성_1, 특성_2
FROM 테이블_이름
WHERE 특성_2 IN ("특정값_1", "특정값_2")
값이 없는 경우 'NULL' 을 찾을 때에는 'IS' 와 같이 사용합니다.
SELECT *
FROM 테이블_이름
WHERE 특성_1 IS NULL
값이 없는 경우를 제외할 때에는 'NOT' 을 추가해 이용합니다.
SELECT *
FROM 테이블_이름
WHERE 특성_1 IS NOT NULL
Q)Select all records where the City column has the value "Berlin".
A) SELECT * FROM Customers WHERE city = 'Berlin';
Q)Use the NOT keyword to select all records where City is NOT "Berlin".
A) SELECT * FROM Customers WHERE NOT city = 'Berlin';
Q)Select all records where the CustomerID column has the value 32.
A) SELECT * FROM Customers WHERE CustomerID = 32;
Q)Select all records where the City column has the value 'Berlin' and the PostalCode column has the value 12209.
A) SELECT* FROM Customers WHERE city ='Berlin'AND'PostalCode = 12209;
Q)Select all records where the City column has the value 'Berlin' or 'London'.
A) SELECT* FROM Customers WHERE City = 'Berlin' OR City = 'London';
(4) Order By (기본 정렬은 오름차순입니다.)
오름차순 정렬
SELECT *
FROM 테이블_이름
ORDER BY 특성_1
내림차순 정렬
SELECT *
FROM 테이블_이름
ORDER BY 특성_1 DESC
Q)Select all records from the Customers table, sort the result alphabetically by the column City.
A) SELECT * FROM Customers Order By City;
Q)Select all records from the Customers table, sort the result reversed alphabetically by the column City.
A) SELECT * FROM Customers Order By City DESC;
Q)Select all records from the Customers table, sort the result alphabetically, first by the column Country, then, by the column City.
A) SELECT * FROM Customers Order By Country, City;
(5) Insert Into
Q)Insert a new record in the Customers table.
A)
Insert into Customers(
CustomerName,
Address,
City,
PostalCode,
Country
)
Values(
'Hekkan Burger',
'Gateveien 15',
'Sandnes',
'4306',
'Norway');
(6) Null Values
Q)Select all records from the Customers where the PostalCode column is empty.
A) SELECT * FROM Customers WHERE Postalcode is null;
Q)Select all records from the Customers where the PostalCode column is NOT empty.
A) SELECT * FROM Customers WHERE PostalCode is Not null;
(7) Update
Q)Update the City column of all records in the Customers table.
A) Update Cusotmers Set City = 'Oslo';
Q)Set the value of the City columns to 'Oslo', but only the ones where the Country column has the value "Norway".
A) Update Customers Set City = 'Oslo' Where Country = 'Norway';
Q)Update the City value and the Country value.
A) Update Customers Set City = 'Oslo',Country= 'Norway' WHERE CustomerID = 32;
(8) Delete
Q) Delete all the records from the Customers table where the Country value is 'Norway'.
A) DELETE FROM Customers WHERE Country = 'Norway';
Q) Delete all the records from the Customers table.
A) Delete from Customers;
(9) Count
MIN() MAX() AVG()
Q)Use the MIN function to select the record with the smallest value of the Price column.
A) SELECT Min(Price) FROM Products;
Q)Use an SQL function to select the record with the highest value of the Price column.
A) SELECT Max(Price) FROM Products;
Q)Use the correct function to return the number of records that have the Price value set to 18.
A) SELECT Count(*) FROM Products Where Price = 18;
Q)Use an SQL function to calculate the average price of all products.
A) SELECT AVG(Price)FROM Products;
Q)Use an SQL function to calculate the sum of all the Price column values in the Products table.
A) SELECT SUM(Price)FROM Products;
(10) Like
Q)Select all records where the value of the City column starts with the letter "a".
A) SELECT * FROM Customers Where City like 'a%';
Q)Select all records where the value of the City column ends with the letter "a".
A) SELECT * FROM Customers Where City like '%a';
Q)Select all records where the value of the City column contains the letter "a".
A) SELECT * FROM Customers Where City like '%a%';
Q) Select all records where the value of the City column starts with letter "a" and ends with the letter "b".
A) SELECT * FROM Customers Where City like 'a%b';
Q) Select all records where the value of the City column does NOT start with the letter "a".
A) SELECT * FROM Customers Where City NOT like 'a%';
(11) Wildcards
Q)Select all records where the second letter of the City is an "a".
A) SELECT * FROM Customers Where City like '_a%';
Q)Select all records where the first letter of the City is an "a" or a "c" or an "s".
A) SELECT * FROM Customers
WHERE City LIKE '[acs]%';
Q)Select all records where the first letter of the City starts with anything from an "a" to an "f".
A) SELECT * FROM Customers
WHERE City LIKE '[a-f]%';
Q)Select all records where the first letter of the City is NOT an "a" or a "c" or an "f".
A) SELECT * FROM Customers
WHERE City LIKE '[!acf]%';
(12) In /between
Q) Use the IN operator to select all the records where Country is either "Norway" or "France".
A) SELECT * FROM Customers WHERE Country IN
('Norway','France');
리스트의 값들과 일치하는 데이터를 필터할 때에는 'IN' 을 사용합니다.
Q) Use the IN operator to select all the records where Country is NOT "Norway" and NOT "France".
A) SELECT * FROM Customers WHERE COUNTRY NOT IN ('Norway', 'France');
Q) Use the BETWEEN operator to select all the records where the value of the Price column is between 10 and 20.
A) SELECT * FROM Products
WHERE Price Between 10 and 20;
Q) Use the BETWEEN operator to select all the records where the value of the Price column is NOT between 10 and 20.
A) SELECT * FROM Products
WHERE Price not Between 10 and 20;
Q) Use the BETWEEN operator to select all the records where the value of the ProductName column is alphabetically between 'Geitost' and 'Pavlova'.
A) SELECT * FROM Product WHERE ProductName BETWEEN 'Geitost' AND 'Pavlova';
(13) Aliases
Q)When displaying the Customers table, make an ALIAS of the PostalCode column, the column should be called Pno instead.
A) SELECT CustomerName, Address, PostalCode as pno FROM Customers;
Q)When displaying the Customers table, refer to the table as Consumers instead of Customers.
A) SELECT *FROM Customers AS Consumers;
(14) Joins
Q)Insert the missing parts in the JOIN clause to join the two tables Orders and Customers, using the CustomerID field in both tables as the relationship between the two tables.
A) SELECT * FROM Orders LEFT JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Q) Choose the correct JOIN clause to select all records from the two tables where there is a match in both tables.
A) SELECT * FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
Q) Choose the correct JOIN clause to select all the records from the Customers table plus all the matches in the Orders table.
A) SELECT * FROM Orders RIGHT JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
(15)Group By
Q) List the number of customers in each country.
A) SELECT COUNT (CustomerID),Country FROM Customers GROUP BY Country;
Q) List the number of customers in each country, ordered by the country with the most customers first.
A) SELECT COUNT(CustomerID),Country FROM Customers GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
SQL Create DB
SQL Drop DB
SQL Create Table
SQL Drop Table
SQL Alter Table
SQL Not Null
SQL Unique
SQL Primary Key
SQL Foreign Key
SQL Default
SQL Auto Increment
SQL Dates