Primary key  & foriegn key

can i create more than one primary key in database table..?what is the function of primary key compare to foriegn key

Hi
Primary Key:
it is useful to uniquely identify the rows in a table by one or more columns so that you can process them in a specified sequence, for example. You can do this by assigning a “primary key.” The column names that are to create the table key are represented by the keywords PRIMARY KEY. The input values of the key columns defined in this way must not be a NULL value.
You can use the primary key to insert rows in a table in the same way as you insert rows in a base table when no primary key is defined. However, the system outputs an error message if you attempt to insert an existing value into the primary key column a second time, since the uniqueness of the column is ensured by defining the primary key.
A primary key can consist of multiple columns. However, it is unusual for a key to be constructed from more than five columns, since this makes it difficult for users to enter unique values. The arrangement of the columns behind the keywords PRIMARY KEY defines the key sequence.
Foreign Keys :
You can define the relationships between tables in the ABAP Dictionary by creating foreign keys.
Using foreign keys, you can easily create value checks for input fields. Foreign keys can also be used to link several tables in a  view or a  lock object.
Reward Points if useful

Similar Messages

  • Prcedure to joining of two tables and pls explore the primary & foriegn key

    Dear All,
    Am new to this forum looking forward to have some discussions and guidance reg ABAP.
    <b>My query is</b>
    what is the prcedure to joining of two tables and pls explore the primary & foriegn key relationships.
    Your kind help is required in this query .
    Thanks n regards
    Carol P

    Hi Carol,
    Joining two tables fetch data from tables that has relevent entry based on the keys. like LIKP and LIPS these are delivery tables. if the business requirement is fetching delivery data that are exists in both two tables. here LIKP will conatins a single entry against a condition and LIPS may contains several entry because one delivery may has multiple line items. so, fetch the data joining the two tables on vbeln that is delivrey number. this is used to increase the performance of the program except for all entries.
    Foreign key is poiting twowards primary key; it may be 1:1 , 1:many and many:many. if field1 of table a is pointing towards field1 of table b. then based on these condition at the time of entry SAP will check how many entry can be entred in field1 of table a.
    regards
    Krishnendu

  • Primary & Foriegn Key Relation

    I have to tables TABLE-A, TABLE-B
    CREATE TABLE A(HEADER_ID NUMBER(4) PRIMARY KEY,BROKER_CODE VARCHAR2(10),E_DATE DATE,AGENT VARCHAR2(10))
    CREATE TABLE B(LINE_ID NUMBER(4) PRIMARY KEY,HEADER_ID NUMBER REFERENCES XX_JVG_HEADER(HEADER_ID),INVOICE_NO NUMBER(4),LOT_NO NUMBER(4))
    1) I will insert the data manually raaa.I'm taking HEADER_ID as a Primary Key in Table-A & Foriegn Key in Table-B.
    2) Again i have taken LINE_ID as a Primary Key in Table-B .If i try to insert the data into Table-B the HEADER_ID automatically should enter in Table-B.
    3) But the HEADER_ID should be the same for Table-A & Table-B.
    Table-A
    2,'abc','12-mar-2002','chennai'
    Table-B
    1,2,1,1
    Header_id should be same in 2 tables i.e -- 2
    we have to create triggers or any...pls let me know ASAP.

    So what is the issue with the tables? The script above looks ok to me, assuming table A is really called XX_JVG_HEADER, although you should really define B.HEADER_ID as NUMBER(4).
    If i try to insert the data into Table-B the HEADER_ID automatically should enter
    in Table-BThis is not something you can do in the table creation script or with triggers. You're inserting data manually so only the front-end program (or you if you're using something like sql plus) can know which record in table A is the parent of the new records in table B, so that will decide the value to insert into the header_id column. I suspect that this line, as well as the fact that this is Forms forum, prompted answers concerning master-detail forms. For database issues you should use the sql forum.

  • Join 2 tables which are not related with any primary-foriegn key constraint

    Hello,
    How to join 2 tables which are not related with any primary key foreign key constraint.
    Ex.Consider Table A has 5 columns->A_ID,A_Name,A_Address,A_City,A_Pin(Total 10 rows)
    Table B has 5 columns->B_ID,B_Name,B_Adress,B_City,B_City(Total 30 rows)
    From both the table i want the data,which i need to use in curosr to display finally as "Address Label".
    Both the table are entirely different,but there can be some names of Table A which may come in Table B also,if the name,address and city is also same.That means same person in both the table.
    So finally i want total number of distinct records(distinct data of Table A which is not in B+all the data of table B) to come under Address Label.
    How can i write the select query for this condition?
    Thanks
    Swapna

    Hi, Swapna,
    user11018268 wrote:
    Hello,
    How to join 2 tables which are not related with any primary key foreign key constraint.
    Ex.Consider Table A has 5 columns->A_ID,A_Name,A_Address,A_City,A_Pin(Total 10 rows)
    Table B has 5 columns->B_ID,B_Name,B_Adress,B_City,B_City(Total 30 rows)
    Both the table are entirely different,but there can be some names of Table A which may come in Table B also,if the name,address and city is also same.That means same person in both the table.I think you want a UNION, not a join.
    If you have 10 rows in table_a, and 30 rows in table_b, then
    SELECT       A_ID,          A_Name,     A_Address,     A_City,     A_Pin
    FROM      table_a
    UNION
    SELECT       B_ID,          B_Name,     B_Adress,     B_City,     B_City
    FROM      table_b
    ORDER BY            2,               4          
    ;will produce up to 40 rows; 40 if there are no duplicates. (UNION implies DISTINCT.)
    The corresponding column types should be similar, if not exactly the same.
    There's no problem if A_Name is VARCHAR2 (50) and B_Name is CHAR (30).
    However, there will be a problem if A_ID is a NUMBER and B_ID is a TIMESTAMP.
    You must have the same number of columns in all branches of the UNION.
    If you want an ORDER BY clause, put it at the very end, after the last branch of the UNION.
    You can use positional notation (where 2 means the 2nd column) like I did, or you can use names from the first prong of the UNION (such as A_Name).
    From both the table i want the data,which i need to use in curosr to display finally as "Address Label".
    So finally i want total number of distinct records(distinct data of Table A which is not in B+all the data of table B) to come under Address Label.I'm not sure what your mean about "Address Label".
    Whenever you have a question, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables, and the exact results (formatted) that you want from that data.
    You can concatenate all 5 columns into one VARCHAR2 column, if you want to.
    You'll probably want to use RPAD (or simillar functions) to make the output line up nicely.
    If any of the columns are not strings, use TO_CHAR to make string versions of them.
    For example:
    SELECT  TO_CHAR (A_ID, '9999999')
         || '   '          -- leave a little space between the left-justified a_id and the right-justified a_name
         || RPAD (A_Name, 25)
         || RPAD (A_Address, 50)
         ...Edited by: Frank Kulash on Nov 14, 2009 10:11 AM

  • Primary Key / Foreign Key relationship

    Hi Folks,
    I have a MASTER_TABLE which has master values . This table has two fields, STATUS & STATUS_TEXT,  Key field is STATUS.
    This is a check table for another table INSTANCE_TABLE which also has field STATUS; this is not a key field though.
    The requirement is: If I  attempt to delete a STATUS value from MASTER_TABLE, it should not allow me if there is any record in INSTANCE_TABLE which has the same STATUS value. Is there a way to establish such a relationship between the two tables?
    Thank you for the help!
    Sid

    Hi Friend,
    Only through table Maintaince only it can be acheived , by table relatio it can not be  .
    because as you know the  non primary key cannot be be  check table field  .means
    In Mater table STATUS is primary key so you are  making it as check table field to  Insance table  STATUS Field.
    But  in Instance table is not a primary key so , without primary key you will not be able to  do the foriegn key relation to the master table ,so that  it will not be check table becs of that they check will not happen for your  scenario  . to acheieve this you need to either make your STATUS field in Instance table also as primary key and  do the foerign key relationship with  Master table  .
    Or else  write an event in the table maintainance  .
    Regards,

  • Hi guru's what is forign key , and what is foriegn key table

    hi guru's what is forign key , and what is foriegn key table

    hi...
    Foreign key is nothing but simply we can say,
    A field in one table related to field in another table..see the below example...
    consider, there are two tables like emp_personal and emp_official .
    In emp_personal table , the fields are  empid,empname, dob for example. In this table, empid is the primary key field.
    In emp_official table , the fields are empid,dept,designat ion for example. In this also, empid is the Primary key or may not be a Primary key field.
    now we relate these two tables using the foreign key relationship. Foreign key relationship is used to avoid the redundancy mainly...
    now, emp_personal is the Check table( Bcos it holds the empid field, which has the primary key...)
    emp_official table is the Foreign key table (Bcos it holds the empid field, which may or may not be a Primary key).
    now, we foreign key relationship is given. (click the KEY Like  icon in ABAP Dict - Database Table : Emp Official )
    Tables are ready to enter the records...for example create some 5 records in the emp_personal table .
    Table : emp_personal :   Primary Key - empid
    empid     empname    empdob             Status
       1            AAA          1.1.1990          Record saved successfully
       2            BBB          2.2.1990          Record saved successfully
       3            CCC          3.3.1990          Record saved successfully
       4            DDD          4.4.1990          Record saved successfully
       5            EEE          5.5.1990          Record saved successfully
    records are saved in the table : emp_personal.
    now, we are tryiing to create records in emp_official table.
    Table : emp_official :   Primary Key or not a Primary Key - empid
    empid          dept        designation             Status
       1            Dept1        S.E                 Record saved successfully
       2            Dept2       S.SE               Record saved successfully
    now, if u try to create the record which is not in the table emp_personal , which has the empid = 6. but it'll not allow us to create the record 6, bcos of the foreign key relationship between these two tables....
       6            Dept6       P.M                Record doesn't exist......
    now, the foreign key relationship helps us to avoid the duplicate entry......
    Foreign key relationship is possbile between the tables having atleast one same type of field. Also the Technical characteristics of the fields should be same . this is done in the value table.....
    this is the concept of Foreign key...I think this explantion is enough to describe the Foreign key....

  • Trouble adding foriegn keys

    I am trying to add a foriegn key to a table through the wizard in the sql server diagram tools. I select the foriegn key table which is film_actors_lookup. The film_actors_lookup table has 2 fields: ActorID and FilmID. Both are primary keys for the film_actors_lookup
    table. The Film table has a FilmID primary key. The Actor table has an ActorID as a primry key. When I go to add a foriegn key relationship between the Actors table and the film_actors_lookup table, I get the error that both tables must
    have the same number of fields. Why is this not working?

    Please post the error message.
    Both ActorID and FilmID needs to be PRIMARY KEY in respective tables.
    You can see it with below script:
    USE [TestDatabase]
    GO
    CREATE TABLE [dbo].[film_actors_lookup] ([FilmID] INT, [ActorID] INT)
    GO
    CREATE TABLE [dbo].[actors] ([ActorID] INT PRIMARY KEY)
    GO
    CREATE TABLE [dbo].[films] ([FilmID] INT PRIMARY KEY)
    GO
    /* Add Foreign Key - ActorID */
    ALTER TABLE [dbo].[film_actors_lookup] ADD CONSTRAINT [FK_Actors_Lookup_Actors_ActorID] FOREIGN KEY ([ActorID]) REFERENCES [dbo].[Actors] ([ActorID])
    GO
    /* Add Foreign Key - FilmID */
    ALTER TABLE [dbo].[film_actors_lookup] ADD CONSTRAINT [FK_Actors_Lookup_Films_FilmID] FOREIGN KEY ([FilmID]) REFERENCES [dbo].[Films] ([FilmID])
    GO
    - Vishal
    SqlAndMe.com

  • Lack of Primary and Foreign Keys and Efficiency

    I am reverse engineering a Maximo database. I am shock that it does not have Primary or foreign keys define for 590 out of 620 tables.
    My question is does the lack of Primary and Foreign key relationships adversely impact the efficiency of an Oracle database? I think it does IBM techs do not think it does.
    Anyone has the answer?

    does the lack of Primary and Foreign key relationships adversely impact the efficiency of an Oracle database? Not necessarily. There are many large OLTP databases that do not define PKs and FKs.
    It is true that the presence of constraint defintions is used by the optimizer. However,
    what matters is how the application is written and how the optimizer handles it.
    Remember that Oracle Databases have been in production since before constraint definitions were introduced.
    Hemant K Chitale
    Edited by: Hemant K Chitale on Jun 9, 2010 10:05 AM

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

    Hi,
    I have a doubt whether Primary Keys/Foreign Keys are allowed in Oracle. Some of the people I know are telling me that Oracle does not encourage having Primary Keys/Foreign keys in its database tables.
    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. However I am being told that ETRM is not a reliable way of having correct information about table structure.
    It would be great if any one of you provides me with some insight in this. Any pointers to a document would be great.
    Thanks

    It is not that PK/FKs are disallowed in Oracle Apps (there are some on the standard Oracle Apps tables), but they are typically not used. I am not positive what the logic behind this is, but my guess is that it was party due to the earlier versions of Oracle Apps pre-dating declarative database referential integrity in Oracle DB and also on performance issues with the standard referential integrity with the earlier versions of declarative database referential integrity.
    As far as eTRM is concerned - I understood that the data is based on a design repository rather than a physical Oracle Apps DB. So all of the information in there is logically correct, but not necessarily enforced via the standard Oracle DB declarative referential integrity (rather by the application code or APIs).

  • Ms sql - {"The referenced table must have a primary or candidate key. [ FK Name = ForeignKeyB_Details ]"}

    I have a txt file which has all the sqltext in it separated by semi colon .Then I try to run a query one by one like this-
                var conn = new SqlCeConnection(ConnectionString);
                conn.Open();
                var cmdArray = Regex.Split(sqlText, ";");
                var cmd = new SqlCeCommand(null, conn);
                foreach (var text in cmdArray)
                    cmd.CommandText = text;
                    if (!text.Equals(string.Empty))
                        cmd.ExecuteNonQuery();
                    else
                        break;
                conn.Close();
    I get the error {"The referenced table must have a primary or candidate key. [ FK Name = ForeignKeyB_Details  ]"}
    here is part of my txt file-
    CREATE TABLE A
           PrimaryId nvarchar(10) NOT NULL REFERENCES C(PrimaryId),
           UserId nvarchar(20) NOT NULL,
           FirstName nvarchar(30) NOT NULL,
           MiddleInitial nvarchar(1) NULL,
           LastName nvarchar(30) NOT NULL,
           MobileNumber nvarchar(20) NULL,
           PhoneNumber nvarchar(10) NOT NULL,
           PhoneExtension nvarchar(6) NULL,
           FaxNumber nvarchar(20) NULL,
           EmailAddress nvarchar(50) NOT NULL,
      CONSTRAINT PrimaryKeyA PRIMARY KEY(PrimaryId, UserId)
    CREATE TABLE B(
       MarketId int NOT NULL references E(MarketId),
       UserId nvarchar(20) NOT NULL,
       UserFirstName nvarchar(30) NOT NULL,
       UserMiddleInitial nvarchar(1) NOT NULL,
       UserLastName nvarchar(30) NOT NULL,
       PhoneNbr nvarchar(10) NOT NULL,
       Extension nvarchar(6) NOT NULL,
       FaxNbr nvarchar(20) NOT NULL,
       Email nvarchar(50) NOT NULL,
       ShortName nvarchar(10) NOT NULL,
    PublicIdFlag nvarchar(6) NOT NULL references D(publicId),
            CONSTRAINT PrimaryKeyB PRIMARY KEY( MarketId, UserId)
    ALTER TABLE B ADD CONSTRAINT ForeignKeyB_Details FOREIGN KEY(UserId, UserFirstName, UserMiddleInitial, UserLastName, PhoneNbr, Extension, FaxNbr, Email) REFERENCES A(UserId, FirstName, MiddleInitial, LastName, PhoneNumber, PhoneExtension, FaxNumber, EmailAddress);

    Hi,
    Foreign key columns are frequently used in join criteria when the data from related tables is combined in queries by matching the column or columns in the FOREIGN KEY constraint of one table with the primary or unique key column or columns in the other table.
    For more information about the foreign key constraint, please refer to this link:
    http://msdn.microsoft.com/en-us/library/ms175464.aspx
    Here is a similar thread for your reference:
    http://social.msdn.microsoft.com/Forums/sqlserver/en-US/5a71948b-dfb1-46a5-8688-ccab9317e959/error-message-the-referenced-table-must-have-a-primary-or-candidate-key-fk-name-fktblatblb-?forum=sqlce
    Thanks.
    Tracy Cai
    TechNet Community Support

  • 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

  • Can I create constraints "Primary key - Foreign key" on materialized views?

    Hello!
    Can I create constraints "Primary key - Foreign key" on materialized views like on tables?
    My purpose - is to make DB schema "COPY" with set of materialized views or tables, which take data from time to time from other tables situated.into another schema "ORIGINAL".
    Also - I want to use reporting tool, like Crystal Reports, to make nice reports from schema "COPY". To make nice reports, I need primary-foreign relationships between materialized views or tables in schema "COPY".
    Is it possible to use materialized views?
    Or I should use only tables to get such result?
    Thank you in advance.
    Edited by: kogotok1 on Dec 3, 2010 5:01 PM

    What happens when you try it? Or search the manuals.
    http://download.oracle.com/docs/cd/E11882_01/server.112/e17118/statements_6002.htm#i2105365
    http://download.oracle.com/docs/cd/E11882_01/server.112/e10706/repmview.htm#REPLN360

  • PRIMARY KEY-FOREIGN KEY 관계 찾기(MASTER TABLE CONSTRAINT 정보 찾는 SQL)

    제품 : ORACLE SERVER
    작성날짜 : 2003-06-19
    PRIMARY KEY-FOREIGN KEY 관계 찾기
    =================================
    PURPOSE
    이 자료는 MASTER TABLE CONSTRAINT 정보를 찾는 SQL이다.
    Explanation
    SCOTT의 EMP table의 Foreign Key와 부모 제약 조건을 찾으려면
    다음의 질의문을 사용하여 찾을 수 있다.
    SQL> alter table dept add constraint dept_pk primary key (deptno);
    Table altered.
    SQL> alter table emp add constraint emp_dept_fk foreign key(deptno)
    references dept(deptno);
    Table altered.
    SQL> select c.constraint_name as "foreign key",
    p.constraint_name as "referenced key",
    p.constraint_type,
    p.owner,
    p.table_name
    from dba_constraints c, dba_constraints p
    where c.owner = 'SCOTT'
    and c.table_name = 'EMP'
    and c.constraint_type = 'R'
    and c.r_owner = p.owner
    and c.r_constraint_name = p.constraint_name;
    foreign key referenced key C OWNER TABLE_NAME
    EMP_DEPT_FK DEPT_PK P SCOTT DEPT
    Example
    none
    Reference Documents
    <Note:1010844.6>

    I don't have intimate knowledge of SQL Server, but to me, your code seems reasonable. I guess there is some "fine point" (a bug?) to using self referenceing foreign keys in SQL Server. It doesn't seem plausible that the error originates with the driver, unless it's a very intelligent kind of driver.
    A "Gordian Knot" kind of solution to your problem is to ask whether you really need the foreign key constraint in the db schema. Is the table used by something other than your EJB? Anyway, putting logic responsible for the correct functioning of your EJB into the db schema is often a bad practice, as it makes the code harder to understand, maintain, port etc.

  • Lost about 60-75% of my primary and foreign keys when Migrating from SQL Server 7

    Hi All,
    I did an almost successful migration between SQL Server 7.0 and Oracle9i.
    What happened:
    I seem to have lost my primary and foreign keys in the migration. The funny thing is when I viewed the constraints and indexes in Toad, they were there. However when I tried to enabled those constraints nothing happened.
    I really don't know how I can fixed this, but I don't understand why I didn't get a warning or an error message in the Migration Workbench (latest version).
    I did ignore the following errors, could that have anything to do with the keys being lost.
    Failed to create User:omwb_emulation; ORA-1920: user name "OMWB_EMULATION" conflicts with another user or role name
    Failed to create User:guest;ORA-01920: user name "GUEST" conflicts with another user or role name
    These users do not own any objects therefore I ignored them.
    Please advise
    Thanks

    Hi Joe,
    Not sure why you are able to see these objects and yet not able to enable them. Did you encounter any errors during the create Oracle Model phase?? Did you encounter any errors during the final Migrate phase?
    Also, it is really important to have a tablespace created before an attempt is made to create tables and indexes in the destination Oracle database.
    Regards
    John

  • SM30 - Deleting a record with Foriegn Key Constraints

    I have a two custom tables ZCCED_STATUS and ZCCED_COSTITEM. 
    ZCCED_COSTITEM has a status column with a foriegn key to a (PK) status record in ZCCED_STATUS.
    I have generated table maintenance objects for the table ZCCED_STATUS.
    When I go to SM30 and maintain the table ZCCED_STATUS I can select a status record and delete it. (still ZCCED_COSTITEM records using that status)
    Is there any way that SM30 can warn or stop a user from deleting a ZCCED_STATUS record when there are child records in the ZCCED_COSTITEM table?
    Regards,

    Create a maintenance view , link both tables and generate a table maintenance for the maintenance view . it will work.

Maybe you are looking for