Primary Key and Unique Index -- sql scripts generated by SQL Developer - sql

When export sql scripts by SQL Developer there are multiple options available, but either way there have to generate a UNIQUE INDEX on primary key like this
CREATE UNIQUE INDEX "SYS_C0018099" ON "TRANSACTION" ("ID")
and add PRIMARY KEY to the same table and same column
ALTER TABLE "TRANSACTION" ADD PRIMARY KEY ("ID")
So the question is: does it looks like kind of redundancy? I thought creating a primary key on a column should by default create an unique index on that column too? So why the first command is necessary?
And this may cause data redundancy?
I am on Oracle 11g so please share any ideas about why it should look like above.
Thanks in advance.

There is no redundancy - or only a little bit :)
The second command will use the index available if exists. Otherwise(if first DDL does not exists) will create an index.
The split into two commands is useful when you had given a proper name to the index and want to keep it.
UPDATE: The link indicated by Thomas Haratyk is a must read, I really like it: http://viralpatel.net/blogs/understanding-primary-keypk-constraint-in-oracle/
UPDATE2: a_horse_with_no_name is right, it can be done in a single statement like:
alter table TRANSACTION
add CONSTRAINT pk_test PRIMARY KEY (id);
So, it will keep the name(won't create a sysblalbla object name) and if you use the 'USING INDEX' keyword you can specify index atributes, for example storage atributes.
But again, you will not have any problems with those two statements, only an index is created.
Probably SQL Developer prefer to get a ddl per object and there might be cases when it's better its way.

Related

Query to Alter Primary Key to any column with keyword

I have a database with several tables that I am looking to add primary keys to any column with the keyword "KEY" in its name. The first problem that doesn't seem fixable is to run a query against all tables rather than one by one... Secondly I don't see how I can Add Primary key or even drop constraints on wildcard column searches.
For those of you who are visual, this is what I am trying to achieve:
ALTER TABLE *
ADD PRIMARY KEY (%KEY%);
Keeping in mind SOME tables already have Primary Keys attached, so I may need to Drop Constraints on all first then re-constrain them. If even possible?
If you want to define existing autonumber fields as primary key, consider:
ALTER TABLE tablename ADD CONSTRAINT fieldname PRIMARY KEY(fieldname)
However, field cannot already be set with an index and table cannot already have a primary key. Again, use ALTER TABLE to remove index.
ALTER TABLE tablename DROP CONSTRAINT indexname
Will have to run this SQL for each table that must be modified. If this is a one-time only requirement (why would it not be?), probably just as fast to open each table and manually modify design.
MS documentation https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/alter-table-statement-microsoft-access-sql
The alternative is VBA using TableDefs to modify table structure. Search web for examples.

Create autoserial column in informix

is it possible to create a autoserial index in order 1,2,3,4... in Informix and what would be the syntax. I have a query and some of my timestamps are identical so I was unable to query using a timestamp variable. Thanks!
These are the commands that I ran to add an id field to an existing table. While logged in to the dbaccess console.
alter table my_table add id integer before some_field;
create sequence myseq;
update my_table set id = myseq.nextval;
drop sequence myseq;
alter table my_table modify (id serial not null);
Thanks to #ricardo-henriques for pointing me in the right direction. These commands will allow you to run the instructions explained in his answer on your database.
That would be the SERIAL data type.
You can use, as #RET mention the SERIAL data type.
Next you will struggle with the fact that you can't add a SERIAL column to an existing table. Ways to work around:
Add an INTEGER column, populate with sequential numbers and then alter the column to SERIAL.
Unload the data to a file, drop the table and recreate it with the new column.
Create a new table with the new column, populate the new table with the data from the old, drop the old and rename the new.
...
Bear in mind that they may not be unique. Hence you have to create an unique index or a primary key or an unique constraint in the column to prevent duplicates.
Another notes you should be aware:
- Primary key don't allow NULLS, unique index and unique constraints allow (as long there is only one record), so you should specify NOT NULL on the column definition.
- If you use a primary key or a unique constraint you can create a foreign key to it.
- In primary key and unique constraint the validation of the uniqueness of the record is done in the end of the DML, for the unique index it is done row a row.
Seems you're getting your first touch with informix, welcome. Yes it can be a little bit hard on the beginning just remember:
Always search before asking, really search.
When in doubt or reached a dead end then ask away.
Try to trim down your case scenario, built your own case the simple away you can, these will not only help us to help us but you will practice and in some cases find the solution by yourself.
When error is involve always give the error code, in informix it is given at least one error code and sometimes an ISAM error too.
Keen regards.

USING index clause

I saw the following statement in a db patch:
ALTER TABLE tablename ADD PRIMARY KEY (somepk_columnname) USING INDEX;
I wanted to look up what USING INDEX does here, but only got from google, that it lets me specify some storage specific stuff, etc.
My question really is, what exactly happens here? Does the db use some default values here? Creates an index for the PK in the default tablespace? I thought that an index is created for every pk per default...
http://docs.oracle.com/cd/B28359_01/server.111/b28286/clauses002.htm#SQLRF52209
Using Indexes to Enforce Constraints
When defining the state of a unique or primary key constraint, you can
specify an index for Oracle to use to enforce the constraint, or you
can instruct Oracle to create the index used to enforce the
constraint.
using_index_clause You can specify the using_index_clause only when
enabling unique or primary key constraints. You can specify the
clauses of the using_index_clause in any order, but you can specify
each clause only once.
If you specify schema.index, then Oracle attempts to enforce the constraint using the specified index. If Oracle cannot find the index
or cannot use the index to enforce the constraint, then Oracle returns
an error.
If you specify the create_index_statement, then Oracle attempts to create the index and use it to enforce the constraint. If Oracle
cannot create the index or cannot use the index to enforce the
constraint, then Oracle returns an error.
If you neither specify an existing index nor create a new index, then Oracle creates the index. In this case:
The index receives the same name as the constraint.
If table is partitioned, then you can specify a locally or globally partitioned index for the unique or primary key constraint.
The response above was very helpful but I also wanted to use a specific tablespace for my unique key. This worked for me:
alter table tablename add constraint uk_name unique (col1, col2) using index tablespace tablespace_name;

Unique Key or Index with 'Is Unique'

I'm having a rather silly problem. I'll simplify the situation: I have a table in SQL Server 2008 R2 where I have a field 'ID' (int, PK) and a Name (nvarchar(50)) and Description (text) field. The values in the Name - field should be Unique. When searching the table, the Name - field will be used so performance is key here.
I have been looking for 2 hours on the internet to completely understand the differences between Unique Key, Primary Key, Unique Index and so on, but it doesn't help me solve my problem about what key/constraint/index I should use.
I'm altering the tables in SQL Server Management Studio. My question for altering that Name - field is: should I use "Type = Index" with "Is Unique = Yes" or use "Type = Unique Key"?
Thanks in advance!
Kind regards,
Abbas
A unique key and a primary key are both logical constraints. They are both backed up by a unique index. Columns that participate in a primary key are not allowed to be NULL-able.
From the point of view of creating a Foreign Key the unique index is what is important so all three options will work.
Constraint based indexes have additional metadata stored that regular indexes don't (e.g. create_date in sys.objects). Creating a non constraint based unique index can allow greater flexibility in that it allows you to define included columns in the index definition for example (I think there might be a few other things also).
A unique key cannot have the same value as any other row of a column in a table. A primary key is the column field(s) that is a unique key and not null which is used as the main look up mechanism (meaning every table should have a primary key as either a column or combination of columns that represent a unique entry).
I haven't really used indexes much, but I believe it follows the same logic.
See http://en.wikipedia.org/wiki/Unique_key for more information.
An index is a collection the DBMS uses to organize your table data efficiently. Usually you want to create an index on columns and groups of columns that you frequently search on. For example, if you have a column 'name' and you are searching your table where name = '?' and index on that column will create separate storage that orders that table so searching for a record by name is fast. Typically primary keys are automatically indexed.
Of course the above is a bit too general and you should consider profiling queries before and after adding an index to ensure it's being used and speeding things up. There are quiet a few subtleties to indexes that make the application specific. They take extra storage and time to build and maintain so you always want to be judicious about adding them.
Hope this helps.

Do I need to create indexes on foreign keys on Oracle?

I have a table A and a table B. A has a foreign key to B on B's primary key, B_ID.
For some reason (I know there are legitimate reasons) it is not using an index when I join these two tables on the key.
Do I need to separately create an index on A.B_ID or should the existence of a foreign key provide that?
The foreign key constraint alone does not provide the index on Oracle - one must (and should) be created.
Creating a foreign key does not automatically create an index on A.B_ID. So it would generally make sense from a query performance perspective to create a separate index on A.B_ID.
If you ever delete rows in B, you definitely want A.B_ID to be indexed. Otherwise, Oracle will have to do a full table scan on A every time you delete a row from B to make sure that there are no orphaned records (depending on the Oracle version, there may be additional locking implications as well, but those are diminished in more recent Oracle versions).
Just for more info: Oracle doesn't create an index automatically (as it does for unique constraints) because (a) it is not required to enforce the constraint, and (b) in some cases you don't need one.
Most of the time, however, you will want to create an index (in fact, in Oracle Apex there's a report of "unindexed foreign keys").
Whenever the application needs to be able to delete a row in the parent table, or update the PK value (which is rarer), the DML will suffer if no index exists, because it will have to lock the entire child table.
A case where I usually choose not to add an index is where the FK is to a "static data" table that defines the domain of a column (e.g. a table of status codes), where updates and deletes on the parent table are never done directly by the application. However, if adding an index on the column gives benefits to important queries in the application, then the index will still be a good idea.
SQL Server has never put indexes onto foreign key columns automatically - check out Kim Tripp's excellent blog post on the background and history of this urban myth.
It's usually a good idea to index your foreign key columns, however - so yes, I would recommend making sure each FK column is backed up by an index; not necessarily on that one column alone - maybe it can make sense to create an index on two or three columns with the FK column as the first one in there. Depends on your scenario and your data.
For performance reasons an index should be created. Is used in delete operations on primary table (to check that the record you are deleting is not used) and in joins that usually a foreign key is involved. Only few tables (I do not create them in logs) could be that do not need the index but probably, in this cases probably you don't need the foreign key constraint as well.
BUT
There are some databases that already automatically create indexes on foreign Keys.
Jet Engine (Microsoft Access Files)
Firebird
MySQL
FOR SURE
SQL Server
Oracle
DOES NOT
As with anything relating to performance, it depends on many factors and there is no silve bullet e.g. in a very high activilty environment the maintainance of an index may be unacceptable.
Most salient here would seem to be selectivity: if the values in the index would be highly duplicated then it may give better performance to drop the index (if possible) and allow a table scan.
UNIQUE, PRIMARY KEY, and FOREIGN KEY constraints generate indexes that enforce or "back" the constraint (and are sometimes called backing indexes). PRIMARY KEY constraints generate unique indexes. FOREIGN KEY constraints generate non-unique indexes. UNIQUE constraints generate unique indexes if all the columns are non-nullable, and they generate non-unique indexes if one or more columns are nullable. Therefore, if a column or set of columns has a UNIQUE, PRIMARY KEY, or FOREIGN KEY constraint on it, you do not need to create an index on those columns for performance.