Sqlite первичный ключ что это
Перейти к содержимому

Sqlite первичный ключ что это

  • автор:

Sqlite первичный ключ что это

При определении столбцов и таблиц для них можно задать ограничения. Ограничения позволяют настроить поведение столбцов и таблиц. Ограничения столбцов указываются после типа столбца:

Ограничения таблицы указываются после определения всех столбцов.

Рассмотрим, какие ограничения столбцов мы можем использовать.

PRIMARY KEY

Атрибут PRIMARY KEY задает первичный ключ таблицы. Первичный ключ уникально идентифицирует строку в таблице. Например:

Здесь столбец id выступает в качестве первичного ключа, он будет уникально идентифицировать строку и его значение должно быть уникальным. То есть у нас не может быть таблице users более одной строки, где в столбце id было бы одно и то же значение.

Установка первичного ключа на уровне таблицы:

Первичный ключ может быть составным. Такой ключ использовать сразу несколько столбцов, чтобы уникально идентифицировать строку в таблице. Например:

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

AUTOINCREMENT

Ограничение AUTOINCREMENT позволяет указать, что значение столбца будет автоматически увеличиваться при добавлении новой строки. Данное ограничение работает для столбцов, которые представляют тип INTEGER с ограничением PRIMARY KEY :

В данном случае значение столбца id каждой новой добавленной строки будет увеличиваться на единицу.

UNIQUE

Ограничение UNIQUE указывает, что столбец может хранить только уникальные значения.

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

Также мы можем определить это ограничение на уровне таблицы:

В данном случае уникальность значений устанавлена сразу для двух столбцов — name и email.

NULL и NOT NULL

По умолчанию любой столбец, если он не представляет первичный ключ, может принимать значение NULL , то есть фактически отсутствие формального значения. Но если мы хотим запретить подобное поведение и установить, что столбец обязательно должен иметь какое-либо значение, то для него следует установить ограничение NOT NULL :

В данном случае столбец name не допускает значение NULL.

DEFAULT

Ограничение DEFAULT определяет значение по умолчанию для столбца. Если при добавлении данных для столбца не будет предусмотрено значение, то для него будет использоваться значение по умолчанию.

Здесь столбец age в качестве значения по умолчанию имеет число 18.

CHECK

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

Кроме проверки возраста здесь также проверяется, что столбец name не может иметь пустую строку в качестве значения (пустая строка не эквивалентна значению NULL).

Для соединения условий используется ключевое слово AND . Условия можно задать в виде операций сравнения больше (>), меньше (<), не равно (!=).

Также CHECK можно использовать на уровне таблицы:

Оператор CONSTRAINT. Установка имени ограничений

С помощью оператора CONSTRAINT можно задать имя для ограничений. Они указываются после ключевого слова CONSTRAINT перед ограничениями на уровне таблицы:

В данном случае ограничение для PRIMARY KEY называется users_pk, для UNIQUE — user_phone_uq, а для CHECK — user_age_chk. Смысл установки имен ограничений заключается в том, что впоследствии через эти имена мы сможем управлять ограничениями — удалять или изменять их.

How to use PRIMARY KEY in SQLite

So what are constraints and how do they work in SQLite? This write-up is a comprehensive guide about constraints and on how to use the PRIMARY key constraint in SQLite.

What are the constraints in SQLite

Constraints are the principles, according to which data of the same data type is inserted into the table, it organizes the structure of the column and also ensures the reliability of the data which is stored in the table. There are many constraints, some of them are:

  • Primary key
  • Foreign key
  • Unique constraint
  • Default constraint
  • Check constraint

What is the PRIMARY KEY in SQLite

A primary key is the unique column of the table, which ensures the entries inserted in the column should be unique and is also used to refer to the foreign key of other tables. The table can be created without using the primary key, but if the table is using the primary key, then only one primary key can be assigned to the table. Primary keys are very essential when creating a database that has a variety of tables, and to create relationships among the different databases, the primary key is used.

A primary key must follow these rules:

  • The column of the primary key cannot be defined with the NULL value
  • The data inserted in the rows of the column of the Primary key should be unique
  • The primary key should be referred to as the particular foreign key of another table
  • The table can contain only one primary key

A primary key cannot be a NULL value in the databases, but in the case of SQLite, it can be assigned a NULL value, because of the “long-standing coding oversight”.

A table should have only one primary key, but multiple columns can be defined in a single primary key, when multiple columns are being used as a single primary key, then it is called a composite primary key.

How many ways to add a primary key to any table in SQLite

There are two ways to assign a primary key while creating a table, which are:

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8
  • To the single column of a table
  • To the multiple columns of a table

How to create a table assigning a primary key to one column in SQLite

We can create a table by assigning a primary key to a single column, its general syntax will be:

The explanation of this syntax is as:

  • The clause of CREATE TABLE is used to create a table
  • Type the table name instead of table_name
  • Type the column name instead of column_name1, and also write its data type
  • Use a clause of PRIMARY KEY, if you are assigning the column as a primary key, and also define it as either NULL or NOT NULL
  • Type the name second column replacing column_name2

To understand it, consider an example: we create a table of school students, having the unique student ids, named, (std_id), and student names, named, (std_name). In this table, students names can be the same but students ids cannot be the same, so we assign the primary key to std_id as:

The table of school_students has been created, having a single column as a primary key.

How to create a table assigning a primary key to multiple columns in SQLite

We can create a table by assigning a primary key to multiple columns, its general syntax will be:

In the above syntax, we defined the primary key at the end of the statement, with the names of the column in parentheses that are to be included in the primary key.

Again to understand this, we consider an example of a table employees_data, we will create it with three columns which are emp_id, emp_name, and emp_dep, and after this we assign emp_id and emp_name as a PRIMARY KEY:

The table has been created with the primary key having two columns in it.

How to add a primary key to the existing table in SQLite

We cannot add a primary key to the existing table in SQLite using ALTER clause, but to assign a primary key to a table in SQLite, we will follow the steps:

  • The foreign key constraint should be checked off
  • Rename the table to some other name
  • Create a new table that has the same structure, which was created before
  • Copy the data from that table to this table
  • Delete the renamed table
  • In the end, turn on the foreign key constraints

We have a table in a database, named, students_data, which has no primary key and its contents can be displayed using:

To assign the “id” a primary key, we will run the following commands:

To check whether the primary key is assigned to the column named, id, run the command:

The primary key has successfully been assigned to the table students_data.

How to delete the primary key constraint in SQLite

Like other databases, we cannot drop the constraint by using the DROP and ALTER commands, to delete the PRIMARY KEY constraints we should follow the same procedure we opt for adding the constraint to an existing table and redefine the structure of the table without defining a primary key to any column. Let us consider the above example again of adding a primary key, and we delete the primary key as:

Conclusion

A primary key is very useful especially to establish relationships of a table with others, as a foreign key always refers to the primary key of the table, moreover, a table has only one primary key, but its fields can be one or more than one. In this article, we have discussed how the primary key is used in SQLite and also discussed with examples how a primary key is assigned to one or more columns as well as to the table which is already existing without a primary key.

About the author

Hammad Zahid

I’m an Engineering graduate and my passion for IT has brought me to Linux. Now here I’m learning and sharing my knowledge with the world.

Primary Keys SQLite

В SQLite первичный ключ — это отдельное поле или комбинация полей, однозначно определяющая запись. Таблица может иметь только один первичный ключ.

СОВЕТ . Хотя стандарты SQL-89 и SQL-92 не допускают значения NULL в первичном ключе, SQLite разрешает использование NULL при определенных обстоятельствах. Мы настоятельно рекомендуем не использовать значение NULL в первичном ключе.

