How to find table name using primary key name in sql? - sql

I have names of primary keys in a variable and I need to find the table to which they belong. The db has many table so linear search is not an option.

You can use the information_schema tables. If the primary key name is the first column in the table, you can just do:
select table_name
from information_schema.columns
where column_name in (<your list here>) and
ordinal_position = 1;
Otherwise, you have to go through the constraints to get what you want. Something like:
select kcu.table_name, kcu.column_name
from information_schema.table_constraints tc join
information_schema.key_column_usage kcu
on tc.contraint_name = kcu.contraint_name and
tc.table_name = kcu.table_name
where tc.contraint_type = 'PRIMARY KEY' and
column_name in (<your list here>);
You can also do this using the system tables and views.

you can try this out ::
SELECT table_name
FROM information_Schema.columns
WHERE column_name='dept_id'
and ordinal_position = 1;

This should work, please try it:
SELECT table_name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND column_name in (select column_name from <your list here>)
Below solution wouldn't work if the primary key constraint is set to any column other than that of the first column in `CREATE TABLE' query.
select table_name
from information_schema.columns
where column_name in (select column_name from <your list here>) and
ordinal_position = 1
For example, it wouldn't work if we create table like this:
create table sample1
(
field1 int,
field2 int primary key
)
Please correct me if I am wrong.

The below query gives tablename based on constraint name
select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where CONSTRAINT_NAME ='<ConstraintName>'

To find table name using primary key name follow this below query
select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where
CONSTRAINT_NAME =<ConstraintName>
---Find the below views to get constraint details in a db select * from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS select * from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS select * from
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE

improved from above answer
select kcu.table_name, kcu.column_name, *
from information_schema.table_constraints tc join
information_schema.key_column_usage kcu
on tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME and
tc.table_name = kcu.table_name
where tc.CONSTRAINT_NAME = 'PK__DC_INPUT__7EA5540496A9FD5D'

SELECT [TABLE_NAME]
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME = 'YourPrimaryKey';

Related

How to get column key constraints from the table : INFORMATION_SCHEMA in SQL?

How to get column key constraints from the table : INFORMATION_SCHEMA in SQL?
I just need to get the columns which has Primary Key, Foreign Key along with these details.
SELECT COLUMN_NAME AS COLUMNNAME,
DATA_TYPE AS DATATYPE,
CHARACTER_MAXIMUM_LENGTH,
IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'My_Table_Name'
This may help...
USE AdventureWorks2012
GO
SELECT t.CONSTRAINT_NAME,t.TABLE_NAME,t.CONSTRAINT_TYPE,c.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS t
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c ON t.CONSTRAINT_NAME = c.CONSTRAINT_NAME
-- WHERE t.TABLE_NAME = 'ProductVendor'
-- AND t.CONSTRAINT_TYPE = 'PRIMARY KEY'
Try the sys.indexes and sys.index_columns
This has been well answered before :
List of all index & index columns in SQL Server DB

Get Table Columns With Primary Key Constraints

I want to get all the columns (MSSQL SERVER) of a particular Table Along with whether it is _PK or Not. So far I have Tried:
SELECT TABLE_CATALOG AS Database_Name, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = 'TableName'
And its Out Put is:
Database_Name TABLE_SCHEMA TABLE_NAME COLUMN_NAME IS_NULLABLE
------------- ------------ ---------- ----------- -----------
Now I want one More Column to above Table Say 'IS_PRIMARYKEY', means I want the output as:
Database_Name TABLE_SCHEMA TABLE_NAME COLUMN_NAME IS_NULLABLE IS_PRIMARYKEY
------------- ------------ ---------- ----------- ----------- -------------
How ths can be Achieved in One Query/Procedure ?
Thanks
CONSTRAINT DATA IS STORED IN DIFFERENT TABLES HENCE YOU NEED TO APPLY A JOIN TO MATCH TABLE CONSTRAINT AND COLUMN USAGE CONSTRAINT TO GET THE PRIMARY KEY COLUMN.
BUT SINCE YOU NEED THE DETAILS IN A SINGLE QUERY, I HAVE CREATED A ALIAS OF MY QUERY TO GENERATE THE DESIRED OUTPUT. BELOW QUERY WILL GIVE YOU APPROPRIATE ANSWER.
CANNOT CREATE FIDDLE AS THIS IS ONLY HAVING SYSTEM TABLES.
I HAVE DONE THIS FOR MY TEMP TABLE tbl_primaryKey YOU CAN REPLACE THE TABLE NAME AS PER YOUR NEED.
SELECT Database_Name,TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,IS_NULLABLE, CASE WHEN (IS_PRIMARYKEY IS NULL) THEN '' ELSE 'YES' END AS [IS_PRIMARYKEY]
FROM
(SELECT cols.TABLE_CATALOG AS Database_Name, cols.TABLE_SCHEMA, cols.TABLE_NAME, cols.COLUMN_NAME, cols.IS_NULLABLE,
(SELECT 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 Constraint_Type = 'PRIMARY KEY'
AND Col.Table_Name = 'tbl_primaryKey'
AND cols.COLUMN_NAME = Col.COLUMN_NAME
) AS IS_PRIMARYKEY
FROM INFORMATION_SCHEMA.COLUMNS cols
WHERE
cols.TABLE_NAME = 'tbl_primaryKey' ) A
SELECT TABLE_CATALOG AS Database_Name, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, IS_NULLABLE, if(COLUMN_KEY = 'PRI', 'YES', 'NO') AS IS_PRIMARYLEY
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = 'TableName'
You can do this by using If condition, for number's of Columns use *

