Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new table and adding a primary key using SELECT INTO

I have a database table that is created using the SELECT INTO SQL syntax. The database is in Access and consists of roughly 500,000 rows. The problem is when I do the join, the unique is the entire row - what I would like is an auto number ID field as the Primary Key.

Code I currently have is something like:

SELECT INTO new_table
FROM 
(SELECT * FROM table a, table b WHERE a.name = b.name)

I was hoping there was a way to add a clause into my SELECT INTO query so I could add a primary key and create the table in one pass - is this possible?

If not, what is the best way to do this using SQL only?

like image 839
user559142 Avatar asked Mar 19 '13 19:03

user559142


People also ask

Does SELECT into create a new table?

SELECT INTO copies data from one table into a new table. SELECT INTO creates a new table located in the default filegroup.

How do I create a new table from a SELECT query in SQL?

If you would like to create a new table, the first step is to use the CREATE TABLE clause and the name of the new table (in our example: gamer ). Then, use the AS keyword and provide a SELECT statement that selects data for the new table.

What is SELECT into in SQL?

The SELECT INTO command copies data from one table and inserts it into a new table. The following SQL statement creates a backup copy of Customers: SELECT * INTO CustomersBackup2017.


2 Answers

Adding a Primary Key during a INSERT INTO statement is not possible as far as I'm aware. What you can do however, is add an IDENTITY column that auto increments by using SQL Server's IDENTITY() function.

Something like this:

SELECT 
    ID = IDENTITY(INT, 1, 1),
    col1,
    col2
INTO new_table 
FROM (SELECT * FROM table a, table b WHERE a.name = b.name)
like image 80
JodyT Avatar answered Oct 24 '22 18:10

JodyT


In Access I don't believe that you can accomplish what you want in a single statement. What I think you'll need to do is...

  1. Create the new table as you described in the question.

  2. Add the AutoNumber column like this:

    ALTER TABLE [new_table] ADD COLUMN [ID] AUTOINCREMENT NOT NULL

  3. Make the column you just added the Primary Key:

    ALTER TABLE [new_table] ADD CONSTRAINT NewTable_PK PRIMARY KEY (ID)

like image 43
Gord Thompson Avatar answered Oct 24 '22 18:10

Gord Thompson