Синтаксис можно упрощенный инструкции create domain

CREATE DOMAIN — define a new domain

Synopsis

CREATE DOMAIN name [ AS ] data_type
    [ COLLATE collation ]
    [ DEFAULT expression ]
    [ constraint [ ... ] ]

where constraint is:

[ CONSTRAINT constraint_name ]
{ NOT NULL | NULL | CHECK (expression) }

Description

CREATE DOMAIN creates a new domain. A domain is essentially a data type with optional constraints (restrictions on the allowed set of values). The user who defines a domain becomes its owner.

If a schema name is given (for example, CREATE DOMAIN myschema.mydomain ...) then the domain is created in the specified schema. Otherwise it is created in the current schema. The domain name must be unique among the types and domains existing in its schema.

Domains are useful for abstracting common constraints on fields into a single location for maintenance. For example, several tables might contain email address columns, all requiring the same CHECK constraint to verify the address syntax. Define a domain rather than setting up each table’s constraint individually.

To be able to create a domain, you must have USAGE privilege on the underlying type.

Parameters

name

The name (optionally schema-qualified) of a domain to be created.

data_type

The underlying data type of the domain. This can include array specifiers.

collation

An optional collation for the domain. If no collation is specified, the domain has the same collation behavior as its underlying data type. The underlying type must be collatable if COLLATE is specified.

DEFAULT expression

The DEFAULT clause specifies a default value for columns of the domain data type. The value is any variable-free expression (but subqueries are not allowed). The data type of the default expression must match the data type of the domain. If no default value is specified, then the default value is the null value.

The default expression will be used in any insert operation that does not specify a value for the column. If a default value is defined for a particular column, it overrides any default associated with the domain. In turn, the domain default overrides any default value associated with the underlying data type.

CONSTRAINT constraint_name

An optional name for a constraint. If not specified, the system generates a name.

NOT NULL

Values of this domain are prevented from being null (but see notes below).

NULL

Values of this domain are allowed to be null. This is the default.

This clause is only intended for compatibility with nonstandard SQL databases. Its use is discouraged in new applications.

CHECK (expression)

CHECK clauses specify integrity constraints or tests which values of the domain must satisfy. Each constraint must be an expression producing a Boolean result. It should use the key word VALUE to refer to the value being tested. Expressions evaluating to TRUE or UNKNOWN succeed. If the expression produces a FALSE result, an error is reported and the value is not allowed to be converted to the domain type.

Currently, CHECK expressions cannot contain subqueries nor refer to variables other than VALUE.

When a domain has multiple CHECK constraints, they will be tested in alphabetical order by name. (PostgreSQL versions before 9.5 did not honor any particular firing order for CHECK constraints.)

Notes

Domain constraints, particularly NOT NULL, are checked when converting a value to the domain type. It is possible for a column that is nominally of the domain type to read as null despite there being such a constraint. For example, this can happen in an outer-join query, if the domain column is on the nullable side of the outer join. A more subtle example is

INSERT INTO tab (domcol) VALUES ((SELECT domcol FROM tab WHERE false));

The empty scalar sub-SELECT will produce a null value that is considered to be of the domain type, so no further constraint checking is applied to it, and the insertion will succeed.

It is very difficult to avoid such problems, because of SQL’s general assumption that a null value is a valid value of every data type. Best practice therefore is to design a domain’s constraints so that a null value is allowed, and then to apply column NOT NULL constraints to columns of the domain type as needed, rather than directly to the domain type.

PostgreSQL assumes that CHECK constraints’ conditions are immutable, that is, they will always give the same result for the same input value. This assumption is what justifies examining CHECK constraints only when a value is first converted to be of a domain type, and not at other times. (This is essentially the same as the treatment of table CHECK constraints, as described in Section 5.4.1.)

An example of a common way to break this assumption is to reference a user-defined function in a CHECK expression, and then change the behavior of that function. PostgreSQL does not disallow that, but it will not notice if there are stored values of the domain type that now violate the CHECK constraint. That would cause a subsequent database dump and restore to fail. The recommended way to handle such a change is to drop the constraint (using ALTER DOMAIN), adjust the function definition, and re-add the constraint, thereby rechecking it against stored data.

Examples

This example creates the us_postal_code data type and then uses the type in a table definition. A regular expression test is used to verify that the value looks like a valid US postal code:

CREATE DOMAIN us_postal_code AS TEXT
CHECK(
   VALUE ~ '^d{5}$'
OR VALUE ~ '^d{5}-d{4}$'
);

