当前位置:网站首页>Kingbasees SQL language reference manual of Jincang database (3.1.1.14. scope type)
Kingbasees SQL language reference manual of Jincang database (3.1.1.14. scope type)
2022-07-26 23:13:00 【Thousands of sails passed by the side of the sunken boat_】
3.1.1.14. Range type
A range type is an expression of an element type ( Called scope subtype) The data type of a range of values . for example ,timestamp The range of can be used to express the time range that a meeting room is reserved . under these circumstances , The data type is tsrange(“timestamp range” Abbreviation ) and timestamp yes subtype.subtype There must be an overall order , In this way, the element value is within a range 、 Before or after that, the boundary is clear .
Range types are very useful , Because they can express multiple element values in a single range value , And it can clearly express concepts such as scope overlap . The time and date range used for scheduling is the clearest example ; But the price range 、 The measuring range of an instrument is also useful .
3.1.1.14.1. Built in scope type
KingbaseES With the following built-in scope types :
int4range—integerThe scope of theint8range—bigintThe scope of thenumrange—numericThe scope of thetsrange—Without a time zone timestampThe scope of thetstzrange—With time zone timestampThe scope of thedaterange—dateThe scope of the
Besides , You can define your own scope type , See CREATE TYPE sentence .
3.1.1.14.2. Example
CREATE TABLE reservation (room int, during tsrange);
INSERT INTO reservation VALUES
(1108, '[2010-01-01 14:30, 2010-01-01 15:30)');
-- contain
SELECT int4range(10, 20) @> 3;
-- overlap
SELECT numrange(11.1, 22.2) && numrange(20.0, 30.0);
-- Extract the upper bound
SELECT upper(int8range(15, 25));
-- Calculate the intersection
SELECT int4range(10, 20) * int4range(15, 25);
-- Is the range empty ?
SELECT isempty(numrange(1, 5));
The complete list of operators and functions on the scope type can be seen in the table 19-1 And the watch 19-2 .
3.1.1.14.3. Include and exclude boundaries
Every non empty range has two boundaries , Lower and upper bounds . All points between these values are included in the range . An inclusion boundary means that the boundary point itself is also included in the range , An excluded boundary means that the boundary points are not included in the range .
In the textual form of a range , A lower bound of inclusion is expressed as “[” And an exclusion lower bound is expressed as “(”. Again , A containing upper bound is expressed as “]” And an exclusion upper bound is expressed as “)”( See Range input / Output ).
function lower_inc and upper_inc Test the upper and lower bounds of a range value respectively .
3.1.1.14.4. Infinite ( unbounded ) Range
The lower bound of a range can be ignored , It means that all points less than the upper bound are included in the range . Again , If the upper bound of the range is ignored , Then everything larger than the upper bound is included in the scope . If the upper and lower bounds are ignored , All values of this element type are considered to be in this range .
This is equivalent to treating the lower bound as “ Negative infinity ”, Or take the upper bound as “ It's just infinite ”. But note that these infinite values are never values of the element type of the range , And by no means part of the scope ( Therefore, there is no such thing as including infinite boundaries — If you try to write a , It will be automatically converted into an exclusion boundary ).
also , Some element types have a “ Infinite ” Concept , But that's just another value beyond what the scope type mechanism cares about . for example , In the timestamp range ,[today,] Means with [today,) The same thing . however [today,infinity] Means with [today,infinity) Something different — The latter excludes special timestamp value infinity.
function lower_inf and upper_inf Test the infinite upper and lower bounds of a range respectively .
3.1.1.14.5. Range input / Output
The input of a range value must follow one of the following patterns :
(lower-bound,upper-bound) (lower-bound,upper-bound] [lower-bound,upper-bound) [lower-bound,upper-bound] empty
Parentheses or square brackets indicate whether the upper and lower bounds are excluded or included . Note that the last pattern is empty, It represents an empty range ( A range that does not contain points ).
``lower-bound`` It can be as subtype A string of legal input , Or empty means there is no lower bound . Again ,``upper-bound`` It can be as subtype A string of legal input , Or empty means there is no upper bound .
For each threshold value, you can use "( Double quotes ) Character reference . If the limit value contains parentheses 、 square brackets 、 comma 、 Double quotation marks or backslashes , This is necessary , Because otherwise, those characters will be considered as part of the range grammar . Put a double quotation mark or backslash in a quoted boundary value , Just put a backslash in front of it ( also , A pair of double quotation marks in the limit value of a double quotation mark reference represent a double quotation mark character , This is related to SQL The single quotation mark rule in a string is similar ). Besides , You can avoid references and use backslash escape to protect all data characters , Otherwise they will be treated as part of the return syntax . also , To write a limit value that is an empty string , So we can write this as "", Because nothing means an infinite limit .
Spaces are allowed before and after the range value , But any space between parentheses or square brackets will be treated as part of the upper and lower bounds ( Depends on the element type , It may or may not be meaningful ).
Be careful :
These rules are very similar to the rules for writing field values in combined type text . For more notes, see Combination type input and output syntax .
Example :
-- Include 3, barring 7, And includes 3 and 7 All points between SELECT '[3,7)'::int4range; -- It does not include 3 It doesn't include 7, But include all points between SELECT '(3,7)'::int4range; -- Only a single point is included 4 SELECT '[4,4]'::int4range; -- Not including points ( And will be standardized as ' empty ') SELECT '[4,4)'::int4range;
3.1.1.14.6. Construction scope
Each scope type has a constructor function with the same name . Using constructor functions is often more convenient than writing a range literal constant , Because it avoids additional references to boundary values . Constructor function accepts two or three parameters . The form of two parameters constructs a range in a standard form ( The lower bound is inclusive , The upper bound is excluded ), The form of three parameters constructs a range according to the boundary form specified by the third parameter . The third parameter must be one of the following strings : “()”、 “(]”、 “[)” perhaps “[]”. for example :
-- The complete form is : Lower bound 、 The inclusion of upper bounds and indicative bounds / Exclusive text parameters . SELECT numrange(1.0, 14.0, '(]'); -- If the third parameter is ignored , Then assume '[)'. SELECT numrange(1.0, 14.0); -- Although it is specified here '(]', When displayed, the value will be converted to the standard form , because int8range Is a discrete range type . SELECT int8range(1, 14, '(]'); -- Use for a boundary NULL The resulting range is unbounded on that side . SELECT numrange(NULL, 2.2);
3.1.1.14.7. Discrete range type
A range of element types has a well-defined “ step ”, for example integer or date. Among these types , If there is no legal value between two elements , They can be said to be adjacent . This is the opposite of the continuous range , Always in a continuous range ( Or almost always ) Other element values can be identified between two given values . for example ,numeric A range above a type is continuous ,timestamp So is the scope of ( Even though timestamp With limited accuracy , And in theory, it can be regarded as discrete , It's best to think of it as continuous , Because we usually don't care about its step size ).
Another way to consider discrete range types is to have a clear definition of each element value “ next ” or “ the previous ” value . After understanding this idea , Replace it by selecting the previously given next or previous element value , You can switch between the inclusion and exclusion expressions of a range boundary . for example , In an integer range type ,[4,8] and (3,9) Represents the same set of values , But for numeric This is not the case with the scope of .
A discrete range type should have a regularization function , It knows the expected step size of the element type . The normalization function is responsible for converting the equal values of the range type into the same expression , Especially consistent with the inclusion or exclusion boundaries . If a normalization function is not specified , Then ranges with different formats will always be treated as unequal , Even if they actually express the same set of values .
Built in scope type int4range、int8range and daterange All use a formal form , This form includes the lower bound and excludes the upper bound , That is to say [). however , Other conventions can be used for user-defined scope types .
3.1.1.14.8. Define new scope types
Users can define their own scope types . The most common reason for doing this is to use what is not provided in the built-in scope type subtype The scope of . for example , To create a subtype float8 Range type :
CREATE TYPE floatrange AS RANGE (
subtype = float8,
subtype_diff = float8mi
);
SELECT '[1.234, 5.678]'::floatrange;
because float8 There is no meaningful “ step ”, We do not define a normalization function in this example .
Defining your own scope type also allows you to specify a different subtype B- Tree operator class or collection , In order to change the sort order to determine which values will fall into the given range .
If subtype It is considered to have discrete values rather than continuous values ,CREATE TYPE The command should specify a canonical function . The normalization function receives an input range value , And must return an equivalent range value that may have different bounds and formats . For two ranges representing the same set of values ( for example [1, 7] and [1, 8)), The normal output must be the same . It doesn't matter which expression you choose as normal , As long as two equal values with different formats can always be mapped to the same value with the same format . In addition to adjustment, it includes / Exclude boundary format , Suppose the expected compensation ratio subtype The storage capacity should be large , A normalization function may round off the boundary value . for example , One timestamp The range type above may be defined as having a one hour step , In this way, the normalization function may need to round the bounds of multiples that are not one hour , Or maybe throw an error directly .
in addition , Any intention to contact GiST or SP-GiST The range type used with the index should be a subtype Difference or subtype_diff function ( No, subtype_diff The index still works , But the efficiency may not be as high as when the difference function is provided ).subtype The difference function uses two subtype The input values , And the return is represented as a float8 The difference between the values ( namely ``X`` reduce ``Y``). In our example above , You can use regular float8 Functions under the subtraction operator . But for any other subtype, Some type conversion may be required . You may also need some innovative ideas on how to express differences as numbers . For maximum scalability ,subtype_diff The function should agree with the sort order contained in the selected operator class and collation , in other words , As long as its first parameter is greater than the second parameter according to the sorting order , Its result should be positive .
subtype_diff A less simplistic example of a function :
CREATE FUNCTION time_subtype_diff(x time, y time) RETURNS float8 AS
'SELECT EXTRACT(EPOCH FROM (x - y))' LANGUAGE sql STRICT IMMUTABLE;
CREATE TYPE timerange AS RANGE (
subtype = time,
subtype_diff = time_subtype_diff
);
SELECT '[11:10, 23:00]'::timerange;
For more information about creating range types, please refer to CREATE TYPE sentence .
3.1.1.14.9. Indexes
You can create... For table columns of range type GiST and SP-GiST Indexes . for example , To create a GiST Indexes :
CREATE INDEX reservation_idx ON reservation USING GIST (during);
One GiST or SP-GiST Indexing can speed up queries involving the following range operators : =、 &&、 <@、 @>、 <<、 >>、 -|-、 &< as well as &> ( As shown in the table 19-1 ).
Besides ,B- Trees and hash indexes can be created on table columns of range type . For these index types , Basically, the only useful scope operation is equivalence . Use corresponding < and > The operator , For the definition of range value, there is a B- Tree sort order , But this order is quite arbitrary and usually not very useful in the real world . Range type B- Tree and hash support is mainly to allow sorting and hashing within queries , Instead of creating a real index .
3.1.1.14.10. Constraints on scope
although UNIQUE Is a natural constraint on scalar values , It is usually not suitable for range types . Instead, , An exclusion constraint is often more appropriate ( see CREATE TABLE Medium CREATE TABLE ... CONSTRAINT ... EXCLUDE ). Exclusion constraints allow descriptions on a range type such as “non-overlapping” Constraints . for example :
CREATE TABLE reservation (
during tsrange,
EXCLUDE USING GIST (during WITH &&)
);
This constraint will prevent any overlapping values from existing in the table at the same time :
INSERT INTO reservation VALUES
('[2010-01-01 11:30, 2010-01-01 15:00)');
INSERT 0 1
INSERT INTO reservation VALUES
('[2010-01-01 14:45, 2010-01-01 15:45)');
ERROR: conflicting key value violates exclusion constraint "
reservation_during_excl"
DETAIL: Key (during)=(["2010-01-01 14:45:00","2010-01-01 15:45:00")) conflicts
with existing key (during)=(["2010-01-01 11:30:00","2010-01-01 15:00:00")).
have access to btree_gist Extension to define exclusion constraints on pure scalar data types , Then combine it with scope exclusion to get maximum flexibility . for example , install btree_gist after , Only when the conference room numbers are equal , The following constraints will reject overlapping ranges :
CREATE EXTENSION btree_gist;
CREATE TABLE room_reservation (
room text,
during tsrange,
EXCLUDE USING GIST (room WITH =, during WITH &&)
);
INSERT INTO room_reservation VALUES
('123A', '[2010-01-01 14:00, 2010-01-01 15:00)');
INSERT 0 1
INSERT INTO room_reservation VALUES
('123A', '[2010-01-01 14:30, 2010-01-01 15:30)');
ERROR: conflicting key value violates exclusion constraint "
room_reservation_room_during_excl"
DETAIL: Key (room, during)=(123A, ["2010-01-01 14:30:00","2010-01-01
15:30:00")) conflicts
with existing key (room, during)=(123A, ["2010-01-01 14:00:00","2010-01-01
15:00:00")).
INSERT INTO room_reservation VALUES
('123B', '[2010-01-01 14:30, 2010-01-01 15:30)');
INSERT 0 1边栏推荐
- Dao:op token and non transferable NFT are committed to building a new digital democracy
- Counter attack dark horse: devdbops training, give you the best courses!
- 你知道磁环电感的常见磁芯类型有哪些吗?
- Too busy with scientific research to take care of your family? Chen Ting: life cannot have only one fulcrum
- Lighting 5g in the lighthouse factory, Ningde era is the first to explore the way made in China
- Regular expressions and bypass case recurrence
- Science | University of Washington uses AI and structural prediction to design new proteins
- 提前批到底影不影响正式批?
- After closing the Suzhou plant, Omron Dongguan plant announced its dissolution, and more than 2000 people are facing unemployment!
- Page file system based on C language
猜你喜欢
![[postgresql]postgresqlg use generate_ Series() function completes statistics](/img/62/893986eb97a61f4e9ef32abc8d2a90.png)
[postgresql]postgresqlg use generate_ Series() function completes statistics

Basic use of gateway

Arduino experiment I: two color lamp experiment

STM32 how to use serial port

杰理下载器强制下载工具的使用介绍_AC695N696NAD14AD15全系列支持
电脑开机后内存占用过高(50%以上)

Apifox--比 Postman 还好用的 API 测试工具

基本的SELECT语句
![[MySQL] - index principle and use](/img/e1/af74ee20ebe0c6e6f5e453330cc13b.png)
[MySQL] - index principle and use

Hcia-r & s self use notes (23) DHCP
随机推荐
程序员成长第二十九篇:如何激励员工?
P5469 [NOI2019] 机器人(拉格朗日插值、区间dp)
The secret weapon of apple iphone11 series: U1 chip may usher in the era of ultra wideband
json格式化小工具--pyqt5实例
Interview questions of Bank of Hangzhou [Hangzhou multi tester] [Hangzhou multi tester _ Wang Sir]
Docker uses mysql:5.6 and owncloud image to build a personal network disk, install and build a private warehouse harbor
The interviewer asked: this point of JS
[hcip] OSPF route calculation
Hcia-r & s self use notes (19) VLAN configuration and experiment, routing between VLANs
Network and VPC hands-on experiment
【MySQL】CentOS 7.9安装、使用MySQL-5.7.39二进制版
Plato farm is expected to further expand its ecosystem through elephant swap
[postgresql]postgresqlg use generate_ Series() function completes statistics
[untitled]
PostgreSQL and Navicat: the backbone of the database industry
Mate30 series release: how far can Huawei go in reconstructing images?
Science | University of Washington uses AI and structural prediction to design new proteins
2019 biometric forum successfully ended: these ten highlights should not be missed!
[hcip] OSPF external route introduction
Basic select statement