Auto increment table column - sql

Using Postgres, I'm trying to use AUTO_INCREMENT to number my primary key automatically in SQL. However, it gives me an error.
CREATE TABLE Staff (
ID INTEGER NOT NULL AUTO_INCREMENT,
Name VARCHAR(40) NOT NULL,
PRIMARY KEY (ID)
);
The error:
********** Error **********
ERROR: syntax error at or near "AUTO_INCREMENT"
SQL state: 42601
Character: 63
Any idea why?

Postgres 10 or later
(serial columns remain unchanged, see below.)
Consider a standard-SQL IDENTITY column. Can be GENERATED BY DEFAULT or (stricter) GENERATED ALWAYS.
Basics in the manual for CREATE TABLE.
Details in this blog entry by its principal author Peter Eisentraut.
Create table with IDENTITY column
CREATE TABLE staff (
staff_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY
, staff text NOT NULL
);
Add IDENTITY column to existing table
Table may or may not be populated with rows.
ALTER TABLE staff ADD COLUMN staff_id int GENERATED ALWAYS AS IDENTITY;
To also make it the PK at the same time (table can't have a PK yet):
ALTER TABLE staff ADD COLUMN staff_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY;
See:
How to add a PostgreSQL 10 identity column to an existing table with rows?
Replace serial with IDENTITY column
See:
How to change a table ID from serial to identity?
You can override system values or user input in INSERT commands with OVERRIDING {SYSTEM|USER} VALUE.
Postgres 9.6 or older
(Still supported in newer versions, too.)
Use the serial pseudo data type:
CREATE TABLE staff (
staff_id serial PRIMARY KEY,
, staff text NOT NULL
);
It creates and attaches the sequence object automatically and sets the DEFAULT to nextval() from the sequence. It does all you need.
I use legal, lower-case, unquoted identifiers in my examples. Makes your life with Postgres easier.

You do not specify which RDBMS you are using, however, in SQL Server you can use this syntax:
CREATE TABLE [dbo].[Staff]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] VARCHAR(40) NOT NULL,
CONSTRAINT [ID] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

In the SQL server database you can use Identity(1,1) like this:
CREATE TABLE Staff
(
ID INT IDENTITY(1,1) NOT NULL,
Name VARCHAR(40) NOT NULL,
PRIMARY KEY (ID)
);

PostgreSQL: If you absolutely must have your own auto increment value:
Then use a sequence:
ericlesc_schools=> drop table yar;
DROP TABLE
ericlesc_schools=> drop sequence user_id_seq;
DROP SEQUENCE
ericlesc_schools=> create sequence user_id_seq;
CREATE SEQUENCE
ericlesc_schools=> create table yar(
id int default nextval('user_id_seq'),
foobar varchar);
CREATE TABLE
ericlesc_schools=> insert into yar (foobar) values('hey alex');
INSERT 0 1
ericlesc_schools=> insert into yar (foobar) values('hey what derick');
INSERT 0 1
ericlesc_schools=> insert into yar (foobar) values('I look like a hushpuppy');
INSERT 0 1
ericlesc_schools=> select * from yar;
id | foobar
----+-----------------
1 | hey alex
2 | hey what derick
3 | I look like a hushpuppy
(3 rows)

Related

H2 refuses to create auto_increment for Postgres emulated database

I created an in memory H2 database with JDBC URL
jdbc:h2:~/test;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DEFAULT_NULL_ORDERING=HIGH
The H2 web console refuses to let me do an auto_increment. I've seen serial for Postgres, but that doesn't work either.
At it's simplest, it hates:
create table test(id bigint auto_increment);
Syntax error in SQL statement "create table test(id bigint [*]auto_increment)"; expected "ARRAY, INVISIBLE, VISIBLE, NOT NULL, NULL, AS, DEFAULT, GENERATED, ON UPDATE, NOT NULL, NULL, DEFAULT ON NULL, NULL_TO_DEFAULT, SEQUENCE, SELECTIVITY, COMMENT, CONSTRAINT, COMMENT, PRIMARY KEY, UNIQUE, NOT NULL, NULL, CHECK, REFERENCES, ,, )"; SQL statement:
create table test(id bigint auto_increment) [42001-214] 42001/42001 (Help)
Why do I care:
My code base was failing with NULL not allowed for column "REV". I'm using JPA/Hibernate + Liquibase. In order to try the suggestions at
Hibernate Envers + Liquibase: NULL not allowed for column "REV"
I'm trying to add an auto_increment to my Liquibase changelog file.
You can use the SQL Standard's generation clause GENERATED ALWAYS AS IDENTITY. For example:
create table test (
id bigint generated always as identity,
name varchar(10)
);
See PostgreSQL Example.
It works the same way in H2. For example:
create table test(id bigint generated always as identity, name varchar(10));
insert into test (name) values ('Chicago') ;
select * from test;
Result:
ID NAME
-- -------
1 Chicago

Error in primary key in sqlplus?