Создать первичный ключ (оператор CREATE TABLE)

Первичный ключ может быть создан при выполнении оператора CREATE TABLE в SQLite.

Синтаксис

Синтаксис для создания первичного ключа с помощью оператора CREATE TABLE в SQLite:

CONSTRAINT constraint_name PRIMARY KEY (pk_col1, pk_col2, . pk_col_n)
);

table_name
Имя таблицы, которую вы хотите создать.

column1 , column2
Столбцы, которые вы хотите создать в таблице.

constraint_name
Название первичного ключа.

pk_col1 , pk_col2 , . pk_col_n
Столбцы, составляющие первичный ключ.

Пример

Рассмотрим пример того, как создать первичный ключ, используя оператор CREATE TABLE в SQLite. Мы начнем с очень простого, где наш первичный ключ состоит всего из одного столбца.

SQLite: Primary Keys

This SQLite tutorial explains how to create, add, and drop a primary key in SQLite with syntax and examples.

What is a primary key in SQLite?

In SQLite, a primary key is a single field or combination of fields that uniquely defines a record. A table can have only one primary key.

Create Primary Key (CREATE TABLE statement)

A primary key can be created when you execute a CREATE TABLE statement in SQLite.

Syntax

The syntax to create a primary key using the CREATE TABLE statement in SQLite is:

table_name The name of the table that you wish to create. column1, column2 The columns that you wish to create in the table. constraint_name The name of the primary key. pk_col1, pk_col2, . pk_col_n The columns that make up the primary key.

Example

Let’s look at an example of how to create a primary key using the CREATE TABLE statement in SQLite. We will start with a very simple one where our primary key consists of just one column.

In this example, we’ve created a primary key on the employees table called employees_pk. It consists of only one column — the employee_id column.

We could have used the alternate syntax and created this same primary key as follows:

Both of these syntaxes are valid when creating a primary key with only one field.

If you create a primary key that is made up of 2 or more columns, you are limited to using only the first syntax where the primary key is defined at the end of the CREATE TABLE statement.

This example creates a primary key on the customers table called customers_pk that is made up of a combination of the last_name and first_name columns. So each combination of last_name and first_name must be unique in the customers table.

Add Primary Key

If your table already exists and you wish to add a primary key later, you can not use the ALTER TABLE statement to create a primary key. Instead, you must create a new table with the primary key and copy the data into this new table.

Syntax

The syntax to add a primary key to a table in SQLite is:

table_name The name of the table to modify. This is the table that you wish to add a primary key to. old_table The name of the original table that will be left behind after you have created the new table with the primary key added. constraint_name The name of the primary key. pk_col1, pk_col2, . pk_col_n The columns that make up the primary key.

Example

Let’s look at an example of how to add a primary key to an existing table in SQLite. So say, we already have an employees table with the following definition:

And we wanted to add a primary key to the employees table that consists of the employee_id. We could run the following commands:

In this example, we’ve created a primary key on the employees table called employees_pk which consists of the employee_id column. The original table will still exist in the database called old_employees. You can drop the old_employees table once you have verified that your employees table and data are as expected.

Drop Primary Key

In SQLite, you can not use the ALTER TABLE statement to drop a primary key. Instead, you must create a new table with the primary key removed and copy the data into this new table.

Syntax

The syntax to drop a primary key from a table in SQLite is:

table_name The name of the table to modify. This is the table that you wish to remove the primary key from. old_table The name of the original table that will be left behind after you have created the new table with the primary key removed.

Example

Let’s look at an example of how to remove a primary key from an existing table in SQLite. So say, we already have a suppliers table with the following definition:

And we wanted to drop a primary key from the suppliers table. We could run the following commands:

In this example, we’ve dropped the primary key on the existing suppliers table. The original table will still exist in the database called old_suppliers. You can drop the old_suppliers table once you have verified that your suppliers table and data are as expected.

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

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