[SQL][psql]基本指令(1)
這篇是整理一些 psql 的基本指令,
內容來自 Udacity 上 Intro to Relational Databases 的免費課程。
BASIC COMMANDS
Connect to psql
$ psql
Quit psql
$ \q
List all databases
$ \list
# or
$ \l
# exit from query result viewer
$ q
List all datatables in current database
# connect to the database
$ \connect dbname
# or
$ \c dbname
# list all tables
$ \dt
SQL COMMANDS
Create and Drop DATABASE
CREATE DATABASE dbname;
DROP DATABASE dbname;
Create and Drop TABLE
# Example: Create a table with a text column and a serial column
CREATE TABLE dtname (
id serial,
name text
);
# drop table dtname
DROP TABLE dtname;
Insert values
INSERT INTO dtname VALUES('This is a test');
Show all data in a table
TABLE dtname
# or
SELECT * FROM dtname
Set primary key
# single column primary key
CREATE TABLE dtname (
id serial primary key,
name text,
birthday date
);
# multiple columns primary key
CREATE TABLE postal_places (
postal_code text,
country text,
name text,
primary key (postal_code, country)
);
Declaring relationships
CREATE TABLE sales (
sku text references products (sku),
sale_date date,
count integer
);