To get if Primary key Columns is referred as foreign key or not

I need to know how to find a Primary Key in a table, also if that primary key is referenced in any foreign keys in any table.
Try this:
SELECT u.COLUMN_NAME as PK, cc.TABLE_NAME, cc.COLUMN_NAME, cc.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS c
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE u on c.CONSTRAINT_NAME = u.CONSTRAINT_NAME AND c.CONSTRAINT_TYPE = 'PRIMARY KEY'
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS r on u.CONSTRAINT_NAME = r.UNIQUE_CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cc on cc.CONSTRAINT_NAME = r.CONSTRAINT_NAME
where c.TABLE_NAME = 'your table'
Will give you all tables and columns that are referencing the primary key of the table
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='tableName'
This will give you your table structure.
To get the priary keys from a table you can use:
select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'PRIMARY KEY' and TABLE_NAME = 'yourTable'
and to get it's references you can use
select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = 'yourTable'

SQL - How to extract multi field primary key

I know the query to get the table names of database is :
SELECT *
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
How to get the table if its primary key is made up from multiple columns? Or get composite primary key for a specific table?
If I understood well, you can have some options with TSQL.
Procedure:
exec sp_pkeys 'table', 'schema'
View:
This query will return related data with unique constraints e foreign_keys as well
select * from information_schema.key_column_usage
where table_schema = 'schema' and table_name = 'table'
If you want to get just the columns related with primary keys you can try something similar bellow. I think it can change with the database version, I am not sure now.
select *
from information_schema.key_column_usage as k
where table_schema = 'schema' and table_name = 'table'
and constraint_name = (
select name
from sysobjects as u
where k.table_name = object_name(u.parent_obj)
and u.xtype = 'PK')
order by table_schema, table_name, ordinal_position
If it's not the answer give us more details.
Try this:
sp_helpindex 'YourTable'

Table with ForeignKey to table x

I've got an Oracle-DB with ~50 Tables.
Now, i'm looking for all tables with a foreign key to Table 'xyz'.
is there a way to do this?
greetings,
Lea
Foreign keys reference primary (or unique) keys, not tables. So first thing is to establish the primary key(s) for XYZ. Then we can look up the foreign keys which reference it.
select p.constraint_name
, p.constraint_type
, f.owner
, f.table_name
, f.constraint_name
from all_constraints p
left join all_constraints f
on ( f.r_constraint_name = p.constraint_name)
where p.table_name = 'XYZ'
and p.constraint_type in ('P', 'U')
and f.constraint_type = 'R'
I've done this as an OUTER JOIN so it will return something even if no tables reference a key on XYZ. Your table might be referenced by tables in other schemas. That's why I suggest using ALL_CONSTRAINTS rather than USER_CONSTRAINTS.
select fk.table_name from all_constraints fk , all_constraints pk
where
pk.table_name = 'XYZ'
and fk.constraint_type = 'R'
and fk.r_constraint_name = pk.constraint_name
It seems, that you can query User_Constraints view, something like
select distinct Table_Name
from User_Constraints
where Constraint_Type = 'R' and
R_Constraint_Name in (
select Constraint_Name
from User_Constraints
where Constraint_Type = 'P' and
Table_Name = Upper('xyz')) -- <- Your table name
order by Table_Name -- <- may be redundant
for sql try this :
SELECT K.TABLE_NAME ,
K.COLUMN_NAME ,
K.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME
AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
WHERE C.CONSTRAINT_TYPE = 'FOREIGN KEY' /*FOR FOREIGN KEY U NEED TO REPLACE CONSTRAINT_TYPE WITH FOREIGN KEY*/
AND K.COLUMN_NAME IN ( SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS )