codestates / codestates/ds-blog
[김지연]SQLite 서브쿼리(subquery) 알아보기
- Dominant language
- No language data
- Stars
- 2
- Forks
- 4
- PR merge metrics
- No merged PRs in 30d
Description
### 서브쿼리란
서브쿼리 혹은 중첩질의는 쿼리 안에 또 다른 쿼리가 포함된 것이다. 서브쿼리는 메인 쿼리에서 일종의 조건으로써 동작한다.
서브쿼리와 함께 쓸 수 있는 명령어는 SELECT, INSERT, UPDATE, DELETE이고 연산자와 함께 사용이 가능하다.
### 서브쿼리 규칙
서브쿼리를 사용하는데 있어 따라야 할 몇 가지 규칙이 있다.
1. 서브쿼리는 괄호 "()" 안에 들어가 있어야 한다.
2. 서브쿼리의 SELECT 문은 하나의 컬럼만을 가질 수 있다.
3. 서브쿼리에서는 ORDER BY 문을 사용할 수 없다.
### 서브쿼리의 사용
본격적으로 서브쿼리를 사용해보기 전에 내가 사용한 chinook 데이터 베이스의 스키마 일부를 살펴보도록 한다.

출처 - [sqlitetutorial.net](https://www.sqlitetutorial.net/sqlite-sample-database/)
위와 같이 employees 테이블의 EmployeeId와 customers 테이블의 SupportRepId가 Primary key - Foreign key 관계이다.
그래서 customers 테이블과 employees 테이블을 연결하기 위해선 두 컬럼(EmployeeId / SupportRepId)을 기준으로 합쳐야 한다.
우선 서브쿼리를 사용하지 않고 두 테이블을 합쳐 Park이란 성을 가진 직원이 담당하는 고객의 성을 쿼리 해도록 한다.
```SQL
SELECT customers.LastName FROM customers
INNER JOIN employees ON employees.EmployeeId = customers.SupportRepId
WHERE employees.LastName = 'Park'
```
INNER JOIN을 통해 두 테이블을 합쳐주고 WHERE 로 조건을 설정해 고객들의 목록을 알아낼 수 있다.
다음으로 서브쿼리를 사용해 똑같은 내용을 쿼리 해보도록 한다.
```SQL
SELECT FirstName FROM customers
WHERE SupportRepId = (
SELECT EmployeeId FROM employees
WHERE LastName = 'Park'
)
```
괄호로 묶인 부분이 서브쿼리로 위의 쿼리와 같이 똑같이 조건(LastName = 'Park')을 WHERE로 설정하지만 INNER JOIN 대신 서브쿼리 밖에서 WHERE를 써서 두 테이블을 묶는 기능을 사용할 수 있다.
짧은
참고자료
[SQLITE tutorial](https://www.sqlitetutorial.net/sqlite-subquery/)
Contributor guide
No contributing guide indexed for this repository
Research direction
No file, test, or entry point is named. Start by checking the repository's blog contribution conventions and confirm whether this article should be added, edited, or reviewed; done should be an agreed publication-ready SQLite subquery article in the expected location.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- sql, sqlite
- Domain
- databases, documentation
- Issue type
- Documentation
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100