Sochi419のブログ

プログラミング初学者です。Ruby, JavaScriptを学習中です。猫が好きです。フィヨルドブートキャンプというスクールの受講生です。

PostgreSQLの操作まとめ

バージョンを確認

psql --version

postgresql起動

brew services start postgresql

postgresqlの状態を確認

brew services list

サービスのリストを出力することで、postgresqlが起動しているかチェックできる。

% brew services list
Name       Status  User  Plist
mysql      stopped       
postgresql started user /Users/user/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

データベース一覧を表示

 psql -l
% psql -l
                          List of databases
    Name     | Owner | Encoding | Collate | Ctype | Access privileges 
-------------+-------+----------+---------+-------+-------------------
 postgres    | user | UTF8     | C       | C     | 
 template0   | user | UTF8     | C       | C     | =c/user         +
             |       |          |         |       | user=CTc/user
 template1   | user | UTF8     | C       | C     | =c/user         +
             |       |          |         |       | user=CTc/user

データベース作成

まずは、データベースのpostgresにログインする。 データベースを何も作成していない場合、まずはpostgresにログインしてから他のデータベースを作成する。(自分はpostgresqlにログインするのをやっていなくて、数時間ハマりました)

psql postgres
psql (14.5)
Type "help" for help.

postgres=# 

入力待ち状態になる。

↓データベース作成コマンド↓

create database mydb;

テーブル作成

先ほど作成したdbに接続する。

psql mydb

↓テーブル作成コマンド↓

create table books(id integer, name text);
CREATE TABLE テーブル名(カラム名 データタイプ, … );

デーブルの情報は\d テーブル名で確認できます。

mydb=# \d books
               Table "public.books"
 Column |  Type   | Collation | Nullable | Default 
--------+---------+-----------+----------+---------
 id     | integer |           |          | 
 name   | text    |           |          | 

テーブルにデータを追加

全てのカラムにデータを入れる場合(全カラムでnillがない場合)は、順番にカラムの値を指定できる。

insert into books values (1, 'はらぺこあおむし');

指定したカラムにデータを入れる場合、こんな感じで指定する。

insert into books (id, name) values (2, 'ぐりとぐら');

テーブルのデータを取得

  • 全データを取得の場合
select * from books;
mydb=# select * from books;
 id |       name       
----+------------------
  1 | はらぺこあおむし
  2 | ぐりとぐら
(2 rows)
  • 特定のデータを取得の場合
mydb=# select name from books;
       name       
------------------
 はらぺこあおむし
 ぐりとぐら
(2 rows)

postgresqlを停止

brew services stop postgresql