Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[20230313] MySQL 쿼리 소소한 팁(?) #274

Open
JuHyun419 opened this issue Mar 13, 2023 · 0 comments
Open

[20230313] MySQL 쿼리 소소한 팁(?) #274

JuHyun419 opened this issue Mar 13, 2023 · 0 comments
Labels

Comments

@JuHyun419
Copy link
Owner

JuHyun419 commented Mar 13, 2023

  1. WHERE 조건 데이터 타입 동일하게 사용
SELECT * FROM test WHERE age = '2'; -- NUMBER 타입에 문자열 사용 X
SELECT * FROM test WHERE age = 2;

  1. 범위 조건 비교 시 인덱스 사용 (WHERE, ORDER BY)
  • 범위 조건 비교 시 조건을 만족하는 칼럼의 값이 여러개일 수 있기 때문에 누락 X
  • index: col_1, col_2, col_3, col_4, col_5
-- 인덱스 사용 가능
... WHERE col_1=10 ORDER BY col_2, col_3;
... WHERE col_1=10 ORDER BY col_1, col_2, col_3; 
... WHERE col_1>10 ORDER BY col_1, col_2, col_3;

-- 인덱스 사용 불가능 
SELECT * FROM tb_test WHERE col_1>10 ORDER BY col_2, col_3; -- 사용 불가

  1. 문자열, 날짜 비교
  • (1), (2)는 모두 인덱스를 효율적으로 이용
  • (3)은 조건의 hire_date 타입을 강제로 변환하기 때문에 인덱스를 효율적으로 이용하지 못함
(1) mysql> ... WHERE hire_date>STR_TO_DATE('2023-03-13', '%Y-%m-%d');
(2) mysql> ... WHERE hire_date>'2023-03-13';
(3) mysql> ... WHERE DATE_FORMAT(hire_date, '%Y-%m-%d') > '2023-03-13';

  1. SCE(Short-Circuit Evaluation)
  • 자바처럼(?) 여러 조건 중 선행 조건을 만족하지 못하는 경우, 후행 조건 실행 X
boolean in_transaction = false;

// has_modified() 실행 X
if ( in_transaction && has_modified() ) {
	commit();
}
  • 1번 수행 후 2번 수행: 244만건 조회 후 0건 조회
  • 2번 수행 후 1번 수행: 0건 조회 끝!
mysql > SELECT COUNT(*) FROM salaries;
 -> COUNT(*) = 2844047

-- 1번 조건
mysql > SELECT COUNT(*) FROM salaries 
				WHERE CONVERT_TZ(from_date, '+00:00', '+09:00')>'1991-01-01')
 -> COUNT(*) = 2442943

-- 2번 조건
mysql > SELECT COUNT(*) FROM salaries WHERE to_date<'1985-01-01';
 -> COUNT(*) = 0

  1. NOT IN
  • NOT IN은 안티 세미 조인 ... 가능하면 다른 조건으로 변경하고 사용하지 말 것
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant