Foreign keys to same table / Who columns in User table???

Hi All,
We are designing a database for our client and we are using common columns in all tables like CreatedBy and UpdatedBy which are foreign keys to USER table. My question is can we use these two columns in USER table and have the foreign key constraints to the same tables?
USER table script will look like following..
CREATE TABLE XX_USER
     User_ID                              VARCHAR2(10)
,     CreatedBy                         NUMBER(10)
,     UpdatedBy                         NUMBER(10)
,     User_Name                         VARCHAR2(100)     NOT NULL
,     Designation                         VARCHAR2(100)     NOT NULL
,     CONSTRAINT USER_ISACTIVE_CHECK CHECK (Is_Active in ('Y', 'N'))
,     CONSTRAINT USER_KEY PRIMARY KEY (User_ID),
,     CONSTRAINT USER_CREATED_BY FOREIGN KEY (CREATED_BY)
     REFERENCES XX_USER (USER_ID)
,     CONSTRAINT USER_UPDATED_BY FOREIGN KEY (UPDATED_BY)
     REFERENCES XX_USER (USER_ID)
);I think what I am doing (the above script) is not correct. Could someone please suggest me how can solve this issue?
Thanks in advance,
Oraebs

user8644385 wrote:
We are designing a database for our client and we are using common columns in all tables like CreatedBy and UpdatedBy which are foreign keys to USER table. My question is can we use these two columns in USER table and have the foreign key constraints to the same tables?You can. After fixing synatx errors:
SQL> CREATE TABLE XX_USER
  2  (
  3   User_ID        VARCHAR2(10)
  4  , CreatedBy     NUMBER(10)
  5  , UpdatedBy     NUMBER(10)
  6  , User_Name     VARCHAR2(100) NOT NULL
  7  , Designation   VARCHAR2(100) NOT NULL
  8  , Is_Active     VARCHAR2(1)
  9  , CONSTRAINT USER_ISACTIVE_CHECK CHECK (Is_Active in ('Y', 'N'))
10  , CONSTRAINT USER_KEY PRIMARY KEY (User_ID)
11  , CONSTRAINT USER_CREATED_BY FOREIGN KEY (CreatedBy)
12       REFERENCES XX_USER(USER_ID)
13  , CONSTRAINT USER_UPDATED_BY FOREIGN KEY (UpdatedBy)
14       REFERENCES XX_USER(USER_ID)
15  )
16  /
Table created.
SQL> Now USER_ID is a string while CreatedBy/UpdatedBy is a number. Even though it is allowed, it limits USER_ID to numeric strings and causes implicit conversions while validating. So I would change CreatedBy/UpdatedBy data type to VARCHAR2(10).
SY.