I am beginner in sql.I am using sqlplus to run the sql query .I used simple query but it shows an error like "MISSING RIGHT PARENTHESIS".My objective is to create the autoincrement primary key .Can anyone solve the error?Thanks in advance...
create table student(rollno int identity(1,1) primary key,
name varchar(20),marks int);
For Oracle, the rollno column could be defined as NUMBER(0010) and primary key.
Then you would need to add an ON INSERT trigger to populate rollno from a SEQUENCE. There are many samples of triggers and sequences on this site.
In oracle 12 you can use a identity column to automatically fill your ID
CREATE TABLE students
(
"ID" NUMBER GENERATED BY DEFAULT AS IDENTITY MINVALUE 1 MAXVALUE 9999999999
INCREMENT BY 1 START WITH 1 ,
"NAME" VARCHAR2(20),
"MARKS" NUMBER(2,0),
CONSTRAINT PK_STUDENTS PRIMARY KEY (ID) ENABLE
);
/
This creates a table without any triggers needed and automatically fills the id column (of not specified with a value) with the next number up to 99999...
If you're using oracle 11 and below, you need a trigger on insert and assign a value (custom_sequence.nextval) to the id column.
CREATE TABLE students
(
"ID" NUMBER(5,0) not null,
"NAME" VARCHAR2(20),
"MARKS" NUMBER(2,0),
CONSTRAINT PK_STUDENTS PRIMARY KEY (ID) ENABLE
);
/
CREATE SEQUENCE SEQ_STUDENTS INCREMENT BY 1 START WITH 1;
/
TRIGGER TC_students
before insert on students
for each row
begin
if (:new.id is null) then
select SEQ_students.nextval into :new.id from dual;
end if;
end;
/
And please use VARCHAR2.

Why modification not taking

Here i'm Using Sql Server And i create two tables Like
Cutst
CREATE TABLE [dbo].[AuditTab](
[LastUpdate] [datetime] NULL
) ON [PRIMARY]
GO
Id CustName
1 John
AuditTab
CREATE TABLE [dbo].[TblCust](
[Id] [int] NULL,
[Name] [varchar](50) NULL
) ON [PRIMARY]
GO
LastUpdate (Datetime)--
//Here its takes date
I wrote simple trigger function in Cust
ALTER TRIGGER [dbo].[lmnTrigger]
ON [dbo].[TblCust]
AFTER INSERT,DELETE,UPDATE
AS
BEGIN
Insert into [dbo].[AuditTab]([LastUpdate]) values(GETDATE())
END
When I update cust column John-To Joe it is throwing an error
Lack of primary key on the table can cause an issue, try to add PK to the table and test it again.
ALTER TABLE TblCust
ADD CONSTRAINT pk_TblCust PRIMARY KEY (Id)
Other possibility is that data has been truncated, but seems like your columns size is correct.
Is any chance you can provide full error message?

Reset auto increment

My question starts here: How to setup auto increment for Service-Based Database
So if I have to go this way to reset auto increment after deleting a table row:
http://befused.com/mysql/reset-auto-increment
first time I have deal with T-SQL extension and SQL generally. What is wrong here, not sure if I got it right:
CREATE TABLE [dbo].[Tab1] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Phrase] TEXT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
SELECT MAX( Id ) FROM [Tab1] ;
ALTER TABLE Tab1 AUTO_INCREMENT = number;
got this errors:
Severity Code Description Project File Line Suppression State Error
SQL80001: Incorrect syntax near ''. Expecting '.', ID, or QUOTED_ID.
dbo.User 8
and:
SeverityCode Description Project File Line Suppression State Error
SQL80001: Incorrect syntax near ''. dbo.User 7
MYSQL
CREATE TABLE Tab1 (
Id INT NOT NULL AUTO_INCREMENT,
Phrase TEXT NOT NULL,
PRIMARY KEY CLUSTERED (Id ASC)
);
ALTER TABLE Tab1 MODIFY COLUMN Id INT AUTO_INCREMENT // To set column as auto increment
MSSQL (In case someone needs it)
The create table syntax is OK but in creating auto increment column, you can add it like this
CREATE TABLE [dbo].[User] (
[Id] INT NOT NULL AUTO_INCREMENT PRIMARY KEY, // Set column as primary key and auto increment
[Phrase] TEXT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
SELECT MAX( Id ) FROM [User]; // You forgot the brackets in this part,Useris a reserved word in TSQL
If you want to reseed to different number you can use below:
dbcc checkident(tab1, reseed, 100)

SQL Server Create Table With Column Unique Not Null and Not Empty(Check)

How to create a table with a column which is unique, not null and not empty(Check)?
I tried below Query
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName nvarchar(255) NOT NULL,
FirstName nvarchar(255),
Address nvarchar(255),
City nvarchar(255),
CHECK (P_Id>0)
)
When i try to create a table with both UNIQUE and CHECK constraint its throwing following error. Is it possible to use two constraint in a single query?
Major Error 0x80040E14, Minor Error 25501
> CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName nvarchar(255) NOT NULL,
FirstName nvarchar(255),
Address nvarchar(255),
City nvarchar(255),
CHECK (P_Id>0)
)
There was an error parsing the query. [ Token line number = 8,Token line offset = 1,Token in error = CHECK ]. I am using SQL Server 2008.
CREATE TABLE tab
(
id INT,
notnullandnotemptystr VARCHAR(10) NOT NULL UNIQUE CHECK (DATALENGTH(notnullandnotemptystr) > 0)
)
It should be some thing like this.
CREATE TABLE [dbo].[TABLE1](
[COL1] [nvarchar](50) NOT NULL UNIQUE
)
ALTER TABLE [dbo].[TABLE1] WITH CHECK
ADD CONSTRAINT [CK_TABLE1] CHECK (([COL1]<>N''))
for this problem you can use Constraint in sql server
ALTER TABLE TBL WITH CHECK ADD CONSTRAINT [CK_TBL] CHECK
(([dbo].[TBLCheckCustomeUnique](ID)=(1)))
TBLCheckCustomeUnique is a user define function that check this conditions
You can controll the uniqueness of a column or column set by the UNIQUE constraint.
The data stored in the column or column set could be checked/controlled (and forced with various rules) by the CHECK constraint.
The CHECK constraint to achieve your goal is the following:
ALTER TABLE [YourTable]
ADD CONSTRAINT CK_CheckConstraintName
CHECK (LEN([YourColumn]) >= {MinimumColumnWidth})
You can add the constraints in the CREATE TABLE statement or if the table already exists you can add it with the ALTER TABLE .. ADD CONSTRAINT statement.