INSERT即向表中寫入數據,每條INSERT語句可以寫入一條數據,也可以寫入多條數據。另外還可以將其他的查詢結果集用在INSERT中,將查詢結果寫入表中。
測試表
test=# create table tbl_insert(a int,b varchar(32)); CREATE TABLE
示例1.單條記錄INSERT
test=# insert into tbl_insert (a,b) values (1,'test'); INSERT 0 1
示例2.多條記錄INSERT
和單條記錄INSERT的差別是各value間使用逗號分隔,最后一個value跟分號。
test=# insert into tbl_insert (a,b) values (2,'test'),(3,'sd'),(4,'ff'); INSERT 0 3
示例3.查詢結果INSERT
generate_series(1,10)生成1到10連續的10個數字,concat將參數串接在一起組成新的字符串,入參可以有很多個。
test=# insert into tbl_insert (a,b) select id,concat(id,'test') from generate_series(1,10) id; INSERT 0 10 test=# select * from tbl_insert ; a | b ----+-------- 1 | test 2 | test 3 | sd 4 | ff 1 | 1test 2 | 2test 3 | 3test 4 | 4test 5 | 5test 6 | 6test 7 | 7test 8 | 8test 9 | 9test 10 | 10test (14 rows)
示例4.SELECT INTO創建新表,並將查詢結果寫入表中,但是如果表已存在則會失敗。
test=# select * into tbl_insert1 from tbl_insert ; SELECT 14 test=# select * into tbl_insert1 from tbl_insert ; ERROR: relation "tbl_insert1" already exists