Force Natural key on a column

I know the definition of a Natural Key but I don't know how to apply it for a column. For a primary key we have a syntax like "CREATE
TABLE Persons
P_Id int NOT NULL PRIMARY KEY)"
Do we have anything similar for Natural Key?? Thanks in advance.
svk

Take a look at the Product table in AdventureWorks2012.
ProductID - INTEGER SURROGATE PRIMARY KEY
Name - UNIQUE KEY (NATURAL KEY)
ProductNumber - UNIQUE KEY (NATURAL KEY)
rowguid - UNIQUE KEY (ALTERNATE KEY)
CREATE TABLE [Production].[Product](
[ProductID] [int] IDENTITY(1,1) PRIMARY KEY,
[Name] [dbo].[Name] NOT NULL UNIQUE, -- NATURAL KEY
[ProductNumber] [nvarchar](25) NOT NULL UNIQUE, -- NATURAL KEY
[MakeFlag] [dbo].[Flag] NOT NULL CONSTRAINT [DF_Product_MakeFlag] DEFAULT ((1)),
[FinishedGoodsFlag] [dbo].[Flag] NOT NULL CONSTRAINT [DF_Product_FinishedGoodsFlag] DEFAULT ((1)),
[Color] [nvarchar](15) NULL,
[SafetyStockLevel] [smallint] NOT NULL,
[ReorderPoint] [smallint] NOT NULL,
[StandardCost] [money] NOT NULL,
[ListPrice] [money] NOT NULL,
[Size] [nvarchar](5) NULL,
[SizeUnitMeasureCode] [nchar](3) NULL,
[WeightUnitMeasureCode] [nchar](3) NULL,
[Weight] [decimal](8, 2) NULL,
[DaysToManufacture] [int] NOT NULL,
[ProductLine] [nchar](2) NULL,
[Class] [nchar](2) NULL,
[Style] [nchar](2) NULL,
[ProductSubcategoryID] [int] NULL,
[ProductModelID] [int] NULL,
[SellStartDate] [datetime] NOT NULL,
[SellEndDate] [datetime] NULL,
[DiscontinuedDate] [datetime] NULL,
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL UNIQUE -- ALTERNATE KEY
CONSTRAINT [DF_Product_rowguid] DEFAULT (newid()),
[ModifiedDate] [datetime] NOT NULL CONSTRAINT [DF_Product_ModifiedDate] DEFAULT (getdate()))
GO
Kalman Toth Database & OLAP Architect
SQL Server 2014 Design & Programming
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