CREATE TABLE us_snail_addy (
  address_id SERIAL PRIMARY KEY,
  street1 TEXT NOT NULL,
  street2 TEXT,
  street3 TEXT,
  city TEXT NOT NULL,
  postal us_postal_code NOT NULL
);

Compatibility

The command CREATE DOMAIN conforms to the SQL standard.

CREATE DOMAIN-определение нового домена

Synopsis

CREATE DOMAIN name [ AS ] data_type
    [ COLLATE collation ]
    [ DEFAULT expression ]
    [ constraint [ ... ] ]

where constraint is:

[ CONSTRAINT constraint_name ]
{ NOT NULL | NULL | CHECK (expression) }

Description

CREATE DOMAIN создает новый домен. Домен — это, по сути, тип данных с необязательными ограничениями (ограничениями на разрешенный набор значений). Пользователь, определяющий домен, становится его владельцем.

Если указано имя схемы (например, CREATE DOMAIN myschema.mydomain ... ), то домен создается в указанной схеме. В противном случае он создается в текущей схеме. Доменное имя должно быть уникальным среди типов и доменов, существующих в его схеме.

Домены полезны для абстрагирования общих ограничений по полям в одном месте для обслуживания.Например,несколько таблиц могут содержать столбцы адресов электронной почты,все они требуют одного и того же ограничения CHECK для проверки синтаксиса адреса.Определите домен,а не настраивайте ограничения каждой таблицы по отдельности.

Чтобы иметь возможность создать домен, вы должны иметь право USAGE для базового типа.

Parameters

name

Имя (по желанию-схематическое)создаваемого домена.

data_type

Тип данных,лежащий в основе домена.Сюда могут входить спецификаторы массива.

collation

Необязательный параметр сортировки для домена. Если параметры сортировки не указаны, домен имеет то же поведение параметров сортировки, что и его базовый тип данных. Базовый тип должен быть сопоставлен, если COLLATE указан.

DEFAULT expression

Предложение DEFAULT определяет значение по умолчанию для столбцов типа данных домена. Значением является любое выражение без переменных (но подзапросы не допускаются). Тип данных выражения по умолчанию должен соответствовать типу данных домена. Если значение по умолчанию не указано, то значением по умолчанию является нулевое значение.

Выражение по умолчанию будет использоваться в любой операции вставки,которая не задает значение для столбца.Если значение по умолчанию определено для конкретного столбца,оно перекрывает любое значение по умолчанию,связанное с доменом.В свою очередь,значение по умолчанию домена отменяет любое значение по умолчанию,связанное с типом данных,лежащих в основе.

CONSTRAINT constraint_name

Необязательное имя для ограничения.Если не указано,система генерирует имя.

NOT NULL

Значения этого домена не могут быть нулевыми (но см.примечания ниже).

NULL

Значения этого домена могут быть нулевыми.Это значение по умолчанию.

Данное положение предназначено только для совместимости с нестандартными базами данных SQL.Его использование не рекомендуется в новых приложениях.

CHECK (expression)

CHECK определяют ограничения целостности или тесты, которым должны удовлетворять значения домена. Каждое ограничение должно быть выражением, дающим логический результат. Он должен использовать ключевое слово VALUE для обозначения тестируемого значения. Выражения, оцениваемые как ИСТИНА или НЕИЗВЕСТНО, завершаются успешно. Если выражение дает результат FALSE, выдается сообщение об ошибке и значение не может быть преобразовано в тип домена.

В настоящее время выражения CHECK не могут содержать подзапросы или ссылаться на переменные, отличные от VALUE .

Если для домена установлено несколько ограничений CHECK , они будут проверяться в алфавитном порядке по имени. (В версиях PostgreSQL до 9.5 не соблюдается какой-либо конкретный порядок CHECK ограничений CHECK .)

Notes

Ограничения домена, особенно NOT NULL , проверяются при преобразовании значения в тип домена. Столбец, который номинально относится к типу домена, может считаться нулевым, несмотря на наличие такого ограничения. Например, это может произойти в запросе внешнего соединения, если столбец домена находится на стороне внешнего соединения, допускающей значение NULL. Более тонкий пример:

INSERT INTO tab (domcol) VALUES ((SELECT domcol FROM tab WHERE false));

Пустой скаляр sub-SELECT выдаст нулевое значение,которое считается типом домена,поэтому к нему не применяется дополнительная проверка ограничений,и вставка будет успешной.

Избежать таких проблем очень сложно из-за общего предположения SQL о том, что нулевое значение является допустимым значением для каждого типа данных. Поэтому лучше всего разработать ограничения домена так, чтобы было разрешено значение NULL, а затем при необходимости применить ограничения NOT NULL столбца к столбцам типа домена, а не непосредственно к типу домена.

