Учебники

4) Создать, изменить, удалить таблицу

В этой статье мы увидим, как создавать таблицы, изменять таблицы и удалять таблицы в SQLite3 с примерами.

В этом уроке вы узнаете

SQLite Создать таблицу

Синтаксис

Ниже приведен синтаксис оператора CREATE TABLE.

CREATE TABLE table_name(
column1 datatype,
column1 datatype
);

Чтобы создать таблицу, вы должны использовать запрос «CREATE TABLE» следующим образом:

CREATE TABLE guru99 (
  Id Int,
  Name Varchar
);

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

  • Имя, имя столбца, оно должно быть уникальным среди столбцов таблицы.
  • Тип данных — тип данных столбца,
  • Необязательные ограничения столбцов, как мы объясним в последующих разделах этого руководства.

Дроп стол

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

DROP TABLE guru99;

Изменить стол

You can use «ALTER TABLE» command to rename a table as follows:

ALTER TABLE guru99 RENAME TO guru100;

To verify that the table’s name is changed, you can use the command «.tables» to show the list of tables and the table name should be changed now as following:

SQLite Create, Alter, Drop Table

As you can see the table name «guru99» is changed to «guru100» after the «alter table» command.

SQLite add columns- Using ALTER TABLE Command

You can also use the «ALTER TABLE» command to add columns:

ALTER TABLE guru100 ADD COLUMN Age INT;

This will alter the table «guru100» and add a new column Age to it.

  • If you didn’t see any output, this means that the statement was successful, and the column was added. No output means that the cursor will be positioned after «sqlite>» with no text after it like this

SQLite Create, Alter, Drop Table

  • However, to verify that the column was added, we can use the command «.schema guru100» this will give you the table definition, and you should see the new column we have just added:

SQLite Create, Alter, Drop Table

SQLite Insert value into a table

To insert values into a table, we use the «INSERT INTO» statement as follow:

INSERT INTO Tablename(colname1, colname2, ….) VALUES(valu1, value2, ….);

You can omit the columns names after the table name and write it as follows:

INSERT INTO Tablename VALUES(value1, value2, ….);

In such case, where you are omitting the columns names from the tables, the number of inserted values must be the same exact number of the table’s columns. Then each value will be inserted in the correspondence column. For example, for the following insert statement:

INSERT INTO guru100 VALUES(1, 'Mike', 25);

The result of this statement will be as following:

  • The value 1 will be inserted in the column «id«.
  • The value ‘Mike’ will be inserted in the column «Name«, and
  • The value 25 will be inserted in the column «Age«.

SQLite Create, Alter, Drop Table

INSERT … DEFAULT VALUES statement

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

INSERT INTO Tablename DEFAULT VALUES;

Если столбец не допускает нулевого значения или значения по умолчанию, вы получите сообщение об ошибке « Сбой ограничения NOT NULL» для этого столбца. Следующим образом:

SQLite Create, Alter, Drop Table