Similar Messages

  • Primary key and WHO columns on EO

    We are trying to create a EO based on a database view. We do not have primary key and standard OA WHO columns but the OA framework is forcing us the have these columns. How do we go about this issue? Any suggestion will be appreciated.

    Oracle Apps mandates that you should have the Audit columns in the Applications tables.
    So you must have the 5 columns defined.
    I have created new tables for my application and need to populate them whenever user creates or modifies any row
    Jdeveloper/BC4J handles direct updates/inserts through default EO implementation, it would insert/update/delete from the base table via the EO, what is your qeustion then ? do you want to know how to perform DMLs in OA or something else ?
    Thanks
    Tapash

  • SCD issue when multiple records in the source dataset have same natural key

    When I load a dataset into a slowly changing dimension, sometimes the dataset contains multiple records for the same natural key. The rows are different by the column last_update_date (among other possible differences).
    The behavior I want is this: if during an ODI job run, the source dataset contains multiple records for one natural key, all records will load into the dimension, but only the record with the greatest last_update_date gets marked as the current record in the dimension. Right now, ODI is marking all of the incoming rows for the natural key as current. Any ideas? Thanks!

    Last_update_date is on the source but is not being sent to the target. Thus, it doesn't have an SCD behavior. I think my solution will be to pre-process the incoming records so I don't attempt to load multiple rows per natural key. I was just hoping someone here knew of an easier solution.
    If it helps, except for the SK, NK, Current Flag, and Effective Date fields, all SCD behaviors are "add row on change".

  • Given that I'll use a natural key, how do I deal with the situation if I find out the value later?

    I have been doing a lot of reading about the pros and cons of using natural versus surrogate keys.  I have read in Joe Celko's books and his writing online that he strongly opposes using surrogate keys and using IDENTITY for generating values for a
    surrogate key column of a table in SQL Server.  I would like some advice on how to handle this situation:  I have a table with physician information and would like to use their NPI as a natural key (it would be a foreign key in many other tables)
    but the people who enter new physicians often don't know the NPI until later.  They also may receive the wrong NPI and need to change it later.
    Right now they use Excel spreadsheets to manage their data and I'm sure you can understand what a nightmare of data integrity that is.  Now that I'm going to design and build a database for them, can you recommend a good approach to this specific problem?
     I cannot tell them to hold on to the new physician's data until they get the NPI because they need to immediately work with the physician's information as soon as the new physician joins the organization.  It's a small shop and not a health system
    but thousands of physicians join.  They cannot insist that the NPI be supplied at the time of registration for various political reasons.  The people who are using the system now have varying degrees of skepticism to outright vehement opposition
    to having a new database system so I cannot "lay down the law" about things that may adversely affect the relationship with the new physicians who sign up.  With the Excel spreadsheets they cope with this by either leaving it blank, entering
    9999999 or some other stray string of characters, or perhaps typing in their shopping list.
    Is there a viable solution to this design problem?  Any and all suggestions appreciated.  Thanks for reading this.

    While I disagree with the standard practice of adding an identity column as the primary key for every table, I think that this is a case where it can be beneficial or practical.  You might not want to cluster on the identity column and you still need
    to enforce the uniqueness of the natural key. 
    OTOH, the alternative is to simply fabricate a value for the natural key when it is unknown.  You could do this manually (where the user must enter the fabricated value) or automatically (where the server generates it).  A manual approach might
    be frustrating to the users since they have to "guess" what would be unique and acceptable, resulting in sort of trial-and-error approach to adding.  You would also very likely need to have a way of identifying which rows had a fabricated value.  Once
    the actual natural key has been identified for a given provider you would then need to update it.  The server can handle cascading the value where needed if you so choose.  Note that, except for the cascading part, you need the same capabilities
    for an identity-based table since this natural key is most likely essential to the system. 
    I'll also point out that you can use a unique constraint as the target of a foreign key - you don't have to use the primary key.  Not recommending this, just mentioning the alternative.  
    Which you should choose I can't say - that requires a much better understanding of your model and that isn't something that can be readily provided in a forum such as this.  I will say that you should not prematurely choose an identity.  Why?  First,
    you make this choice once you have deemed the natural key to be a problem.  Second, it may be (at least) some of your anticipated relationships to physician are actually to something else.  A medical system is as much art as science - at least in
    the USA.  Providers, plans, participants, terms, renewals, diagnosis codes, etc. make one's head spin.  Given that you have just started modeling, there is no reason at this point to make this choice - just be aware that the natural key poses some
    issues that you need to address at some point before completion.  Personally I would choose the natural key for now and let the model develop and demonstrate where this choice becomes a problem. 

  • Replacing natural keys with surrogate keys

    Hi,
    We have database that is runnig with some old applications since many years. In the database, all the primary key are natural keys (composed with many columns). The applications are developped with mod pl/sql and oracle forms6i / designer6i.
    We are planning to develop a new system (replacing all the old applications), the database tables will ramain the same but we are thinking about replacing the natural keys with surrogate keys. Since we are planning to develop and migrate into the new system gradually (oracle forms applications will not be redeveloped first), my question is:
    - will the oracle forms applications still works?
    - what is the risk and precautions to take ?
    - is the decision to convert natural keys into surrogate a good one?
    All your comments and propositions are welcome.
    Thanks.

    Surrogate keys in general is a good idea. Many generators cannot handle multiple column PK's very well, or not at all. I believe, for instance, that Apex can handle 2 columns only.
    But, doing this on an existing datamodel can be a lot of work. You have to change your tables, of course, but also the foreign keys, triggers, constraints etc. A PK is protected from an update, but I guess you also want your old, natural PK, to be protected as well.
    Forms generates master-detail synchronization based on FK relations. If these change, you may have to change your Forms too. As long as you don't do anything in your existing form, my guess is that it will still work. The forms will maintain the FK relation between old table definitions. This works independently of the actual FK relation in the database. You can create triggers on the tables to actually populate the new PK and FK.
    For something like this: give it a try in a small test setup first. Than calculate the risk and impact.

  • Surrogate Keys vs. Natural Keys

    Hi All,
    Is anyone aware of a recommendation regarding the use of surrogate keys vs. natural keys?
    Regards,
    Irfan Abdul Rehman

    The Natural Keys approach was first. This was the approach used when Relational Databases were first discovered. But I believe, it was based on the premise that the design of the Database does not change over time. Most people seem to side with one or the other. People's opinions here are usually based on what they were brought up with or personal experiences where they have run into problems with one approach or the other.
    When viewed within the context of object-oriented design, the Surrogate approach is more common. Consider: does the uniqueness of a table have any relevance to other tables? If the uniqueness of a table changes, why should this have to impact other tables? If a customer is associated with an Order, using Natural Keys, you need to know what columns make the Customer unique when inserting a record into the ORDERS table. With Surrogate Keys, you don't need to know what columns make the Customer unique, the customer is referenced by its Surrogate Key. With Surrogate Keys, you only need to know what makes a Customer unique when dealing with the CUSTOMERS table.
    With SQL Server, the Surrogate approach is very straight forward. In Oracle, the appeal of Surrogate Keys is less than with SQL Server as there is a more work to implement them. In SQL Server – you specify the Column as an identity column. In Oracle you need to additionally add a sequence. In addition, if you want the value automatic on inserts, you will need to create a trigger (unfortunately here, when you insert, there is no way to find out what you just inserted). If you don't choose to have the value automatic on inserts, your insert SQL statements will require extra SQL code and the Surrogate value is not enforced (i.e. someone could enter any value and this could lead to a Key Violation)
    Here are some disadvantages of Natural Keys:
    -     Almost always, more columns to join on. If Table B is a detail table of master A and C is a detail to B and D is a detail to C, you will need at least 3 columns to join D to C in an SQL query.
    -     If your uniqueness of a table changes (Ex: the number of Columns making your Table unique changes from 2 to 3), with Natural Keys, all of your SQL (Stored Procedures, Reports, Views, SQL Scripts, Application Code) will have to be re-written and your foreign keys relating to that table will have to be changed. With Surrogate Keys – usually as simple as modifying that table.
    -     If the data type of a Primary Key column changes (Ex: you used a varchar(20), now it's not big enough and has to be changed to varchar(100)), with Natural Keys, all Foreign Keys related to that Table will have to be changed (may also impact SQL Code). With Surrogate Keys – usually as simple as modifying that table.
    -     The Classic: a value changes in the Primary Key (Like Last Name). Now you've got to update that in every Foreign Key. Which means you'll have a big headache when you have to temporarily drop the constraint(s).

  • Table creation from type - Primary key with 2 columns

    Hello,
    I have to create a table from a type that I created.
    The thing is that I want to create a primary key using two column.
    Because this table is junction table.
    How can I do this ?
    CREATE TABLE CONTENT OF CONTENT_T (ID_COMP primary key, ID_CHAR_J NOT NULL PRIMAR
    Y KEY);
    Oracle return:
    CREATE TABLE CONTENT OF CONTENT_T (ID_COMP primary key,ID_CHAR_J NOT NULL PRIMARY KEY)
    ERROR at line 1:
    ORA-02260: table can have only one primary key
    So I tried:
    CREATE TABLE CONTENT OF CONTENT_T (ID_COMP,ID_CHAR_J NOT NULL PRIMARY KEY)
    ERROR at line 1:
    ORA-02338: missing or invalid column constraint specification
    Tahnk's in advance.
    Edited by: user8266437 on 29 avr. 2009 13:56
    Edited by: user8266437 on 29 avr. 2009 13:56

    SCOTT@orcl_11g> CREATE OR REPLACE TYPE content_t AS OBJECT
      2    (id_comp    NUMBER,
      3       id_char_j  VARCHAR2 (10),
      4       other_cols VARCHAR2 (10));
      5  /
    Type created.
    SCOTT@orcl_11g> CREATE TABLE CONTENT OF CONTENT_T (PRIMARY KEY (ID_COMP, ID_CHAR_J))
      2  /
    Table created.
    SCOTT@orcl_11g> INSERT INTO content VALUES (content_t (1, 'A', 'WHATEVER'))
      2  /
    1 row created.
    SCOTT@orcl_11g> COMMIT
      2  /
    Commit complete.
    SCOTT@orcl_11g> INSERT INTO content VALUES (content_t (1, 'A', 'DUPLICATE'))
      2  /
    INSERT INTO content VALUES (content_t (1, 'A', 'DUPLICATE'))
    ERROR at line 1:
    ORA-00001: unique constraint (SCOTT.SYS_C0062057) violated
    SCOTT@orcl_11g> COMMIT
      2  /
    Commit complete.
    SCOTT@orcl_11g> SELECT * FROM content
      2  /
       ID_COMP ID_CHAR_J  OTHER_COLS
             1 A          WHATEVER
    SCOTT@orcl_11g>

  • Explain me about natural key

    Anybody explain me about natural key and what situations use this type of keys in RPD?
    Thanks in Advance.

    Hi ,
    Check the below link
    http://gerardnico.com/wiki/data_modeling/key
    Thanks,
    Ananth

  • Primary Key With Four Column ,How to use that Column As Primary Key In Form

    Dear All,
    i have create composite Key as primary Key With Four Column .
    How can i use these column in Form With Report Page.
    How can i use these four Column as primary Key to Edit Record .
    How can i do this.
    Thanks
    Vedant

    wrap a view around your table with this bogus primary key. Use an instead of trigger to handle the inserts and updates. And then look at using surrogate keys to resolve these bad design issues...
    5 out of 4 people don't understand fractions.
    Thank you,
    Tony Miller
    Webster, TX

  • No matching unique or primary key for this column-list --error

    CREATE TABLE CUSTOMER(CUS_NUM NUMBER(10) PRIMARY KEY,CUS_NAME VARCHAR2(50),ADDRESS VARCHAR2(50));
    CREATE TABLE ITEM(ITEM_NUM NUMBER(10),ITEM_DESC VARCHAR2(50),TYPE VARCHAR2(50),ITEM_STATUS VARCHAR2(50),
    CONSTRAINT PK_ITEM PRIMARY KEY(ITEM_NUM,TYPE));
    CREATE TABLE ITEM_TYPE(TYPE VARCHAR2(50) PRIMARY KEY,TYPE_NAME VARCHAR2(50),SKU VARCHAR2(50),RATING VARCHAR2(50));
    CREATE TABLE ORDERS(ORDER_NUMBER NUMBER(10),CUS_NUM NUMBER(10),ITEM_NUM NUMBER(10),ORDER_POINT VARCHAR2(50),DISPATCH_POINT VARCHAR2(50),
    PRIORITY VARCHAR2(50),ORDER_STATUS VARCHAR2(50),
    CONSTRAINT PK_ORDERS PRIMARY KEY(ORDER_NUMBER,ITEM_NUM),
    CONSTRAINT FK1_ORDERS FOREIGN KEY (CUS_NUM) REFERENCES CUSTOMER(CUS_NUM),
    CONSTRAINT FK2_ORDERS FOREIGN KEY (ITEM_NUM) REFERENCES ITEM(ITEM_NUM));
    Hi,friends i created tables as above when i creating 'ORDERS' table the error will fir as "ORA-02270: no matching unique or primary key for this column-list".
    can any body solve this issue.
    Cheers,
    Sudhir reddy.

    For your own sanity, you should learn to format your code, or use a tool to do it for you. For the sanity of the forum members, you should preserve that code using the \ tagsCREATE TABLE CUSTOMER
    CUS_NUM NUMBER(10) PRIMARY KEY,
    CUS_NAME VARCHAR2(50),
    ADDRESS VARCHAR2(50)
    CREATE TABLE ITEM
    ITEM_NUM NUMBER(10),
    ITEM_DESC VARCHAR2(50),
    TYPE VARCHAR2(50),
    TYPE is a reserved word.  Call it ITEM_TYPEITEM_STATUS VARCHAR2(50),
    CONSTRAINT PK_ITEM PRIMARY KEY(ITEM_NUM,TYPE)
    CREATE TABLE ITEM_TYPE
    TYPE VARCHAR2(50) PRIMARY KEY,
    again, with the reserved word.TYPE_NAME VARCHAR2(50),
    SKU VARCHAR2(50),
    RATING VARCHAR2(50)
    CREATE TABLE ORDERS
    ORDER_NUMBER NUMBER(10),
    be consistent.  NUM or NUMBER.  Pick one and stick with it.CUS_NUM NUMBER(10),
    ITEM_NUM NUMBER(10),
    ORDER_POINT VARCHAR2(50),
    DISPATCH_POINT VARCHAR2(50),
    PRIORITY VARCHAR2(50),
    ORDER_STATUS VARCHAR2(50),
    CONSTRAINT PK_ORDERS PRIMARY KEY(ORDER_NUMBER,ITEM_NUM),
    CONSTRAINT FK1_ORDERS FOREIGN KEY (CUS_NUM) REFERENCES CUSTOMER(CUS_NUM),
    CONSTRAINT FK2_ORDERS FOREIGN KEY (ITEM_NUM) REFERENCES ITEM(ITEM_NUM)

  • Force width change of readonly column

    Within a drag and drop ADF table, using an outputtext component, the column is shrunk to the width of the contents, likewise if I use an inputtext with the readonly attribute set to true.
    How can I force a readonly column to be a width greater than the contents ?
    Cheers,
    Brent

    Thanks Steven,
    I've posted it on the JDeveloper forum.
    Force width change of readonly column
    Cheers.
    Brent

  • What's force quit keys on older Mac keyboard

    I recently overburdened my system by burning a disk and doing several other high tasking operations at the same time. I was unable to access the Apple menu to force quit. What is the force quit key combination on an older keyboard - I have the Apple pro keyboard.

    thanks - marked as solved

  • How to implement SCD when a natural key gets changed?

    Hi,
    I have an requirement that, some times the natural key field of the dimension table may get changed. In that scenario, how can I implement the SCD type 2 for that dimension table. Pls post your suggestions and feedback.
    Thanks in advance,
    Kishan

    Hello Kishan,
    could you please be a little bit more specific and provide an example? I really can't imagine why a natural key should change. If it changes it's another item that has nothing to do with the item described by the old natural key. What I'm trying to say is if your natural key gets "broken" then it's not your natural key. Try to build one on your own. You can for instance concatenate the old natural key with a sequence number and use that construct as your natural key.
    Regards,
    Jörg

  • SCD - source sets where multiple changes exist for the same natural key

    I am using the Oracle SCD type2 method (end date old record and insert the new record) which was working fine until my source set contained multiple changes for the same natural key. Does anyone know of a way to handle this?
    Thanks

    Hello,
    I think, the way of handling multiply changes of NK is totally depend on business requirements for your project.
    There could be number of approaches for this. For example:
    - all changes but the last are considered active during one day, going subsequently right after previously existed SCD record;
    - all changes but the last are considered “active” depending on its occurrence within “fact” data (as far as you consider NK change based on some attribute set - probably some of attributes show themselves within “fact” data)
    - etc.
    So, make an agreement upon this with your customer – and ETL design decision will follow immediately.
    Sergey

  • MDX Query to show the latest product text again historical facts (Type 2 dimenion linking on Surrogate key and also Natural Key)

    I need to write a MDX query to show the latest product text again historical facts or a chosen product text in time. I can write this query in TSQL, but new to MDX.
    The way I do it in TSQL is joining two queries together on the Natural Key as opposed to the surrogate key.
    Can this be done in MDX. I know I could write two separate MDX queries, one which get the product text I wan and the other to get the measure with the actual product text and Natural Key, and use a lookup function in ssrs to show the two result sets I the
    same tablix by looking up the Natural Keys. But this should be able to be done in one query shouldn't it.
    In the dsv the fact knows to join to the dimension using the surrogate key.
    Thanks J

    Hi Jamster,
    According to your description, you want to write a query to show the latest product text, right?
    In MDX, we can use LastNonEmpty function to return the lastest member winth a dimension. LastNonEmpty is an aggregation function available in the Enterprise version of SQL Server. However, you can create your own with a little bit of recursive MDX. Here
    is a sample query for you reference.
    With Member Measures.LastHits as
    iif(isempty(Measures.Hits),
    ([Date].[Year Month Day].prevmember,
    Measures.LastHits
    ),Measures.Hits)
    Reference
    http://cwebbbi.wordpress.com/2011/03/24/last-ever-non-empty-a-new-fast-mdx-approach/
    http://richardlees.blogspot.com/2010/07/getting-last-non-empty-value.html
    If this is not what you want, please provide us the detail structure of your cube and the expected result, so that we can make further analysis and give you the exactly MDX query.
    Regards,
    Charlie Liao
    TechNet Community Support

Maybe you are looking for

  • Netflow is not showing on prime infra 1.2 and also reports are not generating

    Hi friends, I add my router to cisco prime for netflow and configured it by temelate as mentioned by cisco in deployment guide. I got netfloe till last friday but today i am getting anyflow on prime. second I am not able to generate raw netflow. how

  • How does sleep command works?

    Does anyone know how sleep command works? If I send "sleep 2m" to terminal.. would cpu be idling during those 2 minutes (from that command itself)? Is there something that is implemented in kernel that tells how sleep command works? and how its imple

  • Can I install 8.5.1 modules on a LABVIEW 8.5 system

    Can I install 8.5.1 modules especially ARM module on a LABVIEW 8.5 system ... Since 8.5.1 is just a minor upgrade to 8.5 I guess it should do .. But does it work effectively while importing code to  ARM processor

  • How can I make may Mac faster?

    Whomever can help please advise. 1. Is there a way to defrag a Mac 2. Will Parallels 4 cause the the Mac to crash? 3. I need to make the Mac run faster, anything you can advise would be great. Thanks, JCR

  • Deploying jar on mobile

    hi, i have successfully created one j2me application using blutooth, Jar file is also successfully created but when i deply it on mobile having bluetooth capabilty it doesn't work properly, can anybody tell me y it happens?? Thanx