I have to create a table (H2 embedded database) using fields from other tables. I decided to use CREATE TABLE AS statement.
My code:
CREATE TABLE DOC AS
SELECT I.ID, I.STATUS, A.REMINDERINFORMATION
FROM IE802 I JOIN IE802_ATTRIBUTES A ON A.IE802_ID=I.ID;
Each row which is generated from the code above additionally must have DOCID PrimaryKey. How can I add this column and make it autoincrement and PK at the same time?
Thanks for any tips and other solutions!
Alternatively, how can I make existing I.ID to be PK?
I'm still getting an error: Column "ID" must not be nullable; SQL statement:
ALTER TABLE DOC ADD PRIMARY KEY (ID) [90023-147]
H2 supports column definitions in CREATE AS SELECT:
CREATE TABLE DOC(
ID INT PRIMARY KEY,
STATUS INT,
REMINDERINFORMATION VARCHAR(255)
)
AS SELECT I.ID, I.STATUS, A.REMINDERINFORMATION
FROM IE802 I JOIN IE802_ATTRIBUTES A ON A.IE802_ID=I.ID;
Related
I have two tables that I would like to let them share the same sequence to populate the primary key ID column. However, I also don't want the user to specify or change the value for the ID column.
By using the code below, I can let two tables share the same sequence.
CREATE TABLE T1
(
ID INTEGER DEFAULT SEQ_1.nextval NOT NULL
);
This code will use its own sequence and prevent users from changing or specifying with INSERT:
CREATE TABLE T1
(
ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL
);
Is there a way that can both world? Something like this:
CREATE TABLE T1
(
ID INTEGER GENERATED ALWAYS AS ( SEQ_1.nextval ) NOT NULL
);
Regarding the use case, as #Sujitmohanty30 asked, the reason that I raised this question:
I'm thinking to implement inheritance in the database, consider this UML diagram (I can't directly post images due to insufficient reputation, and sorry for being lack of imagination).
ANIMAL is abstract and all inheritance is mandatory. This means no instance of ANIMAL should be created. Furthermore, there is an one-to-many relationship between ANIMAL and ZOO_KEEPER.
Therefore, I came up with this idea:
CREATE SEQUENCE ANIMAL_ID_SEQ;
CREATE TABLE HORSE
(
ID INT DEFAULT ANIMAL_ID_SEQ.nextval NOT NULL PRIMARY KEY,
HEIGHT DECIMAL(3, 2) NOT NULL
);
CREATE TABLE DOLPHIN
(
ID INT DEFAULT ANIMAL_ID_SEQ.nextval NOT NULL PRIMARY KEY,
LENGTH DECIMAL(3, 2) NOT NULL
);
CREATE MATERIALIZED VIEW LOG ON HORSE WITH ROWID;
CREATE MATERIALIZED VIEW LOG ON DOLPHIN WITH ROWID;
CREATE MATERIALIZED VIEW ANIMAL
REFRESH FAST ON COMMIT
AS
SELECT 'horse' AS TYPE, ROWID AS RID, ID -- TYPE column is used as a UNION ALL marker
FROM HORSE
UNION ALL
SELECT 'dolphin' AS TYPE, ROWID AS RID, ID
FROM DOLPHIN;
ALTER TABLE ANIMAL
ADD CONSTRAINT ANIMAL_PK PRIMARY KEY (ID);
CREATE TABLE ZOO_KEEPER
(
NAME VARCHAR(50) NOT NULL PRIMARY KEY,
ANIMAL_ID INT NOT NULL REFERENCES ANIMAL (ID)
);
In this case, the use of the shared sequence is to avoid collision in ANIMAL mview. It uses DEFAULT to get the next ID of the shared sequence. However, using DEFAULT doesn't prevent users from manually INSERTing the ID field or UPDATE the value of it.
You can create a master view/table and generate the sequence in it.
Then copy it as column values into both tables while inserting.
Another option could be inserting into both tables at same time.Use SEQ.NEXTVAL to insert into first table to get a new ID, and then SEQ.CURRVAL to copy same id in the table.
No, you cant have anything like this because ID is independently generated for each of the tables and this can be done only using sequence when you are inserting the data in both the tables at the same time.
You should normalize your data schema: add column animal_type into the table and create composite primary key on both columns
I am pretty inexperienced when it comes to SQL, so I apologize if this is a rookie question.
I need to add columns to a table in a database, based on a join from another database, using a common column between the two tables.
When you say "add columns to a table in a database," do you mean that you have a table, e.g.
create table Targets (
TargetID int identity(1,1) not null ,
constraint pkc_Target primary key clustered ( TargetID ) ,
TargetField1 varchar(64) not null ,
..... )
And you want to add additional columns to that table? If so, you'd do something like
alter table dbo.Targets add TargetNewField1 varchar(64) null
After that, you'd have empty columns in your table, and could then run an update to fill in the blanks, something like:
update dbo.Targets
set dbo.Targets.TargetNewField1 = dbo.Source.SourceField1
from dbo.Targets
inner join dbo.Source
on dbo.Targets.SomeUniqueField = dbo.Source.SomeUniqueField
I want to create a table using query result. But I want to also add a auto increment primary key field to it. Is it possible to achieve it using SQLite?
Example:
Select two fields from table_a. But I want the output schema as (id, field_a, field_b).
create table foo as
select field_a, field_b
from tablel_a
Currently using SQLite 3, but solutions using other database systems are also fine.
This is not possible with a single statement; CREATE TABLE ... AS ... does not create constraints.
You have to use two statements:
CREATE TABLE foo ( ID INTEGER PRIMARY KEY, [...] );
INSERT INTO foo (...) SELECT ...;
by default sqlite adds a rowid column in every table you create , so unless there's some specific need here, you can use this rowid column
check this out https://www.sqlite.org/lang_createtable.html#rowid
I have a strange issue in MS SQL Server 2012. I'm trying to check if a foreign key already exist in an upgrade script. I've used the system OBJECT_ID() function in the past to find tables, views and procedures, but when I try to use it to find a foreign key it does not work.
-- This query always returns null
SELECT OBJECT_ID(N'FK_Name', N'F')
-- This query works, returning the object ID for the foreign key
SELECT object_id FROM sys.foreign_keys WHERE name=N'FK_Name'
This SO answer suggests that my OBJECT_ID() query should work.
Well it could be that your foreign key is looking to the table not in default schema (probably dbo). In this case you'll not see object_id until you specify schema, like this:
SELECT OBJECT_ID(N'<schema>.FK_Name', N'F')
Actually, you could have multiple objects with the same name in your database, but within different schemas. OBJECT_ID(N'FK_Name', N'F') will return id of object in the default schema.
You can test it like this:
create schema test
create table test.temp1 (id int primary key)
create table test.temp2 (id int)
go
alter table test.temp2 add constraint FK_temp foreign key(id) references test.temp1(id)
select object_id('FK_temp', 'F') -- returns null
select object_id('test.FK_temp', 'F') -- returns object id
drop table test.temp2
drop table test.temp1
drop schema test
sql fiddle demo
How to change the type of a column in a SQLite table?
I've got:
CREATE TABLE table(
id INTEGER,
salt TEXT NOT NULL UNIQUE,
step INT,
insert_date TIMESTAMP
);
I'd like to change salt's type to just TEXT and id's type to INTEGER PRIMARY KEY.
Below is an excerpt from the SQLite manual discussing the ALTER TABLE command (see URL: SQLite Alter Table):
SQLite supports a limited subset of
ALTER TABLE. The ALTER TABLE command
in SQLite allows the user to rename a
table or to add a new column to an
existing table. It is not possible to
rename a colum, remove a column, or
add or remove constraints from a
table.
As the manual states, it is not possible to modify a column's type or constraints, such as converting NULL to NOT NULL. However, there is a work around by
copying the old table to a temporary table,
creating a new table defined as desired, and
copying the data from the temporary table to the new table.
To give credit where credit is due, I learned this from the discussion on Issue #1 of hakanw's django-email-usernames project on bitbucket.org.
CREATE TABLE test_table(
id INTEGER,
salt TEXT NOT NULL UNIQUE,
step INT,
insert_date TIMESTAMP
);
ALTER TABLE test_table RENAME TO test_table_temp;
CREATE TABLE test_table(
id INTEGER PRIMARY KEY,
salt TEXT,
step INT,
insert_date TIMESTAMP
);
INSERT INTO test_table SELECT * FROM test_table_temp;
DROP TABLE test_table_temp;
Notes
I used the table name test_table since SQLite will generate an error if you try to name a table as table.
The INSERT INTO command will fail if your data does not conform to the new table constraints. For instance, if the original test_table contains two id fields with the same integer, you will receive an "SQL error: PRIMARY KEY must be unique" when you execute the "INSERT INTO test_table SELECT * FROM test_table_temp;" command.
For all testing, I used SQLite version 3.4.0 as included as part of Python 2.6.2 running on my 13" Unibody MacBook with Mac OS X 10.5.7.
Since RDBMS is not specified, these are DB2 queries:
Make ID as primary key:
ALTER TABLE table
ADD CONSTRAINT pk_id
PRIMARY KEY (id)
Make salt as not UNIQUE:
ALTER TABLE table
DROP UNIQUE <salt-unique-constraint-name>
Make salt nullable:
ALTER TABLE table
ALTER COLUMN salt DROP NOT NULL
You will need to do a reorg after drop not null. This is to be done from the command prompt.
reorg table <tableName>
In this case you can make salt to nullable and remove unique constraint. Also If id column does not contain any null or duplicate values you can safely make it primary key using sql server management studio. below is the screen shot. hope it makes it clearer:
alt text http://img265.imageshack.us/img265/7418/91573473.png
or use following sql:
alter table <TableName> modify salt text null
alter table <TableName> drop constraint <Unique Constraint Name>
alter table <TableName> modify id int not null
alter table <TableName> add constraint pk<Table>d primary key (id)