How can I list Foreign tables in PostgreSQL? - sql

In PostgreSQL, running \d command will list the tables along with their table type. Currently I'm trying to list out all foreign tables that I've created using foreign data wrapper. What is the query to list out those tables?

Query for listing foreign tables only:
select * from information_schema.foreign_tables

According to the manual \dE[S+] should do it.
http://www.postgresql.org/docs/current/static/app-psql.html
To see the query behind this, start psql with the -e ("echo queries") option.
Or use the information_schema.tables view: http://www.postgresql.org/docs/current/static/infoschema-tables.html
The table_type column will contain FOREIGN TABLE for those tables.

You can also use this command:
\detr

SELECT tc.table_name , ctu.table_name
FROM information_schema.table_constraints tc
inner join information_schema.constraint_table_usage ctu on ctu.constraint_name = tc.constraint_name
where constraint_type = 'FOREIGN KEY'

Related

How to get the name of a unique constraint in postgresql?

I need to drop a unique constraint from a postgresql table, but I didn't give it a name in the schema. Does anybody know, how to get the name of such a constraint, or how to drop it?
That is something like (for single column constaint):
tableName_columnName_key
To get constaint name write (in psql):
\d tableName
or use pg_constraint system catalog:
SELECT conname
FROM pg_constraint
WHERE conrelid =
(SELECT oid
FROM pg_class
WHERE relname LIKE 'tableName');
Also you can get it from pgAdmin in objects tree.
SELECT conname
FROM pg_constraint
WHERE conrelid = 'mytable'::regclass::oid

How to trace the foreign keys?

