- SQLite Create Table
- Introduction to SQLite CREATE TABLE statement
- SQLite CREATE TABLE examples
- SQLite: CREATE TABLE Statement
- Description
- Syntax
- Parameters or Arguments
- Example
- Oracle PL/SQL •MySQL •MariaDB •SQL Server •SQLite
- Базы данных
- CREATE TABLE оператор SQLite
- Описание
- Синтаксис
- Параметры или аргументы
- Примечание
- Пример
- Database.Guide
- Beginners
- Categories
- Create a Table in SQLite
- Example
- Specify the Schema
- Data Type is Optional
- Constraints & Other Options
- Temporary Tables
- Create a Table from Another Table
- Создание базы данных и таблиц
- Создание и открытие базы данных
- Создание и удаление таблицы
- Первичный ключи и автоинкремент
- NOT NULL и DEFAULT
- Внешний ключ
SQLite Create Table
Summary: in this tutorial, you will learn how to create new tables using SQLite CREATE TABLE statement using various options.
Introduction to SQLite CREATE TABLE statement
To create a new table in SQLite, you use CREATE TABLE statement using the following syntax:
- First, specify the name of the table that you want to create after the CREATE TABLE keywords. The name of the table cannot start with sqlite_ because it is reserved for the internal use of SQLite.
- Second, use IF NOT EXISTS option to create a new table if it does not exist. Attempting to create a table that already exists without using the IF NOT EXISTS option will result in an error.
- Third, optionally specify the schema_name to which the new table belongs. The schema can be the main database, temp database or any attached database.
- Fourth, specify the column list of the table. Each column has a name, data type, and the column constraint. SQLite supports PRIMARY KEY , UNIQUE , NOT NULL , and CHECK column constraints.
- Fifth, specify the table constraints such as PRIMARY KEY , FOREIGN KEY , UNIQUE , and CHECK constraints.
- Finally, optionally use the WITHOUT ROWID option. By default, a row in a table has an implicit column, which is referred to as the rowid , oid or _rowid_ column. The rowid column stores a 64-bit signed integer key that uniquely identifies the row inside the table. If you don’t want SQLite creates the rowid column, you specify the WITHOUT ROWID option. A table that contains the rowid column is known as a rowid table. Note that the WITHOUT ROWID option is only available in SQLite 3.8.2 or later.
Note that the primary key of a table is a column or a group of columns that uniquely identify each row in the table.
SQLite CREATE TABLE examples
Suppose you have to manage contacts using SQLite.
Each contact has the following information:
The requirement is that the email and phone must be unique. In addition, each contact belongs to one or many groups, and each group can have zero or many contacts.
Based on these requirements, we came up with three tables:
- The contacts table that stores contact information.
- The groups table that stores group information.
- The contact_groups table that stores the relationship between contacts and groups.
The following database diagram illustrates tables: contacts groups , and contact_groups.
The following statement creates the contacts table.
The contact_id is the primary key of the contacts table.
Because the primary key consists of one column, you can use the column constraint.
The first_name and last_name columns have TEXT storage class and these columns are NOT NULL . It means that you must provide values when you insert or update rows in the contacts table.
The email and phone are unique therefore we use the UNIQUE constraint for each column.
The following statement creates the groups table:
The groups table is quite simple with two columns: group_id and name . The group_id column is the primary key column.
The following statement creates contact_groups table:
The contact_groups table has a primary key that consists of two columns: contact_id and group_id .
To add the table primary key constraint, you use this syntax:
In addition, the contact_id and group_id are the foreign keys. Therefore, you use FOREIGN KEY constraint to define a foreign key for each column.
Note that we will discuss in the FOREIGN KEY constraint in detail in the subsequent tutorial.
In this tutorial, you have learned how to create a new table with various options using SQLite CREATE TABLE statement.
SQLite: CREATE TABLE Statement
This SQLite tutorial explains how to use the SQLite CREATE TABLE statement with syntax and examples.
Description
The SQLite CREATE TABLE statement allows you to create and define a table.
Syntax
The syntax for the CREATE TABLE statement in SQLite is:
Parameters or Arguments
- There can only be one column in a table that is set as AUTOINCREMENT with a datatype of INTEGER. This column must be the primary key.
Example
Let’s look at a SQLite CREATE TABLE example.
This SQLite CREATE TABLE example creates a table called employees which has 4 columns and one primary key:
- The first column is called employee which is created as an INTEGER datatype. It has been defined as the primary key and is set as an AUTOINCREMENT field which means that it is an autonumber field (starting at 1, and incrementing by 1, unless otherwise specified.)
- The second column is called last_name which is a VARCHAR datatype and can not contain NULL values.
- The third column is called first_name which is a VARCHAR datatype and can contain NULL values.
- The fourth column is called hire_date which is a DATE datatype and can contain NULL values.
Next, let’s create a table that has a DEFAULT VALUE.
This SQLite CREATE TABLE example creates a table called products which has 3 columns and one primary key:
- The first column is called product_id which is created as an INTEGER datatype. It has been defined as the primary key and is set as an AUTOINCREMENT field.
- The second column is called product_name which is a VARCHAR datatype.
- The third column is called quantity which is an INTEGER datatype and can not contain NULL values. If no value is provided for this column, the DEFAULT VALUE will be 0.
Oracle PL/SQL •MySQL •MariaDB •SQL Server •SQLite
Базы данных
CREATE TABLE оператор SQLite
В этом учебном пособии вы узнаете, как использовать SQLite оператор CREATE TABLE с синтаксисом и примерами.
Описание
Оператор SQLite CREATE TABLE позволяет создавать и определять таблицу.
Синтаксис
Синтаксис оператора CREATE TABLE в SQLite:
Параметры или аргументы
table_name
Имя таблицы, которую вы хотите создать.
column1, column2
Столбцы, которые вы хотите создать в таблице.
datatype
тип данных для столбца.
Примечание
- В таблице может быть только один столбец, для которого задано значение AUTOINCREMENT с типом данных INTEGER. Этот столбец должен быть первичным ключом.
Пример
Рассмотрим пример SQLite CREATE TABLE.
В этом примере SQLite CREATE TABLE создается таблица с именем employees , которая имеет 4 столбца и один первичный ключ:
- Первый столбец называется employee , который создается как тип данных INTEGER. Он был определен как первичный ключ и установлен как поле AUTOINCREMENT, — это означает, что оно является полем автонумерации (начиная с 1 и с увеличением на 1, если не указано иное).
- Второй столбец называется last_name , который является типом данных VARCHAR и не может содержать значения NULL.
- Третий столбец называется first_name , который является типом данных VARCHAR и может содержать значения NULL.
- Четвертый столбец называется hire_date , который является типом данных DATE и может содержать значения NULL.
Далее, давайте создадим таблицу, которая имеет ЗНАЧЕНИЕ ПО УМОЛЧАНИЮ.
Database.Guide
Beginners
Categories
- Azure SQL Edge (15)
- Database Concepts (48)
- Database Tools (70)
- DBMS (8)
- MariaDB (417)
- Microsoft Access (17)
- MongoDB (265)
- MySQL (372)
- NoSQL (7)
- Oracle (295)
- PostgreSQL (251)
- Redis (132)
- SQL (587)
- SQL Server (871)
- SQLite (233)
Create a Table in SQLite
To create a table in SQLite, use the CREATE TABLE statement.
This statement accepts the table name, the column names and their definitions, as well as some other options.
Example
Here’s a basic example.
So in this case, Products is the name of the table, and it contains three columns; ProductId , ProductName , and Price .
In this example, I have added each column’s data type as well as some constraints, but these are all optional.
Specify the Schema
The table’s name can (optionally) be prefixed with the schema name. When doing this, the schema name must be either main , temp , or the name of an attached database.
So I could do this instead:
In this case, Store is the name of the attached database that I want to create the table in.
The column name can be followed by the data type and any constraints.
Data Type is Optional
Yes, you read that right – the data type is actually optional.
SQLite uses dynamic typing and so the data type of a value is associated with the value itself, not with its container (column). This is in contrast to most other SQL database systems, where you must specify the data type when you create the column.
So I could do this instead:
Constraints & Other Options
You have the option of specifying any constraints or other options you’d like to be applied against each column. These include the following:
- DEFAULT clause. This specifies a default value or expression for each column in the table.
- The COLLATE clause to specify the name of a collating sequence to use as the default collation sequence for the column. The default value is BINARY.
- PRIMARY KEY clause. You can optionally specify that a column is a primary key. Both single column and composite (multiple column) primary keys are supported in SQLite.
- SQLite also supports UNIQUE, NOT NULL, CHECK, and FOREIGN KEY constraints.
- A generated column constraint (also called a computed column). These are columns whose values are a function of other columns in the same row.
- Whether the table is a WITHOUT ROWID table. This is a performance optimisation technique that omits the “rowid” column that is a special column that SQLite uses by default. For more information on this technique, see the SQLite documentation.
Temporary Tables
You can specify that a table is a temporary table by using either the TEMP or TEMPORARY keyword.
If using one of these keywords, they must be inserted between the CREATE and TABLE .
Here’s an example:
You can also add the temp schema if you wish.
See How to Create a Temporary Table for more examples of creating temporary tables in SQLite.
Create a Table from Another Table
You can also use a CREATE TABLE . AS SELECT statement to create a new table based on another table. When you do this, the new table is populated with the data from the SELECT statement (which selects data from another table or tables).
Here’s a basic example:
This example creates a new table called Products2 and populates it with all data from the Products table.
All column names are the same as in the original table.
It’s important to note that tables created in this manner have no PRIMARY KEY and no constraints of any kind. Also, the default value of each column is NULL . Also, the default collation sequence for each column of the new table is BINARY.
Создание базы данных и таблиц
Создание и открытие базы данных
С помощью sqlite3 создать или открыть существующую базу данных можно двумя способами. Во-первых, при вызове утилиты sqlite3 в качестве аргумента можно указать имя базы данных. Если БД существует, она будет открыта. Если ее нет, она будет создана и открыта.
Во вторых, работая в самой программе, можно выполнить команду
Выяснить, какая база данных является текущей, можно с помощью команды .databases утилиты sqlite3. Если вы работаете с одной БД, а потом открываете другую, то текущей становится вторая БД.
Создание и удаление таблицы
Таблицы базы данных создаются с помощью директивы CREATE TABLE языка SQL. После CREATE TABLE идет имя таблицы, после которого в скобках перечисляются имена столбцов и их тип:
Имена как таблицы, так и столбцов принято писать строчными буквами. Если имя включает два слова, обычно их соединяют с помощью нижнего подчеркивания. Команды можно писать в одну строку, а не так, как показано выше.
Чтобы увидеть список таблиц базы данных используется команда .tables .
Для удаления целой таблицы из базы данных используется директива DROP TABLE, после которой идет имя удаляемой таблицы.
Первичный ключи и автоинкремент
Для реляционных баз данных важно, чтобы каждую запись-строку таблицы можно было однозначно идентифицировать. То есть в таблицах не должно быть полностью совпадающих строк. Записи должны отличаться хотя бы по одному полю.
С этой целью принято создавать дополнительное поле, которое часто называют ID или подобно. В базах данных под Android по соглашению столбец для уникального идентификатора записей называют _id.
При таком создании таблицы следить за уникальностью поля _id каждой записи должен будет человек. Для SQLite столбец _id ничем не отличается от любого другого. Мы вполне можем сделать несколько записей с одинаковым ID.
Чтобы исключить возможность ввода одинаковых идентификаторов, столбец ID назначают первичным ключом. PRIMARY KEY – ограничитель, который заставляет СУБД проверять уникальность значения данного поля у каждой добавляемой записи.
Если нам не важно, какие конкретно идентификаторы будут записываться в поле _id, а важна только уникальность поля, следует назначить полю еще один ограничитель – автоинкремент – AUTOINCREMENT.
В этом случае SQLite будет сам записывать в поле уникальное целочисленное значение по нарастающей от записи к записи. Поскольку это поле заполняется автоматически, то при добавлении записи в таблицу его игнорируют.
NOT NULL и DEFAULT
Ограничитель NOT NULL используют, чтобы запретить оставление поля пустым. По умолчанию, если поле не является первичным ключом, в него можно не помещать данные. В этом случае полю будет присвоено значение NULL. В случае NOT NULL вы не сможете добавить запись, не указав значения соответствующего поля.
Однако, добавив ограничитель DEFAULT, вы сможете не указывать значение. DEFAULT задает значение по умолчанию. В результате, когда данные в поле не передаются при добавлении записи, поле заполняется тем, что было указано по умолчанию.
Допустим, в таблице поля url, theme и num не должны быть пустыми. При этом если значение для num не передается, то полю присваивается 0. В этом случае команда для создания таблицы будет такой:
С помощью команд .schema и PRAGMA TABLE_INFO() можно посмотреть схему таблицы.
Внешний ключ
С помощью внешнего ключа устанавливается связь между записями разных таблиц. Внешний ключ в одной таблице для другой является первичным. Внешние ключи не обязаны быть уникальными. В одной таблице может быть несколько внешних ключей, при этом каждый будет устанавливать связь со своей таблицей, где он является первичным.
Представим, что у нас есть вторая таблица, в которой перечислены темы-разделы, а их номера являются уникальными идентификаторами.
Тогда в первой таблице в столбце theme следует хранить номера тем – их ID, взятые из второй таблицы. Это будут внешние ключи, представляющие собой первичные в таблице с разделами. Внешние ключи уникальными не будут, так как разные страницы могут принадлежать к одной и той же теме.
FOREIGN KEY является ограничителем, так как не дает нам записать в поле столбца theme какое-либо иное значение, которое не встречается в качестве первичного ключа в таблице sections. Однако в SQLite поддержка внешнего ключа по умолчанию отключена. Поэтому, даже назначив столбец внешним ключом, вы сможете записывать в его поля любые значения.
Чтобы включить поддержку внешних ключей в sqlite3, надо выполнить команду PRAGMA foreign_keys = ON; . После этого добавить в таблицу запись, в которой внешний ключ не совпадает ни с одним первичным из другой таблицы, не получится.