Notice
Recent Posts
Recent Comments
Link
«   2026/04   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
Archives
Today
Total
관리 메뉴

memo6759 님의 블로그

2025-09-25(SQL-2) 본문

HDC 학습일지

2025-09-25(SQL-2)

heewon09 2025. 9. 25. 23:30

 SQL 기본 문법 정리 (조건 / NULL / 그룹함수 / 내장함수)

1. NULL

  • NULL: 컬럼에 값이 없는 상태
  • NULL과의 연산 결과는 항상 NULL
-- NULL 조회
where 컬럼 is null;

-- NULL이 아닌 값 조회
where 컬럼 is not null;

2. DISTINCT

  • 중복 제거를 위해 사용
  • 한 컬럼 기준으로 중복값 제거 가능
  • 여러 컬럼 조합을 지정하면 동일한 레코드도 제거 가능
select distinct deptno from emp;

3. 조건절 (where)

 비교연산자

=, !=, <>, >, >=, <, <=

 and / or

-- and: 모든 조건 만족
where sal >= 2000 and hiredate < '1981-06-01';

-- or: 조건 중 하나만 만족
where sal = 1250 or sal = 2975 or sal = 3000;

 in

where sal in (1250, 2975, 3000);

 like (패턴 검색)

  • %: 모든 문자열
  • _: 한 글자
-- 이름이 R로 끝나는 사원
where ename like '%R';

4. 정렬 (order by)

  • 오름차순: 기본값 (asc)
  • 내림차순: desc
select ename, sal
from emp
order by sal desc;

5. GROUP BY & 집계함수

  • 데이터를 그룹 단위로 묶어 통계 계산
  • sum, avg, min, max, count 사용 가능
-- 직업별 인원수 & 평균 급여
select job, count(*) cnt, avg(sal) avgsal
from emp
group by job;

-- 조건을 걸 때
having count(*) >= 3;

6. 제어 흐름 함수

 if 함수 (MySQL 전용)

select ename, job,
       if(job = 'PRESIDENT', '대표이사', '사원') as title
from emp;

 case 문 (ANSI 표준)

select ename, deptno, sal,
       case
            when sal >= 3000 then 'high'
            when sal between 2000 and 2999 then 'mid'
            else 'low'
       end as grade
from emp;

 ifnull

-- comm이 null이면 1000 출력
select ename, ifnull(comm, 1000) as comm
from emp;

-- 연봉 계산 (comm이 null이면 0 처리)
select ename, sal*12 + ifnull(comm, 0) as annual
from emp;

7. 문자열 함수

concat('A', 'B')              -- 문자열 연결
instr('hello','e')            -- 특정 문자 위치
substr('hello', 2, 3)         -- 부분 문자열
upper('sql')                  -- 대문자 변환
lower('SQL')                  -- 소문자 변환
lpad('7', 3, '0')             -- 007
rpad('7', 3, '*')             -- 7**
trim('   sql   ')             -- 공백 제거
replace('java','a','A')       -- jAvA
reverse('sql')                -- lqs
repeat('sql', 3)              -- sqlsqlsql

8. 수학 함수

abs(-10)        -- 절대값
round(12.345,2) -- 반올림 → 12.35
ceil(12.1)      -- 올림 → 13
floor(12.9)     -- 내림 → 12
mod(10,3)       -- 나머지 → 1

9. 날짜/시간 함수

sysdate()               -- 실행 순간의 현재 시간
now()                   -- 트랜잭션 시작 시간
year(hiredate)          -- 연도 추출
month(hiredate)         -- 월 추출
day(hiredate)           -- 일 추출
adddate(hiredate, 30)   -- 날짜 더하기
subdate(hiredate, 30)   -- 날짜 빼기
datediff('2025-01-01','2024-01-01')  -- 날짜 차이
dayofweek(hiredate)     -- 요일 (1=일요일)
last_day(hiredate)      -- 해당 달의 마지막 날
quarter(hiredate)       -- 분기

 

'HDC 학습일지' 카테고리의 다른 글

2025-09-29(SQL-4 DDL, 제약조건, VIEW)  (0) 2025.09.30
2025-09-26(SQL-3)  (0) 2025.09.27
2025-09-24(SQL-1)  (0) 2025.09.24
2025-09-23(깃허브 사용법)  (0) 2025.09.24
2025-09-22(학습 리뷰)  (0) 2025.09.23