PostgreSQL : 텍스트와 varchar의 차이점 (문자가 다름)
text
데이터 유형과 character varying
( varchar
) 데이터 유형 의 차이점은 무엇입니까 ?
문서 에 따르면
길이 지정자없이 문자 가변이 사용되는 경우 유형은 모든 크기의 문자열을 허용합니다. 후자는 PostgreSQL 확장입니다.
과
또한 PostgreSQL은 모든 길이의 문자열을 저장하는 텍스트 유형을 제공합니다. 유형 텍스트는 SQL 표준에 없지만 다른 여러 SQL 데이터베이스 관리 시스템에도 텍스트가 있습니다.
그렇다면 차이점은 무엇입니까?
차이가 없습니다. 후드 아래에서 모두 varlena
( 가변 길이 배열 )입니다.
Depesz에서이 기사를 확인하십시오 : http://www.depesz.com/index.php/2010/03/02/charx-vs-varcharx-vs-varchar-vs-text/
몇 가지 주요 사항 :
요약하자면 :
- char (n) –보다 짧은 값을 다룰 때 너무 많은 공간을 차지하고
n
(으로 채움n
) 후행 공백 추가로 인해 미묘한 오류가 발생할 수 있으며 한계를 변경하는 데 문제가 있습니다.- varchar (n) – 라이브 환경에서 제한을 변경하는 데 문제가 있습니다 (테이블을 변경하는 동안 배타적 잠금이 필요함).
- varchar – 텍스트처럼
- text – 나에게는 승자 – 문제가 없기 때문에 (n) 데이터 유형에 대해, 그리고 varchar에 대해 – 고유 한 이름을 가지고 있기 때문에
이 기사는 4 가지 데이터 유형 모두에 대한 삽입 및 선택의 성능이 유사 함을 보여주기 위해 자세한 테스트를 수행합니다. 또한 필요할 때 길이를 제한하는 다른 방법을 자세히 살펴 봅니다. 함수 기반 제약 또는 도메인은 길이 제약의 즉각적인 증가의 이점을 제공하며, 문자열 길이 제약을 줄이는 것이 드물다는 점을 기반으로 depesz는 일반적으로 길이 제약에 대한 최선의 선택이라고 결론을 내립니다.
"와 같은 문자 유형 의 문서 점에서"밖으로 varchar(n)
, char(n)
그리고 text
모두 같은 방식으로 저장됩니다. 유일한 차이점은 길이를 확인하는 데 추가 사이클이 필요하고 (제공된 경우) 패딩이 필요한 경우 추가 공간과 시간이 필요하다는 것입니다 char(n)
.
그러나 단일 문자 만 저장해야하는 경우 특수 유형을 사용하면 약간의 성능 이점이 있습니다 "char"
(큰 따옴표를 유지하십시오. 유형 이름의 일부입니다). 필드에 더 빨리 액세스 할 수 있으며 길이를 저장하는 데 오버 헤드가 없습니다.
방금 "char"
소문자 알파벳에서 선택한 1,000,000 개의 테이블을 무작위로 만들었습니다 . 빈도 분포 ( select count(*), field ... group by field
) 를 가져 오는 쿼리 는 약 650 밀리 초가 걸리지 만 text
필드를 사용하는 동일한 데이터에서 약 760 초가 걸립니다 .
2016 년 기준 업데이트 (9.5 페이지 이상)
그리고 "순수 SQL"벤치 마크 사용 (외부 스크립트없이)
UTF8과 함께 string_generator를 사용하십시오.
주요 벤치 마크 :
2.1. 끼워 넣다
2.2. 비교 및 계산 선택
CREATE FUNCTION string_generator(int DEFAULT 20,int DEFAULT 10) RETURNS text AS $f$
SELECT array_to_string( array_agg(
substring(md5(random()::text),1,$1)||chr( 9824 + (random()*10)::int )
), ' ' ) as s
FROM generate_series(1, $2) i(x);
$f$ LANGUAGE SQL IMMUTABLE;
특정 시험 준비 (예시)
DROP TABLE IF EXISTS test;
-- CREATE TABLE test ( f varchar(500));
-- CREATE TABLE test ( f text);
CREATE TABLE test ( f text CHECK(char_length(f)<=500) );
기본 테스트를 수행하십시오.
INSERT INTO test
SELECT string_generator(20+(random()*(i%11))::int)
FROM generate_series(1, 99000) t(i);
그리고 다른 테스트,
CREATE INDEX q on test (f);
SELECT count(*) FROM (
SELECT substring(f,1,1) || f FROM test WHERE f<'a0' ORDER BY 1 LIMIT 80000
) t;
... 그리고 EXPLAIN ANALYZE
.
UPDATED AGAIN 2018 (pg10)
little edit to add 2018's results and reinforce recommendations.
Results in 2016 and 2018
My results, after average, in many machines and many tests: all the same
(statistically less tham standard deviation).
Recommendation
Use
text
datatype,
avoid oldvarchar(x)
because sometimes it is not a standard, e.g. inCREATE FUNCTION
clausesvarchar(x)
≠varchar(y)
.express limits (with same
varchar
performance!) by withCHECK
clause in theCREATE TABLE
e.g.CHECK(char_length(x)<=10)
.
With a negligible loss of performance in INSERT/UPDATE you can also to control ranges and string structure
e.g.CHECK(char_length(x)>5 AND char_length(x)<=20 AND x LIKE 'Hello%')
On PostgreSQL manual
There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead.
I usually use text
References: http://www.postgresql.org/docs/current/static/datatype-character.html
In my opinion, varchar(n)
has it's own advantages. Yes, they all use the same underlying type and all that. But, it should be pointed out that indexes in PostgreSQL has its size limit of 2712 bytes per row.
TL;DR: If you use text
type without a constraint and have indexes on these columns, it is very possible that you hit this limit for some of your columns and get error when you try to insert data but with using varchar(n)
, you can prevent it.
Some more details: The problem here is that PostgreSQL doesn't give any exceptions when creating indexes for text
type or varchar(n)
where n
is greater than 2712. However, it will give error when a record with compressed size of greater than 2712 is tried to be inserted. It means that you can insert 100.000 character of string which is composed by repetitive characters easily because it will be compressed far below 2712 but you may not be able to insert some string with 4000 characters because the compressed size is greater than 2712 bytes. Using varchar(n)
where n
is not too much greater than 2712, you're safe from these errors.
text and varchar have different implicit type conversions. The biggest impact that I've noticed is handling of trailing spaces. For example ...
select ' '::char = ' '::varchar, ' '::char = ' '::text, ' '::varchar = ' '::text
returns true, false, true
and not true, true, true
as you might expect.
Somewhat OT: If you're using Rails, the standard formatting of webpages may be different. For data entry forms text
boxes are scrollable, but character varying
(Rails string
) boxes are one-line. Show views are as long as needed.
character varying(n)
, varchar(n)
- (Both the same). value will be truncated to n characters without raising an error.
character(n)
, char(n)
- (Both the same). fixed-length and will pad with blanks till the end of the length.
text
- Unlimited length.
Example:
Table test:
a character(7)
b varchar(7)
insert "ok " to a
insert "ok " to b
We get the results:
a | (a)char_length | b | (b)char_length
----------+----------------+-------+----------------
"ok "| 7 | "ok" | 2
'IT박스' 카테고리의 다른 글
사전의 값으로 키 가져 오기 (0) | 2020.10.04 |
---|---|
Ruby에서 파일에 쓰는 방법? (0) | 2020.10.04 |
Google 크롬에서 HTTP 헤더를 보시겠습니까? (0) | 2020.10.04 |
내 시스템에서 RVM (Ruby 버전 관리자)을 제거하려면 어떻게해야합니까? (0) | 2020.10.04 |
명령 프롬프트 명령 실행 (0) | 2020.10.04 |