How to query all Foreign keys in each table using SQL? - sql

I have a database with more than 1600+ tables, and I need to know the foreign keys of each table. I only know how to look for foreign keys manually by clicking the table > column. How to query it and show it in one table along with the table name?

The SQL standard defines catalog tables and catalog views for this purpose in the schema INFORMATION_SCHEMA.
E.g. "The REFERENTIAL_CONSTRAINTS table has one row for each row in the TABLE_CONSTRAINTS table that has a CONSTRAINT_TYPE value of “FOREIGN KEY”." and "CONSTRAINT_COLUMN_USAGE view [...] Identify the columns used by referential constraints, unique constraints, check constraints, and assertions defined
in this catalog and owned by a given user or role.".
There are several tables/views to inspect for your particular purpose.
If your SQL engine supports INFORMATION_SCHEMA, look in the INFORMATION_SCHEMA section of your product's documentation.
If your SQL engine does not support INFORMATION_SCHEMA, then its catalog tables (if any) will be proprietary (and may possibly provide only rudimentary info) and you must inspect your product's doco for the detail of its catalog tables.

Related

SQL server tables not showing relation in Diagram

I have a lot of tables that share keys but in the diagram does not show a route from table to table. Most tables will show a route to but a lot of them do not although they should. I've already checked data types, and I can join these tables, so I am wondering if this is something I have to do within the diagram tool to set the relationships to correlating tables. I assumed this is something sql server automatically does when you select tables for the diagram.
Any suggestions?
Edited:
It could also just be that you need to "refresh" the diagram, remove and ad back the table to the diagram.
Original:
The relationship is not shown in the diagram if this does not exist. Maybe you defined they key in both tables with same name and data type but you are missing the explicit reference (constraint). Something like this:
ALTER TABLE Sales.TempSalesReason
ADD CONSTRAINT FK_TempSales_SalesReason FOREIGN KEY (TempID)
REFERENCES Sales.SalesReason (SalesReasonID)
ON DELETE CASCADE
ON UPDATE CASCADE
;
You may want to ommit the ON [ACTION] CASCADE, though. The reason you can use JOIN in the queries is because the contraint is not mandatory in order to JOIN the tables, you can JOIN any columns as longs as the data type allows it. You can even JOIN with columns that don't have a PK, but this will have a bad performance (and is also another topic).
Refer to official documentation on how to do it with the graphic tool or with code:
https://learn.microsoft.com/en-us/sql/relational-databases/tables/create-foreign-key-relationships?view=sql-server-2016

What is exclusion constraint in PostgreSQL? What is the according term (and sample SQL script) in Microsoft SQL Server?

I read a book
Exclusion constraint
CREATE TABLE movies
(
Title TEXT,
Copies INTEGER
);
ALTER TABLE movies ADD EXCLUDE (title WITH=, copies WITH=);
What is the meaning of Exclusion constraints? What is the according term (and sample SQL script) in Microsoft SQL Server?
What is the meaning of Exclusion constraints?
That's a special type of constraints, that is defined as a series of comparaison on table columns. It guaranties that there cannot be two different rows for which the comparisons are all true.
In the (oversimplified) example that is presented in the book, the constraint prevents two different rows to have the same title and the same copies.
Exclusion constraints are very powerful; they have a flexible syntax, that can accomodate much more complex cases that what is demonstrated in your book. A typical example is to ensure that, given a table with two timestamp columns, there is no overlap in the timestamp ranges across rows.
What is the according term (and sample SQL script) in Microsoft SQL Server?
I don't think that such feature exists in SQL Server. It has check constraints, but that does not offer the same range of functionality as Postgres' exclusion constraints.

Is USER_NAME column unique in HANA DB USERS table?

