Как создать таблицу в postgresql
Перейти к содержимому

Как создать таблицу в postgresql

  • автор:

PostgreSQL CREATE TABLE

Summary: in this tutorial, you will learn how to use the PostgreSQL CREATE TABLE statement to create new a new table.

PostgreSQL CREATE TABLE syntax

A relational database consists of multiple related tables. A table consists of rows and columns. Tables allow you to store structured data like customers, products, employees, etc.

To create a new table, you use the CREATE TABLE statement. The following illustrates the basic syntax of the CREATE TABLE statement:

  • First, specify the name of the table after the CREATE TABLE keywords.
  • Second, creating a table that already exists will result in a error. The IF NOT EXISTS option allows you to create the new table only if it does not exist. When you use the IF NOT EXISTS option and the table already exists, PostgreSQL issues a notice instead of the error and skips creating the new table.
  • Third, specify a comma-separated list of table columns. Each column consists of the column name, the kind of data that column stores, the length of data, and the column constraint. The column constraints specify rules that data stored in the column must follow. For example, the not-null constraint enforces the values in the column cannot be NULL. The column constraints include not null, unique, primary key, check, foreign key constraints.
  • Finally, specify the table constraints including primary key, foreign key, and check constraints.

Note that some table constraints can be defined as column constraints like primary key, foreign key, check, unique constraints.

Constraints

PostgreSQL includes the following column constraints:

    – ensures that values in a column cannot be NULL . – ensures the values in a column unique across the rows within the same table. – a primary key column uniquely identify rows in a table. A table can have one and only one primary key. The primary key constraint allows you to define the primary key of a table. – a CHECK constraint ensures the data must satisfy a boolean expression. – ensures values in a column or a group of columns from a table exists in a column or group of columns in another table. Unlike the primary key, a table can have many foreign keys.

Table constraints are similar to column constraints except that they are applied to more than one column.

PostgreSQL CREATE TABLE examples

We will create a new table called accounts that has the following columns:

  • user_id – primary key
  • username – unique and not null
  • password – not null
  • email – unique and not null
  • created_on – not null
  • last_login – null

The following statement creates the accounts table:

PostgreSQL Create Table - accounts example

The following statement creates the roles table that consists of two columns: role_id and role_name :

PostgreSQL Create Table - roles example

The following statement creates the account_roles table that has three columns: user_id , role_id and grant_date .

PostgreSQL Create Table - account_roles example

The primary key of the account_roles table consists of two columns: user_id and role_id , therefore, we have to define the primary key constraint as a table constraint.

Because the user_id column references to the user_id column in the accounts table, we need to define a foreign key constraint for the user_id column:

The role_id column references the role_id column in the roles table, we also need to define a foreign key constraint for the role_id column.

The following shows the relationship between the accounts , roles , and account_roles tables:

Как создать таблицу в postgresql

You can create a new table by specifying the table name, along with all column names and their types:

You can enter this into psql with the line breaks. psql will recognize that the command is not terminated until the semicolon.

White space (i.e., spaces, tabs, and newlines) can be used freely in SQL commands. That means you can type the command aligned differently than above, or even all on one line. Two dashes ( “ — ” ) introduce comments. Whatever follows them is ignored up to the end of the line. SQL is case insensitive about key words and identifiers, except when identifiers are double-quoted to preserve the case (not done above).

varchar(80) specifies a data type that can store arbitrary character strings up to 80 characters in length. int is the normal integer type. real is a type for storing single precision floating-point numbers. date should be self-explanatory. (Yes, the column of type date is also named date . This might be convenient or confusing — you choose.)

The second example will store cities and their associated geographical location:

The point type is an example of a PostgreSQL -specific data type.

Finally, it should be mentioned that if you don’t need a table any longer or want to recreate it differently you can remove it using the following command:

Prev Up Next
2.2. Concepts Home 2.4. Populating a Table With Rows

Submit correction

If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.

Как создать таблицу в postgresql

Вы можете создать таблицу, указав её имя и перечислив все имена столбцов и их типы:

Весь этот текст можно ввести в psql вместе с символами перевода строк. psql понимает, что команда продолжается до точки с запятой.

В командах SQL можно свободно использовать пробельные символы (пробелы, табуляции и переводы строк). Это значит, что вы можете ввести команду, выровняв её по-другому или даже уместив в одной строке. Два минуса ( « — » ) обозначают начало комментария. Всё, что идёт за ними до конца строки, игнорируется. SQL не чувствителен к регистру в ключевых словах и идентификаторах, за исключением идентификаторов, взятых в кавычки (в данном случае это не так).

varchar(80) определяет тип данных, допускающий хранение произвольных символьных строк длиной до 80 символов. int — обычный целочисленный тип. real — тип для хранения чисел с плавающей точкой одинарной точности. date — тип даты. (Да, столбец типа date также называется date . Это может быть удобно или вводить в заблуждение — как посмотреть.)

Во втором примере мы сохраним в таблице города и их географическое положение:

Здесь point — пример специфического типа данных PostgreSQL .

Наконец, следует сказать, что если вам больше не нужна какая-либо таблица, или вы хотите пересоздать её по-другому, вы можете удалить её, используя следующую команду:

Как создать таблицу в postgresql

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

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

Например, создадим таблицу в базе данных через pgAdmin. Для этого вначале выберем в pgAdmin целевую базу данных, нажмем на нее правой кнопкой мыши и в контекстном меню выберем пункт Query Tool. :

Создание таблицы в базе данных PostgreSQL

После этого откроется поле для ввода кода на SQL. Причем таблица будет создаваться именно для той базы данных, для которой мы откровыем это поле для ввода SQL.

Далее в открывшееся в центральной части программы поле введем следующий набор выражений:

В данном случае в таблице Customers определяются пять столбцов: Id, FirstName, LastName, Age, Email. Первый столбец — Id представляет идентификатор клиента, он служит первичным ключом и поэтому имеет тип SERIAL . Фактически данный столбец будет хранить числовое значение 1, 2, 3 и т.д., которое для каждой новой строки будет автоматически увеличиваться на единицу.

Следующие три столбца представляют имя, фамилию клиента и его электронный адрес и имеют тип CHARACTER VARYING(30) , то есть представляют строку длиной не более 30 символов.

Последний столбец — Age представляет возраст пользователя и имеет тип INTEGER , то есть хранит числа.

Создание таблицы в pgAdmin

И после выполнения этой команды в выбранную базу данных будет добавлена таблица customers.

Удаление таблиц

Для удаления таблиц используется команда DROP TABLE , которая имеет следующий синтаксис:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *