What to use for SQL Server instead of "Key"? - sql

I have a script of MySQL queries that I use and that work.
I'm trying to execute the same queries in Microsoft SQL server and there's one thing I don't understand.
MySql uses "key" to define a key made up of different fields.
What is the way to do the same thing in SQL Server?
Thanks!
-Adeena

You can declare a primary key that consists of multiple columns in TSQL (SQL server's query language)
ALTER TABLE product
ADD CONSTRAINT prim_prod PRIMARY KEY(product_foo, product_bar)
If you use SQL Server Management studio, you can also achieve this via "Modify Table".

In MySQL, the keyword KEY is simply a synonym for INDEX. The following two are equivalent:
CREATE TABLE foo (
id SERIAL PRIMARY KEY,
ctime DATETIME,
KEY ctkey (ctime)
);
CREATE TABLE foo (
id SERIAL PRIMARY KEY,
ctime DATETIME,
INDEX ctidx (ctime)
);
In Microsoft SQL Server, the closest equivalent is INDEX. As far as I can tell, to create an index on a column in Microsoft SQL Server, you use CREATE INDEX. You can also create constraints that build indexes as part of a CREATE TABLE statement, but if you just need an index, use CREATE INDEX.
CREATE TABLE foo (
id BIGINT IDENTITY PRIMARY KEY,
ctime DATETIME
);
CREATE INDEX ctidx ON foo(ctime);
See also documentation on CREATE INDEX.

Related

Is it possible to create an identity column in Oracle without it being a primary key, and how does it relate to H2 Database?

I'm trying to transform a table to start using natural keys instead of surrogate keys, so before explaining what I'm trying to do, I'll explain how the database is currently set up.
-- FOO_BAR TABLE
id NUMBER(10) PRIMARY KEY, -- A sequence and a trigger is set up to this column.
uuid CHAR(36) UNIQUE
What I'm trying to do is:
The id column should be deleted;
The uuid column should be the primary key;
A new column called creation_order should be created, and it should have the same values as id, but it'll not be the primary key.
So after the migration the table should look like this:
-- FOO_BAR TABLE
creation_order NUMBER(10) UNIQUE GENERATED AS IDENTITY,
uuid CHAR(36) PRIMARY KEY
The problem that made me create this question is that I'm using H2, and I should try to create the migration scripts the most pure SQL compliant as Oracle allows me, and since GENERATED AS IDENTITY is pure SQL and it's now supported by Oracle DB, I should try to stick with that.
So, my first question is:
In H2, I can't follow this approach, as GENERATED AS IDENTITY will always implicitly create a PRIMARY KEY constraint, as pointed in H2 Database Documentation:
Identity and auto-increment columns are columns with a sequence as the default. The column declared as the identity columns is implicitly the primary key column of this table (unlike auto-increment columns).
So for H2, I need to use AUTO_INCREMENT instead.
I looked for the documentation of Oracle DB and I didn't find any information about primary keys for the identity type, does it mean that Oracle's GENERATED AS IDENTITY work just as H2's AUTO_INCREMENT?
And if the answer is positive and GENERATED AS IDENTITY is different for each database, does anyone have any idea of how to use the same migration script for both databases, or is it impossible?
Thank you!
Yes, it is possible (Oracle 12c):
CREATE TABLE tab (
id INT PRIMARY KEY,
some_identity NUMBER GENERATED ALWAYS AS IDENTITY, -- it is not PK
descr VARCHAR2(30)
);
or with DEFAULT:
CREATE SEQUENCE seq;
CREATE TABLE tab(
id INT PRIMARY KEY
,some_identity NUMBER DEFAULT seq.NEXTVAL
,descr VARCHAR2(30)
);

What is the statement to create a primary key in SQL like "3585c5d240dd4132bab35ab969137f3f"

I'm working with SQL Server Management Studio. I want to create a primary key like "3585c5d240dd4132bab35ab969137f3f" with a statement from SQL but I don't know the statement to create a primary key.
Can someone tell me what the statement is, to create a primary key like this?
First, you need to add a column that will store that GUID.
alter table your_table
add field_name uniqueidentifier not null
Then you need to create your primary key constraint on that field.
alter table your_table
add constraint PK_[your_table] PRIMARY KEY(field_name)
Lastly, when inserting data into your table, the field_name is generated using newid() like so:
insert into your_table(field_name)
values(newid())
This value seems to be a Universally Unique IDentifier, or UUID for short.
In MS SQL Server, you can use the newid() function to generate such an identifier. E.g.:
SELECT NEWID()
One way to go is to use a GUID. In SQL Server, the function NEWID (see the doc here). If you don't like dashes, use REPLACE as well:
SELECT REPLACE(NEWID(), "-", "");
But beware of guids as primary key: The Cost of GUIDs as Primary Keys. It is a bit old, but still interesting.
To make it a primary key, you can:
declare a primary key of type varchar() in your create statement
since functions are not allowed as default values, use a trigger before insert that uses the function stated above to generate your primary key.
I agree with everyone that says that you need to use the NEWID() function to generate what you want. My recommendation is that if that column will also be your clustered index, you should probably use NEWSEQUENTIALID(), to avoid the horrible fragmentation and page splits a random GUID column may cause.
Try this code:
ALTER TABLE Persons ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id, LastName);

Interbase how to add guid field to existing table

I have an old existing interbase table and I want to add a primary key field to and populate it. Is there any way to do it all in the SQL statement (like SQL server). Example:
ALTER TABLE IBUSERS ADD IBUSERSPK VARCHAR(32) default (newid()) NOT NULL
As far as I can tell in interbase newid function does not exist unless I am missing something.
I am using IBExpert and also have IBConsole.
Or am I stuck with populating this field in code after it gets created?
Thanks.
It appears interbase has no easy way to SQL populate a guid field. Therefore the solution is to create your own UDF function in the database to create a random guid. It then becomes a three step process:
Add the field to the table
ALTER TABLE IBUSERS ADD IBUSERSPK VARCHAR(32) NOT NULL
Populate the new field using the UDF:
UPDATE IBUSERS SET IBUSERSPK = GETGUID()
Add primary key constraint if it is such:
ALTER TABLE IBUSERS ADD CONSTRAINT PK_IBUSERS PRIMARY KEY (IBUSERSPK)
The nice thing about this is that then this function can be used anytime/anywhere in the database.

H2 database: Information about primary key in INFORMATION_SCHEMA

I create the following table in H2:
CREATE TABLE TEST
(ID BIGINT NOT NULL PRIMARY KEY)
Then I look into INFORMATION_SCHEMA.TABLES table:
SELECT SQL
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'TEST'
Result:
CREATE CACHED TABLE TEST(
ID BIGINT NOT NULL
)
Then I look into INFORMATION_SCHEMA.CONSTRAINTS table:
SELECT SQL
FROM INFORMATION_SCHEMA.CONSTRAINTS
WHERE TABLE_NAME = 'TEST'
Result:
ALTER TABLE TEST
ADD CONSTRAINT CONSTRAINT_4C
PRIMARY KEY(ID)
INDEX PRIMARY_KEY_4C
These statements are not the ones which I have stated, therefore, the question is:
Is the information in TABLES and CONSTRAINS reflects how real SQL which was executed in database?
In original CREATE TABLE statement
there was no CACHED word. (not a problem)
I have never executed ALTER TABLE .. ADD CONSTRAINT statement.
The actual reason why I am asking the question is that I am not sure which statement should I execute in order to guarantee that primary key is used in a clustered index.
If you look at my previous question H2 database: clustered index support then you may find in the answer of Thomas Mueller the following statement:
If a primary key is created after the table has been created then the primary key is stored in a new index b-tree.
Therefore, if the statements are executed as such they are shown in INFORMATION_SCHEMA, then primary key is created after the table is created and hence ID is not used in a clustered index (basically as a key in a data b-tree).
Is there a way how one can guarantee that primary key is used in a clustered index in H2?
Is the information in TABLES and CONSTRAINS reflects how real SQL which was executed in database?
Yes. Basically, those are the statements that are run when opening the database.
If you look at my previous question
The answer "If a primary key is created after the table has been created..." was incorrect, I fixed it now to "If a primary key is created after data has been inserted...".
Is there a way how one can guarantee that primary key is used as a clustered index in H2?
This is now better described in the H2 documentation at "How Data is Stored Internally": "If a single column primary key of type BIGINT, INT, SMALLINT, TINYINT is specified when creating the table (or just after creating the table, but before inserting any rows), then this column is used as the key of the data b-tree."

Can you create a table with indexes at the same time?

I'd like to create a table:
CREATE TABLE sfc.OpenId (
Url VARCHAR(255) PRIMARY KEY,
UserGuid uniqueidentifier NOT NULL references dbo.aspnet_users(userId),
)
...with an index on UserGuid.
Is it possible to create that index in the create table statement?
You can do that if the index on UserGuid is a unique index, via UNIQUE constraint. Otherwise, no.
Is it possible to create that index in the create table statement?
No, only constraints can be created within the CREATE TABLE syntax.
f not defined otherwise, the primary key will automatically be a CLUSTERED index - but that doesn't cover the userguid column. The CREATE INDEX syntax needs to be a separate statement otherwise.
Can you clarify why?
You can use transactions with DDL in SQL server and for most purposes this is equivalent to doing it at the same time.