Is USER_NAME field/column unique in HANA Database USERS table? I am seeing just number in USER_ID values.
Like BNAME in SAP USR02 table, I want to know what is the unique(or equivalent to bname) value field in HANA DB USERS table.
Amandeep Modgil's answer is not wrong but does not fully answer the question.
Of course, the documentation makes it clear that user names in SAP HANA need to be unique. However, it does not specifically explain whether or how this is enforced/guaranteed.
The "DB dev way" to find out something like this is to check the table structure used by HANA to store users.
Looking at the PUBLIC.USERS objects, we realize: this is not a table but a view instead.
Views don't have any constraints assigned to them, so any primary key or unique constraint must be implemented with one of the tables referenced by the view.
The next step is to review the source code for the view. In SAP HANA Studio one can simply mark the name of the view in the SQL editor and choose "Show Definition" from the context menu.
For PUBLIC.USERS this opens two(!) new windows:
one for the public synonym (there really is no PUBLIC schema, just synonyms) for USERS
and another one for the view SYS.USERS
This SYS schema is where SAP HANA system objects are implemented, so it's not surprising to find the view for USERS here.
In my HANA Express 2.00.045 system, the source code for the view surprisingly begins with
CREATE **ROW TABLE** "SYS"."USERS" ( "USER_NAME",
"USER_ID",
"USERGROUP_NAME" ...
That's weird at the very least, and I suspect it might be a bug as all other metadata entries for this object make it clear that this is in fact a view.
But I digress...
The question to answer was: where is the uniqueness of USER_NAME enforced?
Scrolling down the last main FROM-clause of the SYS.USERS-view points to a table: SYS.P_USERS_.
The trailing underscore in the name indicates that this is an internal HANA object that should never be directly used by any user or application. But that does not stop us from looking at it. Appropriate privileges are required for that, though. The "normal" application user account probably won't be able to directly look at this table's definition. I'm just using the SYSTEM user in this case.
Anyhow, we use the same technique as before: mark the SYS.P_USERS_ table in the SQL Editor, choose "Show definition" and we get: the definition of the table that holds the user accounts in SAP HANA.
The first three columns are defined like this:
Name SQL Data Type Dimension Column Store Data Type Key Not Null
OID BIGINT FIXED X
NAME NVARCHAR 256 STRING
LAST_SUCCESSFUL_CONNECT TIMESTAMP LONGDATE ...
Notice how there is no primary key defined on this table and how only OID has a NOT NULL constraint?
Clearly, the uniqueness of NAME is not guaranteed by table constraints.
So what else could it be?
Let's switch to the Indexes tab of the table definition and we find:
IDX_P_USERS_OID, indexed columns: "OID" ASC
IDX_P_USERS_NAME, index columns: "NAME" ASC
AND for both of these indexes the Unique-flag is set.
And there we have it:
Both OID (exposed as USER_ID) and NAME (exposed as USER_NAME) are unique in SAP HANA, enforced by unique indexes on the internal table that holds these user account entries.
You can look up the schema information on SAP portal link below:
https://help.sap.com/viewer/4fe29514fd584807ac9f2a04f6754767/2.0.01/en-US/21026099751910148e0cdbddc75652b8.html
Although it does not tell you whether a particular column is the primary key or need to be unique, but you can combine this information with the data from following system view and get the information you are after.
https://help.sap.com/viewer/4fe29514fd584807ac9f2a04f6754767/2.0.05/en-US/210197377519101481cfb213f0b84848.html
I have highlighted the columns in the tables system view you need in the screenshot below

What is the difference between key and constraint in sql?

I have referred many documents but couldn't find a supporting/compromising answer for this. Can anyone briefly describe the difference between key and constraints?
A key is a single or combination of multiple fields in a table. Its is used to fetch or retrieve records/data-rows from data table according to the condition/requirement. Keys are also used to create relationship among different database tables or views.
SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action, the action is aborted.
Constraints can be specified when the table is created (inside the CREATE TABLE statement) or after the table is created (inside the ALTER TABLE statement).
you can check more documentation in the links below
Keys
Constraint

Design ideas for a versioned db schema with related tables also versioned

Here is the drill, I want to version a database. I have done this before using multiple rows where the table primary key becomes a combination of the row id and either a datestamp or a version #.
Now I want to version a table that depends on many other small tables. Versioning each table will be a giant PITA, so I am looking for good options to verion a schema where the data to be versioned spreads over multiple tables.
All related tables are properly keyed with foreign key relationships. The database is currently on Sql Server 2005.