PostgreSQL предполагает, что условия ограничений CHECK неизменяемы, то есть они всегда будут давать один и тот же результат для одного и того же входного значения. Это предположение оправдывает CHECK ограничений CHECK только тогда, когда значение сначала преобразуется в доменный тип, а не в другое время. (По сути, это то же самое, что и обработка ограничений таблицы CHECK , как описано в Разделе 5.4.1 .)

Примером распространенного способа разрушить это предположение является ссылка на определяемую пользователем функцию в выражении CHECK , а затем изменение поведения этой функции. PostgreSQL не запрещает этого, но он не заметит, есть ли сохраненные значения доменного типа, которые теперь нарушают ограничение CHECK .Это приведет к сбою последующего дампа и восстановления базы данных. Рекомендуемый способ обработки такого изменения — удалить ограничение (используя ALTER DOMAIN ), скорректировать определение функции и повторно добавить ограничение, тем самым перепроверив его по сохраненным данным.

Examples

В этом примере создается us_postal_code данных us_postal_code, а затем этот тип используется в определении таблицы. Проверка регулярного выражения используется для проверки того, что значение похоже на действительный почтовый индекс США:

CREATE DOMAIN us_postal_code AS TEXT
CHECK(
   VALUE ~ '^d{5}$'
OR VALUE ~ '^d{5}-d{4}$'
);

CREATE TABLE us_snail_addy (
  address_id SERIAL PRIMARY KEY,
  street1 TEXT NOT NULL,
  street2 TEXT,
  street3 TEXT,
  city TEXT NOT NULL,
  postal us_postal_code NOT NULL
);

Compatibility

Команда CREATE DOMAIN соответствует стандарту SQL.


PostgreSQL

