SQL 入門演習

Sqliteman で既存のデータベースを開く

すでに作成済みのデータベースを,下記の手順で開くことができる.

以下の手順で,既存のデータベースファイルを開く. (Open an existing database file) q

  1. File」→ 「Open
  2. データベースファイルを開く

    * Ubuntu での実行例(「/home/ubuntuuser/mydb」を開く場合)

    データベースファイル /home/ubuntuuser/mydb を選び, 「開く」をクリック (Click '開く' after choosing the database file "/home/ubuntuuser/mydb2")

    * Windows での実行例(「C:\SQLite\mydb」を開く場合)

    データベースファイル C:\SQLite\mydb を選び, 「開く」をクリック (Click '開く' after choosing the database file "C:\SQLite\mydb")

    要するに,/home/<ユーザ名>/SQLite 3の mydb を選ぶ. 

SQL を用いたテーブル定義と一貫性制約の記述

以前の授業で定義した products テーブルを使う。 products テーブルのテーブル定義が残っている場合には、ここの操作は必要ない。 products テーブルのテーブル定義が残っていない場合には、次の手順で定義する。

SQL を用いて,products テーブルを定義し,一貫性制約を記述する. (Define 'products' table and specify integrity constrants of the table using SQL)

リレーショナル・スキーマ (relational schema): products( name, teacher_name, student_name, score )
  1. products テーブルの定義 (Define a table)

    次の SQL を入力し,「Run SQL」のアイコンをクリック (Write the following SQL, and click "Run SQL" icon).

    create table products (
        id            INTEGER  PRIMARY KEY autoincrement not null,
        product_name  TEXT     UNIQUE not null,
        type          TEXT     not null,
        cost          real,
        created_at    DATETIME not null );
    

    * 「SQL Editor」のウインドウには,SQL プログラムを書くことができる. In the 'SQL string' window, you can write down SQL program(s).

  2. コンソールの確認 (Inspect console)

    エラーメッセージが出ていないことを確認

SQL を用いたテーブルへの行の挿入

以前の授業で定義した products テーブルを使う。

下記の操作により、演習用のデータ(1000行)を、products テーブルに格納する。

  1. Sqliteman で、products右クリック (right click) し、「Populate Table...」を選ぶ.
  2. Number of Rows to Populate に「1000」を設定、 ecost の行は「Random Number」に設定し、 「Populate」をクリック
  3. 「Close」をクリック

条件を満足する行のみの表示 (List the rows which satisfy a given condition)

SELECT * FROM products WHERE id = 123;

LIKE と % の組み合わせ: 文字列のパターンマッチ

「aa」あるいは「aA」あるいは「Aa」あるいは「AA」を含むという条件での検索。 検索条件では「'%AA%'」と書いている。 大文字と小文字の両方が検索条件にマッチする。

SELECT * FROM products WHERE type LIKE '%AA%';
ORDER BY と COUNT の組み合わせ: ソート group by と COUNT の組み合わせ: グループごとの数え上げ group by と COUNT と HAVING の組み合わせ: COUNT で数えたタップル数に関して条件を指定し,タップルを絞り込む.