PK 타입 설정: INT or STR ?

김맥스·2023년 3월 26일

데이터베이스

목록 보기
2/3
post-thumbnail

PK 설정 이유

  • PK의 특성 : B*tree Index, Unique, Not Null
  • PK는 테이블에서 오직 한개만 존재할 수 있으며, 이 PK는 테이블에서 데이터의 유일성을 보장
  • 관계형 데이터베이스에서는 반드시 각 행이 고유하게 식별되어야 하고, 이 규칙을 위반하면 더 이상 관계형이 아니며 데이터에서 모호함이 생길 수 있음
  • 대부분의 경우에 PK값을 기반으로 테이블의 행을 검색하거나 FK값으로 활용하여 다른 테이블과 결합

Primary Key는 int형으로 하는게 좋을까, str형으로 하는게 좋을까?

구글링

참조
https://stackoverflow.com/questions/2103322/varchar-as-foreign-key-primary-key-in-database-good-or-bad

The problem with VARCHAR being used for any KEY is that they can hold WHITE SPACE. White space consists of ANY non-screen-readable character, like spaces tabs, carriage returns etc. Using a VARCHAR as a key can make your life difficult when you start to hunt down why tables aren't returning records with extra spaces at the end of their keys.

Sure, you CAN use VARCHAR, but you do have to be very careful with the input and output. They also take up more space and are likely slower when doing a Queries.

Integer types have a small list of 10 characters that are valid, 0,1,2,3,4,5,6,7,8,9. They are a much better solution to use as keys.

You could always use an integer-based key and use VARCHAR as a UNIQUE value if you wanted to have the advantages of faster lookups.

ChatGPT에게 물어봤다.

When choosing a primary key for your database, it is generally recommended to use an integer type whenever possible. There are several reasons for this:

Efficiency: Integer types take up less space than character types, which makes them more efficient in terms of storage and indexing.

Performance: Because integer types are smaller in size, they can be processed more quickly by the database engine. This can result in faster queries and better performance overall.

Simplicity: Integer types are simpler to work with than character types, especially when it comes to querying the database. They are easier to sort, compare, and manipulate.

Consistency: Because integers have a well-defined range of values, they are less prone to data entry errors and inconsistencies than character types. This can help ensure the integrity of your database over time.

While there are some cases where a character type may be necessary for a primary key (for example, if you are working with legacy data that uses a character-based identifier), in most cases an integer type will be the better choice.

번역

당신의 데이터베이스에 대한 기본 키를 선택할 때는 가능한 경우 정수형을 사용하는 것이 일반적으로 권장됩니다. 그 이유는 다음과 같습니다:

  1. 효율성
    정수형은 문자형보다 적은 공간을 차지하기 때문에 저장 및 인덱싱 측면에서 더 효율적입니다.
  2. 성능
    정수형은 크기가 작기 때문에 데이터베이스 엔진에서 더 빠르게 처리될 수 있습니다. 이는 더 빠른 쿼리 및 전반적으로 더 나은 성능을 낼 수 있습니다.
  3. 간단함
    정수형은 쿼리하는 것과 같은 작업을 할 때 문자형보다 더 간단합니다. 정렬, 비교 및 조작하기가 더 쉽습니다.
  4. 일관성
    정수는 값의 범위가 정의되어 있기 때문에 문자형보다 데이터 입력 오류 및 일관성 문제가 덜 발생합니다. 이는 시간이 지남에 따라 데이터베이스의 무결성을 보장하는 데 도움이 됩니다.

일부 경우 문자형 기본 키가 필요한 경우가 있을 수 있습니다
(예: 문자 기반 식별자를 사용하는 기존 데이터 작업 등)
그러나 대부분의 경우 정수형이 더 나은 선택일 것입니다.

블록체인 엔티티의 경우는 어떠할지도 물어봤다

In a blockchain entity, the choice of primary key depends on the specific use case and the requirements of the application. However, there are some general principles that can guide the decision.

One approach is to use a unique identifier for each entity, such as a cryptographic hash of the entity's contents. This has the advantage of ensuring that each entity has a unique identifier that cannot be duplicated or tampered with. However, it can also be computationally expensive to calculate the hash for each entity.

Another approach is to use a sequential integer as the primary key, similar to traditional databases. This is simpler and more efficient, but it may not be suitable for certain types of blockchain applications where the order of transactions is critical.

In summary, the choice of primary key in a blockchain entity depends on the specific requirements of the application. Factors such as uniqueness, security, computational efficiency, and transaction order must be taken into consideration when making the decision.

번역

블록체인 엔터티에서 기본 키의 선택은 특정 사용 사례와 응용 프로그램 요구 사항에 따라 달라집니다. 그러나 결정을 지원하는 일반적인 원칙이 있습니다.

하나의 접근 방법은 각 엔터티에 대해 고유한 식별자(예: 엔터티 내용의 암호화 해시)를 사용하는 것입니다. 이렇게 하면 각 엔터티에 고유한 식별자가 있어 중복되거나 조작될 수 없다는 장점이 있습니다. 그러나 각 엔터티의 해시를 계산하는 것이 계산적으로 비싸다는 단점이 있습니다.

다른 접근 방법은 전통적인 데이터베이스와 유사하게 순차적인 정수를 기본 키로 사용하는 것입니다. 이것은 더 간단하고 효율적이지만, 트랜잭션 순서가 중요한 특정 유형의 블록체인 애플리케이션에는 적합하지 않을 수 있습니다.

요약하면, 블록체인 엔터티에서 기본 키의 선택은 특정 응용 프로그램 요구 사항에 따라 결정됩니다. 고유성, 보안성, 계산 효율성 및 트랜잭션 순서와 같은 요소는 결정을 내릴 때 고려해야 합니다.

profile
3년차 백엔드 개발자의 공부 기록

0개의 댓글