I have a database table with several columns where some of them used to form the primary key together. Now the model changed and a single primary key column, called 'id', gets introduced.
When I alter the table and add the column, the column gets populated in every row with an default value, 0 or NULL, so that it can not be used as a candidate for a new primary key. To achieve that, I have to have a different (numerical) value for 'id' in every row. How can I achieve that, preferably as generic as possible (MySQL, Oracle, SQL Server).
Here is a sample of how to add an identity column that populates as a primary key.
create table #t (vals varchar(100))
insert into #t
values('a'),('b'),('c')
alter table #t
add ID int identity primary key
select * from #t
Results:
vals ID
a 1
b 2
c 3
This is a SQL Server answer. I don't know how the other databases work.
CREATE TABLE Persons (
ID int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
Might be this will be helpful.
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.
In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.
Tip: To specify that the "ID" column should start at value 10 and increment by 5, change it to IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "ID" column (a unique value will be added automatically):
Related
I need that the values for a ColumnID, which is a Primary Key, to start at 100 and increment by 5. This condition is asked to be included as a constraint before populating the tables. I already created the tables, I just need to add that constraint. I know I can't use AUTO_INCREMENT because the increase is only by 1. Is there a way to do it in MySQL?
MySQL does not provide any built-in function to create a sequence for a table's rows or columns. But we can generate it via SQL query.
Example:
Let us understand it with the help of the following example. First, we need to create a new table and make sure that there is one column with the AUTO_INCREMENT attribute and that too, as PRIMARY KEY.
Execute the below query to create a table:
CREATE TABLE Insects (
Id INT AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
Type VARCHAR(30) NOT NULL,
Origin VARCHAR(30) NOT NULL
);
Then you can alter your column to start from another value:
ALTER TABLE Insects AUTO_INCREMENT=100;
You can check it here.
I have a table with a unique auto-incremental primary key. Some entries have been deleted from the table, so there are gaps in the ids, it is not a sequence.
I need a query that will make it a sequence. the table is not connected with any other table, so I can temporarily remove the pk and auto-increment from the id column (until the ids will be a sequence).
I use SQL server
If possible, I want to run the query starting from specific id
You cannot update identity column values, nor you can remove the identity from the column, update the values and set it back. You must create a new table with the same schema, copy the data from the old table, but for ID generate a new value, drop the old table and rename the new one to keep the same name.
use [tempdb]
go
if OBJECT_ID('TestTable') is not null
drop table TestTable
go
create table TestTable (
ID int not null primary key clustered identity(1,1)
, Name varchar(50)
)
insert into TestTable(Name) values
('Row #1'),('Row #2'),('Row #3'),
('Row #4'),('Row #5'),('Row #6'),
('Row #7'),('Row #8'),('Row #9')
delete from TestTable where ID in (3, 4, 8) -- Make some gaps
create table TestTable_NEW (
ID int not null primary key clustered identity(1,1)
, Name varchar(50)
)
insert into TestTable_NEW(Name)
select Name
from TestTable
order by ID -- Preserve the rows order
drop table TestTable
exec sp_rename N'TestTable_NEW', N'TestTable'
However, I will not recommend doing this at all. Identity values are supposed to be immutable. They should never change. If you have problems with gaps, then do not allow deletion of existing records. Also, identity do not guarantee that there will be no gaps in the sequence. Only that the values will be unique and increasing. So you should definitely reconsider your database and/or application design, because it is flawed.
I have an existing product table which is already populated with 120 records and I have tried below SQL query:
ALTER TABLE product ADD product_id
INT PRIMARY KEY AUTO_INCREMENT
But it's given me the error:
Error: #1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
Here is work around
create a simple column with autoincrement
browse the table and again make this newly added column as primary key
You are done !
:) Thanks to Guy who is not in Stackoverflow
Friend
If you try to do this in MSSQL then your script will be this.
suppose your table is below
create table product
(
name varchar(20),
product_type varchar(20)
)
and suppose you entered some record in this table after that you want to add a column that name product_id with auto increment and primary key. Then you use this script that is below
alter table product add product_ID int primary key identity(1,1)
suppose this will be help full for you.
There can only be one auto increment field per table. But, you could have a calculated field based on the auto increment field. Or, you could have an int field where you manage the sequence by front end code or by a trigger. And also you could use a sequence in SQL Server.
CREATE SEQUENCE MySequence START WITH 100;
CREATE TABLE MyTable
(
RealIdentity INT IDENTITY(1,1),
RandomCol NVARCHAR(100),
FakeIdentity INT DEFAULT NEXT VALUE FOR MySequence
);
UPDATE - MySQL Way
I just noticed that your question is taged for MySQL. Above answer is for MS SQL. Here's how you'd do the same in MySQL.
How do I create a sequence in MySQL?
MySQL equivalent of Oracle's SEQUENCE.NEXTVAL
Is it possible to create auto-increment based on a specific field? For example i have UserId and Status fields, so for each row with same UserId i need to auto-increment its Status, not global.
There is three thing that come to mind when I read your question. One was an auto incrementing field which acts as your ID number. Updating a table with data that has no unique ID number. Searching for fields with the same Userid to Status
Mt First example is of a creating a table and your AUTO_INCREMENTing number ID:
CREATE TABLE tableNameHere
(
UniqueID int NOT NULL AUTO_INCREMENT,
FirstName varchar(255) NOT NULL,
StatusOrYourColumn int(100) NOT NULL,
PRIMARY KEY (UniqueUD)
)
More on auto incrementation.
You may have already built your table and now want to 'add' additional and or modify your fields using ALTER:
ALTER TABLE tableNameHere StatusOrYourColumn INT AUTO_INCREMENT PRIMARY KEY
But be careful, you don't want to overwrite your settings that you have already set.
Another Thing that came to my mind when reading was where you said Status and Userid where the same. You can find these using the WHERE clause like so:
SELECT * FROM tableName WHERE tableName.Userid = anotherTableOrTableName.Status
Using these queries you can update, remake, alter and query your database table.
I'm trying the following:
CREATE TABLE Table1
(
RecordNo autonumber, --error here!
PersonId varchar(50),
...
)
But, there is an error.
How can I build the correct query in Access?
According to SQL Auto Increment a Field:
CREATE TABLE Persons
(
P_Id PRIMARY KEY AUTOINCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
The MS Access uses the AUTOINCREMENT
keyword to perform an auto-increment
feature.
By default, the starting value for
AUTOINCREMENT is 1, and it will
increment by 1 for each new record.
To specify that the "P_Id" column
should start at value 10 and increment
by 5, change the autoincrement to
AUTOINCREMENT(10,5).
Synonyms for AUTOINCREMENT include COUNTER and IDENTITY. Using IDENTITY the makes a lot of sense because it matched the #IDENTITY variable which returns the last used autonumber value.
The order might be important
CREATE TABLE Persons
( pkObject AUTOINCREMENT PRIMARY KEY)
If I try PRIMARY KEY AUTOINCREMENT as suggested, it gets upset (MSAccess 2010).
Method 1:
Open table in design view
Make a field named "ID" or whatever the field will be that will have the Auto Increment
Put "AutoNumber" under DataType
Method 2:
Make a new table
Close the table and save it
When it asks if you want a primary key click ok
Open the table in Design View
Edit the new field to whatever name you like
When using ancient DAO 3.60 and Jet 4.0 with Access 2003 files, Eugene Yokota'a syntax did not work. I found that COUNTER keyword will do the trick:
CREATE TABLE tablename(id COUNTER, Name Text (30))
Thanks to this post:
http://www.vbforums.com/showthread.php?234335