15.0

  • CREATE CONVERSION

    CREATE CONVERSION определить новую кодировку CREATE CONVERSION определяет новую между двумя кодировками набора символов.

  • CREATE DATABASE

    CREATE DATABASE new CREATE DATABASE creates new PostgreSQL Чтобы создать базу данных,вы должны быть суперпользователем или иметь специальную привилегию CREATEDB.

  • ВЫЗЫВАТЬ СОБЫТИЯ

    CREATE EVENT TRIGGER define new CREATE EVENT TRIGGER creates new Имя,которое нужно дать новому триггеру.

  • CREATE EXTENSION

    CREATE EXTENSION установить CREATE EXTENSION загружает новый в текущую базу данных.

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Used in : Postgre sql
    CREATE DOMAIN creates a new domain. A domain is essentially a data type with optional constraints (restrictions on the allowed set of values). The user who defines a domain becomes its owner.

    Domains are useful for abstracting common constraints on fields into a single location for maintenance. For example, several tables might contain email address columns, all requiring the same CHECK constraint to verify the address syntax. Define a domain rather than setting up each table’s constraint individually.

    Examples:

    CREATE DOMAIN CPI_DATA AS REAL CHECK
    (value >= 0 AND value <= 10);
    

    Now CPI_DATA domain is create so, we can use this domain anywhere in any table of database as below :

    CREATE TABLE student(
    sid char(9) PRIMARY KEY,
    name varchar(30),
    cpi CPI_DATA
    );
    

    Every time cpi_data will check the constraint, when you add data in student table.

    Example 1 :

    Insert into student values (201501408,Raj,7.5); 
    This will not violate the property of cpi. 
    

    Example 2 :

    Insert into student values (201501188,Dhaval,12); 
    ERROR. This will violate the property of cpi. 
    

    This article is contributed by Dhavalkumar Prajapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

    Last Updated :
    07 Sep, 2018

    Like Article

    Save Article

    CREATE DOMAIN statement creates a user-defined data type with a range, optional DEFAULT, NOT NULL and CHECK constraint. A domain is an alias for a built-in data type.

    Quick Example:

       -- Define a type
       CREATE DOMAIN addr VARCHAR(90);
     
       -- Use it in a table
       CREATE TABLE location (address addr);

    Overview:

    Syntax (full…) CREATE DOMAIN name [AS] datatype [constraints]
    DEFAULT Value
    NOT NULL and NULL NULL is the default
    CHECK Constraint VALUE keyword to reference checked column
    Composite Type Only single field
    Naming Columns and domain types can have the same name
    Alternative CREATE TYPE statement that supports complex (composite), enum and scalar types

    Version: PostgreSQL 9.1

    PostgreSQL CREATE DOMAIN Details

    CREATE DOMAIN statement allows you to create an alias for a built-in data type, and assign range and value constraints:

       CREATE DOMAIN addr VARCHAR(90) NOT NULL DEFAULT 'N/A';
     
       CREATE DOMAIN idx INT CHECK (VALUE > 100 AND VALUE < 999);

    Let’s create a sample table using the created domain types:

       CREATE TABLE location
       (
         address addr,
         index idx 
       );

    Note that idx domain contains VALUE keyword in the CHECK constraint that will be replaced by index column name when the constraint is checked.

    Let’s insert data:

       INSERT INTO location VALUES('Place', 200);
       -- 1 row affected
     
       -- Insert default address, and index NULL
       INSERT INTO location (index) VALUES(NULL);
       -- 1 row affected
     
       -- Insert address, and index that is out of range
       INSERT INTO location VALUES('Place', 20);
       -- Error: value for domain idx violates check constraint "idx_check"

    Note that CHECK constraint does not prevent from inserting NULL values, it is applied to not-NULL values only.

    Table content:

    address index
    ‘Place’ 200
    ‘N/A’ NULL

    Create an ID Type (Auto-increment or Identity)

    Using domains you can also create an ID type:

       CREATE SEQUENCE id_seq;
     
       CREATE DOMAIN id INT DEFAULT NEXTVAL('id_seq') NOT NULL;

    And then use it in tables as an identity (auto-increment) column:

       CREATE TABLE products
       (
          id id, 
          name VARCHAR(70)
       );
     
       INSERT INTO products (name) VALUES ('Cake');
       INSERT INTO products (name) VALUES ('Apple');

    Table content:

    Note that PostgreSQL SERIAL data type is implemented in a similar way.

    Create an Enumeration Type (Enum or Set of Values)

    You can use CREATE DOMAIN to create an enumeration type that can accept only values from a list:

       CREATE DOMAIN color VARCHAR(10)
         CHECK (VALUE IN ('red', 'green', 'blue'));

    Now let’s create a table and insert data:

      CREATE TABLE colors (color color);
     
      INSERT INTO colors VALUES ('red');
      -- 1 row affected
     
      INSERT INTO colors VALUES ('Red');
      -- ERROR: value for domain color violates check constraint "color_check"

    Note that values are case-sensitive. To allow case-insensitive check, you can use UPPER function in the CHECK constraint:

       CREATE DOMAIN color VARCHAR(10)
         CHECK (UPPER(VALUE) IN ('RED', 'GREEN', 'BLUE'));

    CREATE TYPE AS ENUM

    You can also use CREATE TYPE statement to create an enumeration type in PostgreSQL:

      CREATE TYPE color2 AS ENUM ('red', 'green', 'blue');

    Note that if CREATE TYPE is used, the sorting is performed in the order in which the values are listed in CREATE TYPE statement, not by the actual values.

    In case of CREATE DOMAIN, the sorting is based on values in columns:

       CREATE TABLE colors2
       (
          color color,       -- type created by CREATE DOMAIN
          color2 color2    -- type created by CREATE TYPE
       );
     
       -- Let's insert the same data and test sorting
       INSERT INTO colors2 VALUES ('red', 'red');
       INSERT INTO colors2 VALUES ('blue', 'blue');

    Sorting is different:

       -- Sort by CREATE DOMAIN type (alphabetical order)
       SELECT * FROM colors2 ORDER BY color;
       -- Result:
       -- blue   blue
       -- red    red
     
       -- Sort by CREATE TYPE type (by position)
       SELECT * FROM colors2 ORDER BY color2;
       -- Result:
       -- red    red
       -- blue   blue

    Resources

    Summary: in this tutorial, you will learn how to create PostgreSQL user-defined data type using CREATE DOMAIN and CREATE TYPE statements.

    Besides built-in data types, PostgreSQL allows you to create user-defined data types through the following statements:

    • CREATE DOMAIN creates a user-defined data type with constraints such as NOT NULL, CHECK, etc.
    • CREATE TYPE creates a composite type used in stored procedures as the data types of returned values.

    PostgreSQL CREATE DOMAIN statement

    In PostgreSQL, a domain is a data type with optional constraints e.g., NOT NULL and CHECK. A domain has a unique name within the schema scope.

    Domains are useful for centralizing the management of fields with common constraints. For example, some tables may have the same column that do not accept NULL and spaces.

    The following statement create a table named mailing_list:

    CREATE TABLE mailing_list (
        id SERIAL PRIMARY KEY,
        first_name VARCHAR NOT NULL,
        last_name VARCHAR NOT NULL,
        email VARCHAR NOT NULL,
        CHECK (
            first_name !~ 's'
            AND last_name !~ 's'
        )
    );Code language: SQL (Structured Query Language) (sql)

    In this table, both first_name and last_name columns do not accept null and spaces. Instead of defining the CHECK constraint, you can create a contact_name domain and reuse it in multiple columns.

    The following statement uses the CREATE DOMAIN to create a new domain called contact_name with the VARCHAR datatype and do not accept NULL and spaces:

    CREATE DOMAIN contact_name AS 
       VARCHAR NOT NULL CHECK (value !~ 's');Code language: SQL (Structured Query Language) (sql)

    And you use contact_name as the datatype of the first_name and last_name columns as a regular built-in type:

    CREATE TABLE mailing_list (
        id serial PRIMARY KEY,
        first_name contact_name,
        last_name contact_name,
        email VARCHAR NOT NULL
    );Code language: SQL (Structured Query Language) (sql)

    The following statement inserts a new row into the mailing_list table:

    INSERT INTO mailing_list (first_name, last_name, email)
    VALUES('Jame V','Doe','jame.doe@example.com');Code language: SQL (Structured Query Language) (sql)

    PostgreSQL issued the following error because the first name contains a space:

    ERROR:  value for domain contact_name violates check constraint "contact_name_check"
    Code language: SQL (Structured Query Language) (sql)

    The following statement works because it does not violate any constraints of the contact_name type:

    INSERT INTO mailing_list (first_name, last_name, email)
    VALUES('Jane','Doe','jane.doe@example.com');Code language: JavaScript (javascript)

    To change or remove a domain, you use the ALTER DOMAIN or DROP DOMAIN respectively.

    To view all domains in the current database, you use the dD command as follows:

    test=#dD
                                         List of domains
     Schema |     Name     |       Type        | Modifier |               Check
    --------+--------------+-------------------+----------+-----------------------------------
     public | contact_name | character varying | not null | CHECK (VALUE::text !~ 's'::text)
    (1 row)
    Code language: SQL (Structured Query Language) (sql)

    Getting domain information

    To get all domains in a specific schema, you use the following query:

    SELECT typname 
    FROM pg_catalog.pg_type 
      JOIN pg_catalog.pg_namespace 
      	ON pg_namespace.oid = pg_type.typnamespace 
    WHERE 
    	typtype = 'd' and nspname = '<schema_name>';Code language: JavaScript (javascript)

    The following statement returns domains in the public schema of the current database:

    SELECT typname 
    FROM pg_catalog.pg_type 
      JOIN pg_catalog.pg_namespace 
      	ON pg_namespace.oid = pg_type.typnamespace 
    WHERE 
    	typtype = 'd' and nspname = 'public';Code language: JavaScript (javascript)

    PostgreSQL CREATE TYPE

    The CREATE TYPE statement allows you to create a composite type, which can be used as the return type of a function.

    Suppose you want to have a function that returns several values: film_id, title, and release_year. The first step is to create a type e.g., film_summary as follows:

    CREATE TYPE film_summary AS (
        film_id INT,
        title VARCHAR,
        release_year SMALLINT
    ); 
    Code language: SQL (Structured Query Language) (sql)

    Second, use the film_summary data type as the return type of a function:

    CREATE OR REPLACE FUNCTION get_film_summary (f_id INT) 
        RETURNS film_summary AS 
    $$ 
    SELECT
        film_id,
        title,
        release_year
    FROM
        film
    WHERE
        film_id = f_id ; 
    $$ 
    LANGUAGE SQL;Code language: SQL (Structured Query Language) (sql)

    Third, call the get_film_summary() function:

    SELECT * FROM get_film_summary (40);Code language: SQL (Structured Query Language) (sql)

    PostgreSQL user-defined type example

    To change a user-defined type, you use the ALTER TYPE statement. To remove a user-defined type, you use the DROP TYPE statement.

    If you use the psql program, you can list all user-defined types in the current database using the dT or dT+ command:

    dvdrental=# dT
             List of data types
     Schema |     Name     | Description
    --------+--------------+-------------
     public | contact_name |
     public | film_summary |
     public | mpaa_rating  |
    (3 rows)Code language: SQL (Structured Query Language) (sql)

    In this tutorial, you have learned how to create PostgreSQL user-defined types using the CREATE DOMAIN and CREATE TYPE statements.

    Was this tutorial helpful ?

    Понравилась статья? Поделить с друзьями:
  • Урсофальк инструкция по применению цена капсулы взрослым для лечения отзывы
  • Инструкция по адресу обратилась к памяти по адресу 0x00000004
  • Дорс 200 детектор инструкция по применению
  • Saeco magic espresso инструкция на русском языке
  • Хотпоинт аристон холодильник двухдверный инструкция по эксплуатации