---
title: "PostgreSQL主键自增方法"
author: "Horse_Chasing"
date: "2016-03-31T00:19:07Z"
tags: []
categories: ["数据库"]
slug: "postgresql"
draft: false
lastmod: "2016-09-11T21:54:45Z"
id: 2287650
url: "https://horse-chasing.iteye.com/blog/2287650"
---

PG主键自增，方式跟oracle类似
1、首先创建序列
CREATE SEQUENCE test_c_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;
 
2、如果表已经存在了，则执行下面语句：
alter table test_c alter column id set default nextval('test_c_id_seq');
 
3、如果表不存在，则：
create table table_name(
     id int not null primary key default nextval('id_seq'),
     name varchar(30)


)


所有博客已经转移至leanote：<http://blog.leanote.com/shiwei/>

或者：<http://luoshiwei.me/>