백엔드 Back-end/데이터베이스 Database

MySQL 데이터베이스명, 테이블명, 컬럼명은 어떻게 지어야 할까?

Tap to restart 2020. 10. 29. 15:00
반응형

database naming conventions라고 검색해 본다.
convention은 관습이란 뜻이다.

다른 사람들은 어떻게 이름을 만들어서 쓰고 있을까?

dev.mysql.com

Write SQL statements in the style of the MySQL Reference Manual
SQL keywords and reserved words: uppercase
Identifiers (table names, column names, etc.): lowercase
(출처: dev.mysql.com)

SQL 키워드 예약어는 대문자로 작성
테이블명, 컬럼명 등은 소문자로.

SQL Style Guide by Simon Holywell

여기 내용이 좋은 거 같다.
(출처: www.sqlstyle.guide/)

General
● Ensure the name is unique and does not exist as a reserved keyword.
● Keep the length to a maximum of 30 bytes—in practice this is 30 characters unless you are using a multi-byte character set.
● Names must begin with a letter and may not end with an underscore.
● Only use letters, numbers and underscores in names.
● Avoid the use of multiple consecutive underscores—these can be hard to read.
● Use underscores where you would naturally include a space in the name (first name becomes first_name).
● Avoid abbreviations and if you have to use them make sure they are commonly understood.

일반

● 유일한 이름, 예약어가 아닐 것.
● 30바이트 이내로.
● 문자로 시작하고, _으로 끝나지 않게
● 문자, 숫자, _만 사용
● _ 두번 이상 쓰지 않기
● 빈칸 대신 _ 사용 예) first name -> first_name
● 축약형 피하기. 일반적으로 이해할 수 있는 단어가 아니라면.

Tables
● Use a collective name or, less ideally, a plural form. For example (in order of preference) staff and employees.
● Do not prefix with tbl or any other such descriptive prefix or Hungarian notation.
● Never give a table the same name as one of its columns and vice versa.
● Avoid, where possible, concatenating two table names together to create the name of a relationship table. Rather than cars_mechanics prefer services.

테이블들

● 집단명사 사용하기. 이상적인 것은 아니지만 복수형 쓸 수 있다. 예) staff, employees
● 접두사 쓰지 말기 tbl 따위, 헝가리안 표기법 쓰지 말기.
● 테이블의 컬럼명 중 하나인 걸 테이블명으로 쓰지 말기. 반대 경우도 마찬가지. 테이블명을 컬럼명으로 쓰지 말기.
● 가능하면 두 테이블명을 연결해서 관계 테이블 이름을 만드는 걸 피하기. car_mechanics 보다는 services가 낫다.

Columns
● Always use the singular name.
● Where possible avoid simply using id as the primary identifier for the table.
● Do not add a column with the same name as its table and vice versa.
● Always use lowercase except where it may make sense not to such as proper nouns.

컬럼들

● 항상 단수 사용
● 가능하면 테이블 기본키로 id를 사용하지 않기
● 테이블의 이름을 컬럼명으로 쓰지 말기. 테이블의 컬럼명 중 하나를 테이블 이름으로도 쓰지 말기.
● 항상 소문자 쓰기. 고유명사처럼 의미 전달이 안되는 경우가 아니라면.

Aliasing or correlations
● Should relate in some way to the object or expression they are aliasing.
● As a rule of thumb the correlation name should be the first letter of each word in the object’s name.
● If there is already a correlation with the same name then append a number.
● Always include the AS keyword—makes it easier to read as it is explicit.
● For computed data (SUM() or AVG()) use the name you would give it were it a column defined in the schema.

SELECT first_name AS fn FROM staff AS s1 JOIN students AS s2 ON s2.mentor_id = s1.staff_num;
SELECT SUM(s.monitor_tally) AS monitor_total FROM staff AS s;

별칭 또는 상관관계

● 별칭이란 것을 알 수 있게 개체 또는 표현으로 연관되어야.
● 경험으로 봤을 때 상관관계 이름은 개체 이름에 포함된 각 단어의 첫 번째 글자 (예) first_name AS fn
● 상관관계 이름 이미 썼다면 숫자를 덧붙이기. (예) FROM staff AS s1 JOIN students AS s2
● 별칭 사용시 AS 항상 쓸 것.

Stored procedures
The name must contain a verb.
Do not prefix with sp_ or any other such descriptive prefix or Hungarian notation.

저장된 프로시저
● 이름에 동사 포함하기
● sp_ 접두사 사용하지 않기, 헝가리안 표기법 쓰지 않기.

Uniform suffixes
The following suffixes have a universal meaning ensuring the columns can be read and understood easily from SQL code. Use the correct suffix where appropriate.
_id—a unique identifier such as a column that is a primary key.
_status—flag value or some other status of any type such as publication_status.
_total—the total or sum of a collection of values.
_num—denotes the field contains any kind of number.
_name—signifies a name such as first_name.
_seq—contains a contiguous sequence of values.
_date—denotes a column that contains the date of something.
_tally—a count.
_size—the size of something such as a file size or clothing.
_addr—an address for the record could be physical or intangible such as ip_addr.

자주쓰는 접미사

_id - 주키, 기본키
_status - 상태표시
_total - 합
_num - 숫자 포함하고 있음 표시
_name - 이름 예)first_name
_seq - 연속적인 값의 순서를 포함
_date - 뭔가의 날짜를 포함
_tally - 계산
_size - 파일 크기 또는 옷 따위의 크기
_addr - 주소 예) ip_addr

기타

Foreign Key 외래키 constraint 제약조건 이름은?

외래키를 자주 정의하게 된다.

MySQL 문서

(출처: dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html)

MySQL 문서에서는 테이블명_ibfk_1 이런 식으로 한다.
ibfk는 innodb foreign key의 약어다. (출처: dba.stackexchange.com/questions/15530/what-does-ibfk-stand-for-in-mysql)
공식문서를 참고해서
테이블명_fk_번호 또는 테이블명_fk_칼럼명
위 경우 child_fk_1, child_fk_parent_id로 말이다.
제약조건 constraint 이름은 데이터베이스 안에서 유일해야 한다.
겹쳐서는 안 된다. 제약조건명 자체는 쿼리문에서 쓸 일이 없다.
그냥 테이블명_fk_1 식으로 제약조건명을 적게 되면 겹치지 않게 된다.

mysql 공식문서에서는 테이블명은 child, parent처럼 복수형을 쓰지 않고 단수를 주로 쓴다.

정리

□ 예약어(SELECT)는 대문자로.
□ 테이블명은 복수형보다는 단수형
□ 컬럼명도 당연히 단수형
□ 데이터베이스, 테이블명, 컬럼명은 소문자와 _ 만 사용할 것.
□ 접두사 피할 것.

기타 자료

MariaDB Reserved Words: 마리아DB 예약어
MySQL Reserverd Words: MySQL 예약어

왜 테이블명은 단수가 더 잘 어울릴까 궁금해서 좀 더 찾아봤다.
The table naming dilemma: singular vs. plural
이 글이 설득력 있었다.
특히 이 부분에서.

"SELECT activity.name feels better than SELECT activities.name"

SELECT activity.name이 더 느낌이 좋다. SELECT activities.name보다.

반응형