on
TIL 49: [데이터베이스] 관계형 데이터베이스
TIL 49: [데이터베이스] 관계형 데이터베이스
Database & SQL 개념
SQL이란?
Structured Query Language → 구조화된 Query 언어
데이터베이스용 프로그래밍 언어로, SQL을 사용해서 데이터베이스에 Query를 보내 원하는 데이터만을 뽑아올 수 있습니다.
Query 란?
저장되어있는 정보를 필터링하기 위한 질문으로 검색창에 적는 검색어도 Query의 일종입니다.
Database 란?
엑셀과 비슷하게 시트, 행, 열이 있으며, 필터링도 가능합니다. 이러한 데이터베이스를 사용하기 위해서는 사람의 언어와 비슷한 SQL 언어를 배워야 합니다. ORM을 배우면 JavaScript로 할 수 있는 방법도 배울 수 있습니다.
종료하면 데이터가 사라지는 In-memory의 한계와 원하는 데이터만 가져올 수 없고 항상 모든 데이터를 가져오는 File I/O의 한계를 극복할 수 있다는 장점이 있습니다. 또한 File I/O로 구현이 어려운 데이터 관리를 위한 여러 기능들을 가지고 있습니다.
기본 쿼리문
Select
Where
And, Or, Not
Order By
Insert Into
Null Values
Update
Delete
Count
Like
Wildcards
Aliases
Joins (Inner, Left, Right)
Group By
위와 같이 다양한 쿼리문들이 있습니다. 문제를 풀면서 헷갈리거나 잘 안 외워지는 부분 위주로 정리해보려고 합니다.
How can you insert a new record into the "Persons" table?
INSERT INTO Persons VALUES('Jimmy', 'Jackson')
How can you change "Hansen" into "Nilsen" in the "LastName" column in the Persons table?
UPDATE Persons SET LastName='Nilsen' WHERE LastName='Hansen'
How can you return the number of records in the "Persons" table?
SELECT COUNT(*) FROM Persons
Insert a new record in to the Customers table.
INSERT INTO Customers ( CustomerName, Address, City, PostalCode, Country) VALUES ( 'Hekkan Burger', 'Gateveien 15', 'Sandnes', '4306', 'Norway');
Select all records where the value of the City column does NOT start with the letter "a".
SELECT * FROM Customers WHERE City NOT LIKE 'a%';
Select all records where the first letter of the City is NOT an "a" or a "c" or an "s".
SELECT * WHERE Customers WHERE City LIKE '[!acs]%';
When displaying the Customers table, refer to the table as Consumers instead of Customers.
SELECT * FROM Customers AS Consumers;
Choose the correct JOIN clause to select all the records from the Customers table plus all the matches in the Orders table.
SELECT * FROM Orders RIGHT JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
List the number of customers in each country, ordered by the country with the most customers first.
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country ORDER BY COUNT(CustomerID) DESC;
Add a column of type DATE called Birthday.
ALTER TABLE Persons ADD Birthday DATE; //ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
DELETE / TRUNCATE / DROP의 차이
Quiz와 Exercise를 풀면서 세 명령문 모두 공통적으로 무언가를 지우는 기능을 가지고 있지만, 정확히 정리가 되지 않아 표로 정리해보았습니다.
DELETE TRUNCATE DROP 명령어 DML(데이터 조작어) DDL(데이터 정의어) DDL(데이터 정의어) 처리속도 느림 빠름 빠름 Commit 사용자가 직접 자동 자동 Rollback 가능여부 Commit 이전까지 가능 불가능 불가능 삭제되는 정도 Data만 삭제 테이블을 CREATE 상태로 되돌림 테이블까지 완전히 제거
DELETE와 TRUNCATE 모두 TABLE 안의 내용을 삭제하는 기능을 가집니다. 그러나 DELETE문의 경우 WHERE 절을 사용 가능하기 때문에 데이터를 하나하나 선택하여 제거할 수 있습니다. 따라서 WHERE 절을 사용하지 않고, 테이블의 모든 데이터를 삭제하더라도, 재부적으로는 한줄한줄 일일이 제거하는 과정을 거칩니다. 따라서 TRUNCATE나 DROP보다 처리속도가 느리게 됩니다.
from http://high-developer.tistory.com/65 by ccl(A) rewrite - 2021-10-08 20:27:29