SQLは基本的に各データベースに接続し、その中にあるテーブルを操作してデータを使うことになる
データベースを作成するときはCREATE DATABASE データベース名
で作成する
作成したDBは\l
で一覧を確認できる
postgres=# create database goya;
CREATE DATABASE
postgres=# create database tomato;
CREATE DATABASE
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
goya | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
tomato | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
(5 rows)
postgres=#
テーブル操作
・DB接続
\c データベース名
で接続できる
postgres=# \c goya;
You are now connected to database "goya" as user "postgres".
goya=#
・テーブル作成
create table テーブル名(カラム名 データ型);
でテーブル作成
テーブルに登録するデータにはそれぞれデータ型が存在し、データの種類によってそれを扱う必要がある。
データ型 | 説明 |
---|---|
text | 文字列 |
date | 年月日 |
integer | 整数 |
float | 小数点 |
boolean | 真(true)/偽(false) |
goya=# create table crops (
goya(# length float,
goya(# weight integer,
goya(# quality boolean,
goya(# give_for text,
goya(# date date);
CREATE TABLE
goya=#
・テーブル一覧作成
\dt;
・テーブル詳細確認
\d テーブル名;
goya=# \dt
List of relations
Schema | Name | Type | Owner
--------+-------+-------+----------
public | crops | table | postgres
public | price | table | postgres
(2 rows)
goya=# \d crops
Table "public.crops"
Column | Type | Modifiers
----------+------------------+-----------
length | double precision |
weight | integer |
quality | boolean |
give_for | text |
date | date |
goya=# \d price
Table "public.price"
Column | Type | Modifiers
----------+---------+-----------
give_for | text |
price | integer |
goya=#
CSVによるデータインポート
テーブルにCSVファイルを使用してデータをインポートすることができる
copy テーブル名 from 'CSVファイル' WITH CSV;