Printing is disabled on this page for content protection.
SQL 기초 마스터하기 | SELECT 문으로 데이터 검색의 첫걸음 떼기
SELECT 문은 단순 조회 문법이 아니라, 원하는 열만 고르는
Projection, 필요한 행만 걸러내는 Selection,
서로 다른 테이블을 연결하는 Join의 출발점입니다. 실무에서는 SELECT * 남용을 피하고,
NULL과 산술 연산의 함정을 이해하며, 별칭과 가독성 규칙까지 함께 익혀야 좋은 SQL이 됩니다.
데이터베이스의 방대한 정보 속에서 원하는 데이터만 정확하게 꺼내는 능력은 백엔드 개발자와 데이터 분석가의 가장 기본적인 역량입니다.
복잡한 성능 튜닝이나 정교한 모델링도 결국은 가장 기초적인 SELECT 문을 얼마나 정확히 이해하고 있는지에서 출발합니다.
이번 글에서는 단순 문법 암기가 아니라, 왜 이 기능이 필요한지와 실무에서 무엇을 특히 조심해야 하는지를 함께 정리합니다.
- SELECT 문의 3가지 핵심 원리: Projection, Selection, Join
- 실무형 SQL 작성 규칙과 가독성 개선 방법
- 산술 연산 우선순위와
NULL이 만드는 치명적 함정 - Alias, 연결 연산자,
DISTINCT,DESCRIBE활용 팁
1. SELECT 문의 3가지 핵심 기능
데이터를 조회할 때 데이터베이스 엔진 내부에서는 크게 세 가지 메커니즘이 작동합니다. 이 세 가지를 구분해서 이해하면 SQL 작성 속도와 정확도가 동시에 올라갑니다.
1-1. 프로제션 (Projection)
테이블의 여러 열 중에서 필요한 열만 선택하는 기능입니다.
- 비유: 거대한 뷔페에서 원하는 음식만 접시에 담는 것과 같습니다.
- 실무 포인트: 불필요한 열까지 조회하면 네트워크와 메모리를 낭비합니다.
1-2. 선택 (Selection)
테이블의 여러 행 중에서 조건에 맞는 행만 필터링하는 기능입니다.
- 비유: 수많은 지원자 중에서 특정 조건을 만족하는 사람만 추려내는 작업입니다.
- 실무 포인트:
WHERE절을 잘 쓰면 처음부터 불필요한 데이터를 줄일 수 있습니다.
1-3. 조인 (Join)
서로 다른 테이블의 데이터를 공통 키를 기준으로 연결하는 기능입니다.
- 비유: 흩어진 퍼즐 조각을 맞춰 하나의 그림을 완성하는 과정입니다.
- 실무 포인트: 직원 정보와 부서 정보처럼 분리 저장된 데이터를 한 번에 보여줄 수 있습니다.
2. 기본 SELECT 문법과 작성 규칙
가장 기본이 되는 SELECT 문법은 다음과 같습니다.
SELECT * | { [DISTINCT] column | expression [alias], ... }
FROM table;
SELECT: 어떤 열을 가져올지 정의합니다.*: 테이블의 모든 열을 의미합니다.FROM: 어떤 테이블에서 데이터를 가져올지 지정합니다.
SELECT *보다 필요한 열을 명시적으로 적는 습관이 훨씬 안전합니다.
전송 데이터량을 줄일 수 있고, 나중에 테이블 구조가 바뀌었을 때도 쿼리의 영향 범위를 더 명확하게 관리할 수 있습니다.
2-1. SQL 작성 규칙
- SQL 키워드는 대문자로, 테이블명·열 이름은 소문자로 쓰면 가독성이 좋아집니다.
- 절마다 줄바꿈과 들여쓰기를 적용하면 유지보수가 쉬워집니다.
SQL*Plus환경에서는 문장 끝의 세미콜론(;)이 중요합니다.- 결과창에서 문자는 보통 왼쪽, 숫자는 오른쪽으로 정렬되어 데이터 타입을 빠르게 추정할 수 있습니다.
3. 산술 연산자와 데이터 가공
조회 시점에 값을 직접 계산하여 보여줄 수도 있습니다.
| 연산자 | 설명 | 우선순위 |
|---|---|---|
*, / |
곱하기, 나누기 | 높음 |
+, - |
더하기, 빼기 | 낮음 |
3-1. 연산자 우선순위 예시
-- 예시 1: 곱셈이 덧셈보다 먼저 계산됩니다. SELECT last_name, salary, 12 * salary + 100 FROM employees; -- 예시 2: 괄호를 사용하여 100을 먼저 더한 후 12를 곱합니다. SELECT last_name, salary, 12 * (salary + 100) FROM employees;
두 문장은 비슷해 보여도 결과는 완전히 다를 수 있습니다. 산술 연산은 원본 데이터를 바꾸는 것이 아니라, 조회 결과를 가공해서 보여주는 것이라는 점도 함께 기억해야 합니다.
4. 가장 많이 실수하는 영역: NULL
NULL은 0도 아니고 빈 문자열도 아닙니다. 값이 없거나, 아직 정해지지 않았거나, 적용할 수 없음을 의미합니다.
실무에서 초보자와 숙련자의 차이가 가장 크게 나는 지점 중 하나가 바로 이 NULL 처리입니다.
NULL이 포함된 산술 연산의 결과는 다시NULL이 됩니다.NULL은 일반적인 비교 연산으로 정확히 비교할 수 없습니다.- 따라서 예상과 다른 집계 결과나 계산 결과가 쉽게 발생합니다.
예를 들어 월급이 2000이고 커미션이 NULL이면, 다음 계산 결과는 0이 아니라 NULL이 됩니다.
SELECT salary * 12 * commission_pct FROM employees;
이유는 커미션 값이 얼마인지 알 수 없기 때문입니다. 실무에서는 이런 특성을 모르면 보고서 수치가 틀어지거나, 배치 로직이 잘못된 값을 전파할 수 있습니다.
5. 가독성을 높이는 기술: Alias와 연결 연산자
5-1. 열 별칭 (Column Alias)
계산식이나 긴 열 이름은 별칭을 사용해 결과 헤더를 더 읽기 좋게 만들 수 있습니다.
SELECT last_name AS name, salary * 12 "Annual Salary" FROM employees;
AS는 선택 사항이지만 명시하면 더 읽기 쉽습니다.- 공백이나 대소문자 유지가 필요하면 큰따옴표를 사용합니다.
5-2. 연결 연산자와 리터럴
여러 값을 하나의 문장처럼 합쳐 보여줄 때는 연결 연산자 ||를 사용합니다.
SELECT last_name || ' is a ' || job_id AS "Employee Details" FROM employees;
이렇게 하면 King is a AD_PRES 같은 문자열을 쉽게 만들 수 있습니다.
5-3. q 연산자
문자열 안에 작은따옴표가 포함되어 있을 때는 q 연산자를 사용하면 훨씬 깔끔합니다.
SELECT department_name || q'[ 's Manager Id: ]' || manager_id AS "Dept Info" FROM departments;
6. 중복 제거와 테이블 구조 확인
6-1. DISTINCT
특정 열에 어떤 값의 종류가 있는지 확인할 때 유용합니다.
SELECT DISTINCT department_id FROM employees;
직원 수와 상관없이 부서 번호의 종류만 중복 없이 확인할 수 있습니다.
6-2. DESCRIBE
쿼리를 작성하기 전 테이블 구조를 먼저 확인하는 습관은 매우 중요합니다.
DESC employees
- Name: 열 이름
- Null?:
NOT NULL이면 필수 입력 항목 - Type:
NUMBER,VARCHAR2,DATE등 데이터 타입 정보
7. 마무리
SELECT 문은 모든 SQL의 출발점입니다. 단순 조회에 머무르지 않고,
어떤 열을 가져와야 하는지, 어떤 행을 걸러야 하는지, 계산식과 NULL이 어떤 결과를 만드는지까지 이해해야
실무에서 흔들리지 않는 쿼리를 작성할 수 있습니다.
- SELECT는 Projection, Selection, Join의 기본 축으로 이해해야 합니다.
SELECT *는 편하지만 운영 환경에서는 남용하지 않는 편이 좋습니다.- 산술 연산은 우선순위와 괄호에 따라 결과가 크게 달라집니다.
NULL은 0이나 공백이 아니며, 계산과 비교에서 특별하게 취급됩니다.- Alias, 연결 연산자,
DISTINCT,DESC는 초급을 넘어 실무 기본기입니다.
The
SELECT statement is not just a basic query command. It is the starting point for
Projection (choosing columns), Selection (filtering rows), and Join (combining tables).
In real-world SQL work, you should avoid overusing SELECT *, understand the dangers of NULL,
and learn how to improve readability with aliases and formatting rules.
The ability to retrieve exactly the data you need from a large database is one of the most fundamental skills
for backend developers and data analysts. Even advanced tuning and sophisticated schema design ultimately rest on
a solid understanding of the most basic statement of all: SELECT.
This article focuses not only on syntax, but also on why these features matter and which practical pitfalls should be avoided.
- The three core principles of
SELECT: Projection, Selection, and Join - Practical SQL writing conventions and readability tips
- Operator precedence and the dangerous behavior of
NULL - Useful techniques involving aliases, concatenation,
DISTINCT, andDESCRIBE
1. The Three Core Functions of SELECT
Whenever you query data, the database engine is essentially performing three major tasks. Understanding them clearly will improve both SQL accuracy and query design speed.
1-1. Projection
This means selecting only the columns you need from a table.
- Analogy: choosing only the food you want from a large buffet.
- Practical point: retrieving unnecessary columns wastes memory and network bandwidth.
1-2. Selection
This means filtering rows so that only rows matching your condition are returned.
- Analogy: screening applicants and keeping only those who meet the requirements.
- Practical point: a well-written
WHEREclause eliminates unnecessary data early.
1-3. Join
This means combining data from different tables using a shared key.
- Analogy: assembling scattered puzzle pieces into one complete picture.
- Practical point: you can view employee data and department data together in one result set.
2. Basic SELECT Syntax and Writing Rules
The most basic form of a SELECT statement looks like this.
SELECT * | { [DISTINCT] column | expression [alias], ... }
FROM table;
SELECT: defines which columns to retrieve.*: means all columns in the table.FROM: specifies the source table.
SELECT *.
It reduces transferred data volume and makes structural changes easier to control later.
2-1. SQL Writing Rules
- Use uppercase for SQL keywords and lowercase for table and column names for better readability.
- Break clauses into separate lines and use indentation.
- In
SQL*Plus, the semicolon (;) at the end of a statement matters. - In result grids, text is often left-aligned and numbers right-aligned, which helps identify data types quickly.
3. Arithmetic Operators and Data Transformation
You can calculate values at query time instead of simply displaying stored data as-is.
| Operator | Description | Precedence |
|---|---|---|
*, / |
Multiplication, division | High |
+, - |
Addition, subtraction | Low |
3-1. Example of Operator Precedence
-- Example 1: multiplication is evaluated before addition. SELECT last_name, salary, 12 * salary + 100 FROM employees; -- Example 2: parentheses make 100 added first, then multiplied by 12. SELECT last_name, salary, 12 * (salary + 100) FROM employees;
These two statements look similar, but they can produce very different results. Also remember that arithmetic in a query does not modify the original data; it only transforms the output.
4. The Most Common Source of Mistakes: NULL
NULL is neither zero nor an empty string. It means that a value is missing, unknown, or not applicable.
One major difference between beginners and experienced SQL developers is how well they understand NULL behavior.
- If an arithmetic expression contains
NULL, the result becomesNULL. NULLcannot be handled properly with ordinary equality or comparison logic.- This often leads to unexpected totals, calculations, or report outputs.
For example, if salary is 2000 and commission is NULL, the following expression returns NULL, not zero.
SELECT salary * 12 * commission_pct FROM employees;
The reason is simple: if the commission value is unknown, the final calculated amount is also unknown. In real systems, failing to understand this behavior can easily produce incorrect reports or flawed batch logic.
5. Readability Techniques: Alias and Concatenation
5-1. Column Alias
Aliases make result headers cleaner and easier to understand, especially when expressions are involved.
SELECT last_name AS name, salary * 12 "Annual Salary" FROM employees;
ASis optional, but explicit usage improves readability.- Use double quotes when you need spaces or preserved letter case in the alias.
5-2. Concatenation Operator and Literals
Use the concatenation operator || to combine multiple values into one sentence-like output.
SELECT last_name || ' is a ' || job_id AS "Employee Details" FROM employees;
This produces values such as King is a AD_PRES.
5-3. The q Quoting Operator
When a string already contains a single quote, the q quoting syntax is cleaner than escaping it repeatedly.
SELECT department_name || q'[ 's Manager Id: ]' || manager_id AS "Dept Info" FROM departments;
6. Removing Duplicates and Checking Table Structure
6-1. DISTINCT
Use DISTINCT when you want to know which unique values exist in a column.
SELECT DISTINCT department_id FROM employees;
This shows only the unique department IDs, regardless of how many employees exist.
6-2. DESCRIBE
Checking table structure before writing a query is an excellent habit.
DESC employees
- Name: column name
- Null?:
NOT NULLmeans the column is mandatory - Type: data type information such as
NUMBER,VARCHAR2, andDATE
7. Conclusion
The SELECT statement is the true starting point of SQL. To write stable real-world queries,
you need more than the ability to fetch data. You must understand which columns to retrieve,
which rows to filter, and how calculations and NULL values affect the final result.
- Understand
SELECTthrough the lenses of Projection, Selection, and Join. SELECT *is convenient, but should not be overused in production SQL.- Arithmetic results depend heavily on operator precedence and parentheses.
NULLis not zero or blank; it behaves differently in calculations and comparisons.- Aliases, concatenation,
DISTINCT, andDESCare essential practical basics.