Similar Messages

  • Foreign Keys referencing same Table

    Post Author: Teddy
    CA Forum: Data Connectivity and SQL
    Hello!
    One table i'm using to build my report has two foreign key fields ('start_id', 'target_id') referencing the same table 'city' (city_id, cityname).
    When i try to generate the report both field contain the cityname the start_id is pointing to. Is there a way to also retrieve the correct cityname for target_id?
    I'm not sure if this is a CR  or a DB design problem? The DB is not my work...

    Post Author: Teddy
    CA Forum: Data Connectivity and SQL
    Hello!
    One table i'm using to build my report has two foreign key fields ('start_id', 'target_id') referencing the same table 'city' (city_id, cityname).
    When i try to generate the report both field contain the cityname the start_id is pointing to. Is there a way to also retrieve the correct cityname for target_id?
    I'm not sure if this is a CR  or a DB design problem? The DB is not my work...

  • Primary key and Foreign key on same column

    Hi, I am able to create below tables , primary and foreign keys as below.
    But Is this valid design? Can I define a column (ckey2 in table "child") as
    primary key and as well as foreign key?
    CREATE TABLE parent (
    col1 NUMBER,
    col2 NUMBER
    CREATE TABLE child (
    ckey1 NUMBER,
    ckey2 NUMBER,
    ckey3 NUMBER
    alter table parent add constraint parent_pk primary key( col1 );
    alter table child add constraint child_pk primary key( ckey2 );
    alter table child add constraint child_fk foreign key( ckey2 ) references parent( col1);
    Thanks.

    Can I define a column (ckey2 in table "child") as primary key and as well as foreign key?You mean you want to define a one-to-one relationship between parent and child tables.. why would you want to do that ? You might as well merge the 2 tables into one.

  • Foreign keys at the table partition level

    Anyone know how to create and / or disable a foreign key at the table partition level? I am using Oracle 11.1.0.7.0. Any help is greatly appreciated.

    Hmmm. I was under the impression that Oracle usually ignores indices on columns with mostly unique and semi-unique values and prefers to do full-table scans instead on the (questionable) theory that it takes almost as much time to find one or more semi-unique entries in an index with a billion unique values as it does to just scan through three billion fields. Though I tend to classify that design choice in the same category as Microsoft's design decision to start swapping ram out to virtual memory on a PC with a gig of ram and 400 megs of unused physical ram on the twisted theory that it's better to make the user wait while it needlessly thrashes the swapfile NOW than to risk being unable to do it later (apparently, a decision that has its roots in the 4-meg win3.1 era and somehow survived all the way to XP).

  • Update primary key that’s also a foreign key in another table

    Hi Developers,
    I need to update the primary key for a record but it's also the foreign key in another table.
    Example,
    Table 1 Details
    Name : Parent_Table
    Columns : ID, Name, Age
    Primary Key : ID
    Table 2 Details
    Name : Child_Table
    Columns : ID, Parent_ID, Name, Age
    Primary Key : ID
    Foreign Key : Parent_ID (Primary Key in Parent_Table)
    Parent_Table
    ID Name Age
    1001 Sam 26
    1002 George 25
    Child_Table
    ID Parent_ID Name Age
    1010 1001 Sam 26
    1020 1002 George 25
    Now I want to update ID (1001) in Parent_table as 2001 and also, I want to update Parent_ID (1001) in Child_Table as 2001.
    How we will write the java code to update these columns.
    Thanks in advance.

    dcminter wrote:
    If you're looking at changing the primary keys in your data then there's probably something wrong with your data structure.Depends how you feel about business primary keys versus surrogates. Personally I prefer the latter so I'm with you in theory. In practice, however, a DB that uses a business PK may well find that it's a legitimate use case to change the key value (but then that's why I like surrogates in the first place!)Primary keys should not have meaning.

  • Foreign Key To More Than One Column

    Hi Guys,
    I have a requirement like below
    I have 3 tables (Prospect,customer,user) and I have a contact_dtls table .
    In prospect table Prospect_id is the primary like this customer_id in customer table and user_id in the user table
    in the contact_dtls table I have a column contact_id and other cols.The contact_id can be from prospect_id,customer_id and user_id in other words we can tell the prospect can be a contact or the customer can be a contact and the user also can be a contact also.Now the question is "is it possible to maintain primary key and foreign key relationship with this design that means the prospect_id,customer_id and user_id would be the foreign keys to the contact_dtls table
    I am using oracle11g Version

    Hello,
    as it has been said in the previous reply, you cannot have a foreign key on multiple tables. Maybe you can create a new table contacts containing at least an id column. This table will be parent to prospect, customer and user. Now contact_dtls.customer_id can reference the contacts.id column.
    This will also make sure, that the ids from prospect, customer and user are unique. It even will be possible that a contact is user and customer at the same time.
    Regards
    Marcus
    Edited by: Marwim on 16.11.2012 10:59

  • Delete a user from a table whose name is a foreign key in other tables

    Dear All;
    I am trying to figure out an easy way to do this. I just recently took someone application who utilized 500 tables. I am trying to delete a user from a table called member_table. However, I am having problems doing so because the user name is a foreign key in other tables which has a relationship with this member_table. I really can't naviagte through all 500 different tables and start deleting the user from each table . hence, I would like to figure out a way to delete the user from the member_table without getting the error message
    ORA - 02292 "Integrity Constraint (....) violated child record found

    Unless you want to find and re-create all of the FK's that point to that field so you can make them ON DELETE CASCADE (note it is the FK not the PK that has that attribute), you will need to either delete that member id from each of the child tables individually or update each one individually to either null or some valid value in member_table before you can delete the id from member_table.
    You can find all of the tables, and the corresponding column_name that have an FK relationship to memeber_table with the following:
    SELECT c.table_name, col.column_name
    FROM user_constraints c, user_cons_columns col
    WHERE c.constraint_name = col.constraint_name and
          c.r_constraint_name = (SELECT constraint_name
                                 FROM user_constraints
                                 WHERE table_name = 'MEMBER_TABLE' and
                                       constraint_type = 'P') and
         c.constraint_type = 'R';If there are a lot of these, you could use something similar to generate the set of delete/update statements that would be needed.
    John

  • FOREIGN KEY CONSTRAINT 의 MASTER TABLE NAME 의 확인

    제품 : ORACLE SERVER
    작성날짜 : 1995-11-02
    FOREIGN KEY CONSTRAINT 의 MASTER TABLE NAME 의 확인
    ===================================================
    다음은 FOREIGN KEY CONSTRAINT 이름으로 REFERENCE 하는 TABLE
    (MASTER TABLE)을 찾는 SQL SCRIPT이다.
    col Primary_key_table format a20
    col Constraint_name format a20
    select a.object_name Primary_Key_table,
    c.name Constraint_name
    from dba_objects a,
    sys.cdef$ b,
    sys.con$ c
    where c.name = 'EMP_FOREIGN_KEY' -- CONSTRAINT NAME
    and b.con# = c.con#
    and b.robj# = a.object_id
    /

    The set of constraints as you show it is valid, but will likely result in a lot of violations since both child columns are larger than the parent. The Oracle 2256 error has nothing to do with data validation, nor with the different lengths of the columns. The documentation says
    02256, 00000, "number of referencing columns must match referenced columns"
    // *Cause: The number of columns in the foreign-key referencing list is not
    //         equal to the number of columns in the referenced list.
    // *Action: Make sure that the referencing columns match the referenced
    //          columns.Look at the actual statement that the client ran. It will be different than the one you posted. one of the two column lists will have more columns than the other.

  • FOREIGN KEY CONSTRAINT의 MASTER TABLE을 REFERENCE하는 TABLE 찾기

    제품 : SQL*PLUS
    작성날짜 : 2003-12-17
    FOREIGN KEY CONSTRAINT의 MASTER TABLE을 REFERENCE하는 TABLE 찾기
    ================================================================
    Master table 이 dept2일 때, 이 테이블을 참조하는 table들을 찾는 SQL
    select x.table_name "reference table"
    from
    (select distinct r_constraint_name,table_name
    from all_constraints
    where constraint_type='R' ) x, all_constraints a
    where a.table_name = 'DEPT2'
    and x.r_constraint_name = a.constraint_name;

  • How to fetch column data using foreign key in adf table ?

    I have created a adf table using a view that has a group id and user id column. I want to display the user name ( from user table) and group name from group table. I had created view links to the corresponding tables from the user_group view ( whose iterator is used to render the table).
    It sort of works. I dragged the user name from the embedded user iterator in user_group iterator. It does find the correct user name but if I have more than one row, it displays the user name of the last row user in all rows !
    Is there a solution to this problem ?

    Well, I saw in the view query for the association view ( for Many-Many) that the SQL already had the joins with the two ( master) tables to the association table. So I went ahead and added the descriptive columns to the select clause. Then the selected columns showed up in the attribute list by themselves ( without my intervention). So far so good.
    Then I recreated the adf table attribute by dragging these newly selected attribute to the page. I still see that the value of the attribute is the same in all the rows - this time it is the value for the FIRST row. It doesn't correspond to the foreign key for that particular row.
    IS THIS A BUG ? Has anyone else ever done this ?

  • Determine if database view column is foreign key in underlying table

    Hi,
    I have posted this same question to the General Database Discussions and JDBC forums.
    I am using Oracle database 10g (10.1.0.4.0 - 64 bit production) standard edition on Red Hat Enterprise Linux AS release 3, JDK 1.4.2 and the latest Oracle JDBC (thin) driver.
    We have a java GUI application that is a front-end for our database. Some of the data entry screens display data from database views. If a column in the view is a foreign key in the underlying table, we want to display a combo-box with the valid values so that the user can choose a correct value.
    Is there some way to know whether a column in a view is a foreign key in the view's underlying table?
    Thanks,
    Avi.

    I take that back.. I did figure something out for ya.. After reading some elses post I wrote this code... but its time to go home... I believe this will show you all the constraints and constraint types for the underlying tables of all the views for a user. You can mess with it and get it to return only FK (constraint_type = 'R') and only for a single view if ya like... The all_dependencies data dictionary view is the key to this whole operation...
    select con.table_name, ucc.column_name, con.constraint_name, con.constraint_type
    from all_constraints con, all_cons_columns ucc
    where con.owner = user and
    con.owner = ucc.owner and
    con.table_name = ucc.table_name and
    con.table_name in
    (SELECT referenced_name
    FROM all_dependencies
    WHERE referenced_owner = USER
    AND referenced_type = 'TABLE'
    AND type = 'VIEW');

  • How to create a foreign key for the table from two different tables?

    Hi All,
    I have a three table like below. In the below table SAMPLE_CONS_CHECK and SAMPLE_CONS2_CHECK will be having the primary key for NAME column. The same SAMPLE_CONS3_CHECK table also having the primary key for NAME column and forieign key for SAMPLE_CONS_CHECK and SAMPLE_CONS2_CHECK tables. See the below code 2
    code 1:
    CREATE TABLE SAMPLE_CONS_CHECK
            (NAME VARCHAR2(10),
            SERIES  VARCHAR2(5)
    CREATE TABLE SAMPLE_CONS2_CHECK
            (NAME  VARCHAR2(5),
             MODEL  NUMBER
    CREATE TABLE SAMPLE_CONS3_CHECK
            (NAME  VARCHAR2(5),
             MODEL_NO  NUMBER
            )code 2
    alter table SAMPLE_CONS_CHECK
    add constraint SAMPLE_CONS_CHECK_pk primary key (NAME)
    alter table SAMPLE_CONS2_CHECK
    add constraint SAMPLE_CONS2_CHECK_pk primary key (NAME)
    alter table SAMPLE_CONS3_CHECK
    add constraint SAMPLE_CONS3_CHECK_pk primary key (NAME)
    ALTER TABLE SAMPLE_CONS3_CHECK ADD
    CONSTRAINT SAMPLE_CONS3_CHECK_FK1 FOREIGN KEY
         NAME
    ) REFERENCES SAMPLE_CONS_CHECK
        NAME
    ) ON DELETE CASCADE;
    ALTER TABLE SAMPLE_CONS3_CHECK ADD
    CONSTRAINT SAMPLE_CONS3_CHECK_FK2 FOREIGN KEY
         NAME
    ) REFERENCES SAMPLE_CONS2_CHECK
        NAME
    ) ON DELETE CASCADE;From the above schenario i am able to insert the data to SAMPLE_CONS3_CHECK table. But the parent data is already available in the parent table. The problem is here two different constarints from two different tables. While inserting, it is checking from both the tables whether the parent is exist or not.
    How can i solve this problem? Can anyone halp me about this?
    Thanks
    Edited by: orasuriya on Aug 8, 2009 2:02 AM

    Actually the design is completely incorrect.
    What you say is
    I have
    'foo', 'foo series'
    'foo','foo model'
    'foo',666
    By virtue of table3 referring to both table1 and table2.
    This means you actually need to have 1 (one) table:
    'foo','foo series','foo model', 666
    And the 'problem' disappears.
    Sybrand Bakker
    Senior Oracle DBA

  • Basic doubt about Primary Keys/Foreign Keys in Oracle Tables

    Hi,
    I have a doubt whether Primary Keys/Foreign Keys are allowed in Oracle or not. I have been informed that Oracle does not encourage having Primary Keys/Foreign keys in its database tables. Instead it urges users to have unique constraints on the requisite columns.
    However if I go to the ETRM and look for information about some of the Oracle Tables, I am informed that Primary Keys do exist. At the same time, I am being told that ETRM is not a reliable way of having correct information about table structure (at least the Primary Key information).
    It would be nice if any one of you provides me with some insight in this. Any pointers to a document would be welcome.
    Thanks

    FYI,
    There is seprate forum for Core Sql quieries
    PL/SQL
    Thanks

  • Table with n foreign key vs n tables or n foreign key vs 1 table?

    Hi,
    we have a scenario with n tables containing some attributes one table for one category of attribute (es: color, role, type, etc..) of a principal entity and 1 table for the principal entity with n foreign keys vs every attribute table.
    Some propose to create a unique table called attributes in which put every attribute with an attributetype for each record.
    My question is: the principal entity will have n foreign keys vs the same attribute table. Is this perfomant? which is the best solution?
    Thanks in advance.
    v.

    >
    we have a scenario with n tables containing some attributes one table for one category of attribute (es: color, role, type, etc..) of a principal entity and 1 table for the principal entity with n foreign keys vs every attribute table.
    Some propose to create a unique table called attributes in which put every attribute with an attributetype for each record.
    My question is: the principal entity will have n foreign keys vs the same attribute table. Is this perfomant? which is the best solution?
    >
    Ask those 'Some propose' how a foreign key to the 'same attribute table' will prevent the WRONG value from being used for a column.
    1. Principal entity has a column for 'color' and a column for 'role'.
    2. There are FKs on the 'color' column and the 'role' column that both point to the 'same attribute table'
    3. Legal values for 'color' are: 1, 2, 3
    4. Legal values for 'role' are: 10, 20, 30
    What prevents someone from updating the 'color' column to a value of 20?
    Ask those 'Some propose' how your one attribute table will store attributes that are of different datatypes.
    1. 'color' uses numbers: 1, 2, 3
    2. 'type' uses strings: 'type1', 'type2', 'type3'
    3. 'holiday' uses dates: 12/25/2013, 01/01/2014
    How do your 'Some propse' plan to store ALL of those values in one column? They are likely to say they will use VARCHAR2.
    Ok - so how do you keep someone from updating 'holiday' to a value of 'type2' or a value of '3'?
    You can't easily validate the data to begin with and you can't easily prevent 'dirty' data from getting into the system.
    You also can't easily explain to ANYONE, for example new developers, how to properly use and maintain the table.
    I haven't heard you mention even ONE potential benefit to doing things the way that 'Some propose'. So - DON'T DO THAT!

  • A question about foreign key to multiple tables

    Hello everybody,
    I have a question about creating foreign key and I would appreciate if you could kindly give me a hand. Here are my tables:
    CREATE TABLE TEAM1(team_id VARCHAR2(20), project_id VARCHAR2(20));
    ALTER TABLE TEAM1 ADD CONSTRAINT PK_TEAM1 PRIMARY KEY(team_id);
    CREATE TABLE TEAM2(team_id VARCHAR2(20), project_id VARCHAR2(20));
    ALTER TABLE TEAM2 ADD CONSTRAINT PK_TEAM2 PRIMARY KEY(team_id);although the structure of both the tables is exactly the same, the values (in particular team_id) in both tables are different.
    Also I have another table named AGENT
    CREATE TABLE AGENT(agent_id VARCHAR2(20), team_id VARCHAR2(20));
    ALTER TABLE AGENT ADD CONSTRAINT PK_AGENT PRIMARY KEY(agent_id)Now the problem is that the column team_id in AGENT table is actually a foreign key, but the value can be in either TEAM1 or TEAM2. As far as I know a foreign key points only to one table.
    How can I deal with this problem? Whenever there is an INSERT or UPDATE I have to make sure that the value of the column "team_id" in the table "AGENT" is a valid value either in "TEAM1" or "TEAM2"
    Thanks in advance,
    Kind Regards,
    Dariyoosh

    Do you have the ability to change the data model? If so a more appropriate structure may be something like this:
    CREATE TABLE TEAM(team_id VARCHAR2(20), team_name VARCHAR2(20));
    ALTER TABLE TEAM ADD CONSTRAINT PK_TEAM PRIMARY KEY(team_id);
    ALTER TABLE TEAM ADD CONSTRAINT UK_TEAM UNIQUE (team_name);
    CREATE TABLE TEAM_PROJECT(team_id VARCHAR2(20), project_id VARCHAR2(20));
    ALTER TABLE TEAM ADD CONSTRAINT PK_TEAM_PROJECT PRIMARY KEY(team_id, project_id);
    ALTER TABLE AGENT ADD CONSTRAINT FK_TEAM_PROJECT1 FOREIGN KEY (team_id) REFERENCES TEAM(team_id);
    CREATE TABLE AGENT(agent_id VARCHAR2(20), team_id VARCHAR2(20));
    ALTER TABLE AGENT ADD CONSTRAINT PK_AGENT PRIMARY KEY(agent_id);
    ALTER TABLE AGENT ADD CONSTRAINT FK_TEAM FOREIGN KEY (team_id) REFERENCES TEAM(team_id);Edited by: Centinul on Jun 25, 2010 10:50 AM

Maybe you are looking for

  • Error opening a Microsoft Project 2007 file

    I am receiving an error when trying to open a Project 2007 file.  There is no error code.  The error says "The operation cannot be completed because the source file contains invalid project data or the total number of rows would exceed the limit of 1

  • Change Document - for purchase order

    Hi all, when i make some changes in the purchase order(ME22N) it is stored in the table CDPOS but when i change the delivery address field this alone is not stored. what may be the reason? and how to do it? can anyone help me in this? helpfull answer

  • Subreport Command too big

    I have a subreport for which I have made a Command. The Command does some joins and returns a really big result, if it is run as a stand alone SQL. However, when it is run as a subreport, it does not return that much data (since it is restricted by t

  • Uninstallation of Hyp analyzer 7.x

    Hi, I am trying to uninstall Hyp analyzer but I am getting an error saying can't delete tomcat.exe, few files are unistalled but I can't even delete tomcat.exe manually The uninstall log says as follows (Jun 10, 2009 10:02:42 AM), Uninstall, com.inst

  • Asynchrono​us to synchronou​s data

    I have a vi with several sub vis collecting data from a variety of more or less asynchronous processes. In some cases the instruments are triggered but mostly they are supplying serial ASCII strings of various lengths at about 1 second intervals. Som