Monday, February 10, 2014

List primary keys/foreign keys by table names containing a particular string

Oracle:

SELECT cc.table_name, cc.column_name
FROM all_constraints ac, all_cons_columns cc
WHERE cc.table_name like '%<your string>%'
    AND ac.constraint_type = 'P'
    AND ac.constraint_name = cc.constraint_name
    AND ac.owner = cc.owner;

For foreign keys, change the ac.constraint_type='P' to ac.constraint_type='R'


DB2:

SELECT TBCREATOR, TBNAME, NAME, KEYSEQ
FROM SYSIBM.SYSCOLUMNS
WHERE TBNAME like '%<your string>%'
AND KEYSEQ > 0
ORDER BY KEYSEQ;

For foreign keys

SELECT a.TBNAME, b.COLNAME
FROM SYSIBM.SYSRELS a, SYSIBM.SYSFOREIGNKEYS b
WHERE A.TBNAME like '%<your string>%'
AND a.CREATOR = B.CREATOR
AND a.TBNAME = b.TBNAME;
ORDER BY a.RELNAME, b.COLSEQ;


MySQL:

SELECT Col.Table_Name, Col.Column_Name
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col 
WHERE Col.Constraint_Name = Tab.Constraint_Name
    AND Col.Table_Name = Tab.Table_Name
    AND Tab.Constraint_Type = 'PRIMARY KEY '
    AND Col.Table_Name  like '%<your string>%'
ORDER BY Col.TABLE_NAME, Col.ORDINAL_POSITION;

For foreign keys, change Tab.Constraint_Type = 'PRIMARY KEY ' to Tab.Constraint_Type = 'FOREIGN KEY '


-------------------------------------------------------------------------------------------------------------------

                        

If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

2 comments:

  1. Thanks Joy, you are the best. Please write about the inner join and outer join ? I was reading about this and i did not understand the concept very well. Also please write on join predicate.

    Selena

    ReplyDelete
    Replies
    1. Selena, thanks for your comment. For inner join and outer join, here is the link.

      http://flyingjxswithjava.blogspot.com/2014/02/sql-inner-join-and-outer-join.html

      Delete