1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SQLデータベース超入門ノート1

1
Posted at

前提

今回はSQLの練習としてSQLite3を使います。

以下のコマンドでSQLite3をインストールします。

apt -y update
apt -y install sqlite3

データベース作成

データベースを作成します。

sqlite3 [ファイル名].sqlite3

格納される値のデータ型は以下の通り

  • NULL     NULL値
  • INTEGER    符号付整数。1, 2, 3, 4, 6, or 8 バイトで格納
  • REAL      浮動小数点数。8バイトで格納
  • TEXT     テキスト。UTF-8, UTF-16BE or UTF-16-LEのいずれかで格納
  • NUMERIC   数値データを格納

テーブルを作成します。

create table [テーブル名]( [カラム名][データ型], [カラム名][データ型]);

以下のコマンドで利用していない領域を解放します。

VACUUM;

以下のコマンドでデータを挿入します。
※文字列はシングルクォートで囲みます。

insert into [テーブル名] values([データ], [データ]);

テーブル名の変更

ALTER TABLE [テーブル名] RENAME TO [新しいテーブル名];

カラムの追加

ALTER TABLE テーブル名 ADD COLUMN [カラム名][データ型];

テーブル削除

DROP TABLE [テーブル名];

PRIMARY KEY 制約

CREATE TABLE テーブル名([カラム名] [データ型] PRIMARY KEY, ...);
CREATE TABLE テーブル名([カラム名1], [カラム名2], ... ,PRIMARY KEY([カラム名1], [カラム名2], ...));

integerを指定すると自動で連番が割り当てられます。

create table user(id integer primary key, name text);

データの確認

情報の確認

.tables
.databases

データの全件取得

select * from [テーブル名];

データの型取得

select [カラム名], typeof([カラム名]) from [テーブル名];

masterでデータ取得

select * from sqlite_master;
select * from sqlite_master where type='table' and name='[テーブル名]';

以下でスキーマ(履歴)を取得します。

.schema
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?