I have 3 different sql environments which are similar but not same. I have a column "CLMID" used in different tables. Most of them are linked with the foreign key mapping. But some tables are corrupted so do not have the foreign key mapping done right. I now need to update a data into this column in all tables. So I need a query which will find for me the list of tables that are having proper mapping, so that if I update the parent they update the child by them self. I also need to find the constraint the other way where, only if I update the child I can update the parent table.
Please note that I need to get this list without doing any update or insert operations as Its a critical database. Please help me with the query. Thank you.
Every SQL product has some way to query the database for schema data, including keys. Learning to use the Information_Schema is best IMHO because it is a standard across most platforms (as I recall Oracle does not implement it).
SQL Server probably has some easier queries with its own catalogs, but the following somewhat hairy query gives you exactly what you want and is the most cross-platform you can get.
SELECT
FK.TABLE_NAME as child_table,
CU.COLUMN_NAME as child_column,
PK.TABLE_NAME as parent_table,
PT.COLUMN_NAME as parent_column,
C.CONSTRAINT_NAME
FROM
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN
(
SELECT
i1.TABLE_NAME, i2.COLUMN_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT
ON PT.TABLE_NAME = PK.TABLE_NAME
ORDER BY
1,2,3,4
try this
show create table table-name
Upon seeing this, you can see the foreign keys the columns have. This doesnt change any of the table data
Check out sys.foreign_keys for some SQL Server-specific action. Specifically, it seems that you're interested in the delete_referential_action_desc and update_referential_action_desc columns. As far as I know, there's no way to update a child table and have the update automatically propagate to the parent. I'm willing to be corrected, though.

SQL Script To Generate a Database Dictionary **With Linked Fields**

I would like to generate a Data Dictionary for a SQL Server 2008 database that has one row for each field, and the following columns:
table_name
field_name
data_type
link_table (for when the field in question is a foreign key)
link_field (for when the field in question is a foreign key)
I can get the first 3 columns with something like the SQL script below...but I don't know how to get the last two columns of foreign key information. INFORMATION_SCHEMA.TABLE_CONSTRAINTS gets close, but doesn't have the data I'm looking for. Can someone help with this point?
SELECT TABLE_NAME,COLUMN_NAME,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
Secondarily if anyone has any suggestions on additional fields which would be helpful please post.
The following query will duplicate a column if it is involved in more than one relationship.
Select C.TABLE_SCHEMA, C.TABLE_NAME, C.COLUMN_NAME, C.DATA_TYPE
, PKCol.TABLE_SCHEMA, PKCol.TABLE_NAME, PKCol.COLUMN_NAME
From INFORMATION_SCHEMA.COLUMNS As C
Left Join (INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE As FKCol
Join INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS As FK
On FK.CONSTRAINT_NAME = FKCol.CONSTRAINT_NAME
Join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE As PKCol
On PKCol.CONSTRAINT_NAME = FK.UNIQUE_CONSTRAINT_NAME)
On FKCol.TABLE_SCHEMA = C.TABLE_SCHEMA
And FKCol.TABLE_NAME = C.TABLE_NAME
ANd FKCol.COLUMN_NAME = C.COLUMN_NAME

Dynamically determining table name given field name in SQL server

Strange situation: I am trying to remove some hard coding from my code. There is a situation where I have a field, lets say "CityID", and using this information, I want to find out which table contains a primary key called CityID.
Logically, you'd say that it's probably a table called "City" but it's not... that table is called "Cities". There are some other inconsistencies in database naming hence I can never be sure if removing the string "ID" and finding out the plural will be sufficient.
Note: Once I figure out that CityID refers to a table called Cities, I will perform a join to replace CityID with city name on the fly. I will appreciate if someonw can also tell me how to find out the first varchar field in a table given its name.
SELECT name FROM sysobjects
WHERE id IN ( SELECT id FROM syscolumns WHERE name = 'THE_COLUMN_NAME' )
To get column information from the specified table:
SELECT column_name, data_type, character_maximum_length
FROM information_schema.columns
WHERE table_name = 'myTable'
select table_name from information_schema.columns where column_name='CityID'
You can use the INFORMATION_SCHEMA tables to read metadata about the database.
SELECT
TABLE_NAME
FROM
[db].[INFORMATION_SCHEMA].[COLUMNS]
WHERE
COLUMN_NAME='CityID';
For a primer in what's in the INFORMAITON_SCHEMA, see INFORMATION_SCHEMA, a map to your database
The information you seek is all available in the information schema views. Note that you will find many sources telling you how to directly query the underlying system tables that these are views onto - and I must admit that I do the same when it's just to find something out quickly - but the recommended way for applications is to go through these views.
For example, to find your CityID column:
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'CityID'
To find the first varchar field in a table:
SELECT TOP 1 * FROM INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_NAME = 'TableName'
AND DATA_TYPE = 'varchar' -- This is off the top of my head!
ORDER BY ORDINAL_POSITION
As I understand from your question, you want to find tables which contain CITYID column in primary key
You can use SQL Server system views like sysindexes and sysindexkeys as shown in SQL tutorial to query database table primary keys including composite primary keys which are formed
SELECT
TBL.name as TableName
FROM sysobjects as PK
INNER JOIN sys.objects as TBL
on TBL.object_id = PK.parent_obj
INNER JOIN sysindexes as IND
on IND.name = PK.name AND
IND.id = TBL.object_id
INNER JOIN SysIndexKeys as KEYS
on KEYS.id = IND.id AND
KEYS.indid = IND.indid
INNER JOIN syscolumns as COL
on COL.id = KEYS.id AND
COL.colid = KEYS.colid
WHERE
PK.xtype = 'PK' AND
COL.name = 'CityID'

List of all tables with a relationship to a given table or view

In SQL Server is there a command to return a list of all tables with a relationship to a given table or view?
EDIT: SQL SERVER 2008
For SQL Server 2005 and up, use something like:
SELECT
name, OBJECT_NAME(parent_object_id) 'Table'
FROM
sys.foreign_keys
WHERE
referenced_object_id = OBJECT_ID('Your-referenced-table-name-here')
-- To find all the foreign keys established to a table!
-- Columns: FKTABLE_NAME, FKCOLUMN_NAME
sp_fkeys #pktable_name='your table name here'
Say your table name is TableX. If you want to know all foreign key relationships (columns of TableX referenced in other tables and columns of other tables referenced in TableX) you could do this:
select name 'ForeignKeyName',
OBJECT_NAME(referenced_object_id) 'RefrencedTable',
OBJECT_NAME(parent_object_id) 'ParentTable'
from sys.foreign_keys
where referenced_object_id = OBJECT_ID('TableX') or
parent_object_id = OBJECT_ID('TableX')