how to get primary and foreign key in bigquery - google-bigquery

I'm trying to get know what are the primary and foreign keys in any table.
I tried this:
SELECT K.COLUMN_NAME FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS T
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE K
ON K.CONSTRAINT_NAME=T.CONSTRAINT_NAME
WHERE K.TABLE_NAME=‘YOUR-TABLE-NAME’
AND K.TABLE_SCHEMA=‘YOUR-DATABASE_NAME’
AND T.CONSTRAINT_TYPE=’PRIMARY KEY’ LIMIT 1;
and got this error
Table name "INFORMATION_SCHEMA.TABLE_CONSTRAINTS" missing dataset while no default dataset is set in the request.

Google BigQuery doesn't have primary key or foreign key constraints, which is why you can't find them.
Here is the INFORMATION_SCHEMA reference documentation, which shows the information that is available.

Related

Creating a foreign key constraint with non-matching data

Greetings!
I have inserted data from sql insert files into an ms sql database. Apperantly this data is not fully complete.
I discovered this when I was trying to make the ERD and create key constraints between tables.
When I try to connect article_review with order1 where order1 has a primary key and article review has a foreign key.
I have a query where it selects all records with non-matching key values:
see image: http://imgur.com/vDbCuG8
So what I want to do now:
insert new rows into article_review with the missing ID values. The values of the other columns do not really matter, they can be NULL or random generated.
A simple join won't really cut it because all of the other columns are non-identical.
ps. all above is needed because ms sql 2016 wont let me create a key constraint between 2 tables where one of them contains a value that is not in the other one and thus throws the error:
'order1' table saved successfully
'article_review' table saved successfully
'review' table
- Unable to create relationship 'FK_review_order1'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_review_order1". The conflict occurred in database "superDatabase", table "dbo.order1", column 'id'.
Do you just want to add the Foreign key for documentation only?
You could add the FK like this:
ALTER TABLE dbo.order1 WITH NOCHECK
ADD CONSTRAINT FK_review_order1 FOREIGN KEY (id) REFERENCES dbo.article_review (id)
note the WITH NOCHECK
This way the foreign key is created, but is not trusted and disabled, which can be seen with this query:
SELECT SCHEMA_NAME(fk.schema_id) AS sch, T.name,
fk.name, is_disabled, is_not_trusted, fk.is_not_for_replication
FROM sys.foreign_keys fk WITH (NOLOCK)
INNER JOIN sys.tables T WITH (NOLOCK) ON T.object_id = fk.parent_object_id
WHERE fk.is_not_trusted = 1
AND fk.is_disabled = 0
ORDER BY SCHEMA_NAME(fk.schema_id), T.name, fk.name;
idea from https://www.brentozar.com/blitz/foreign-key-trusted/

sql lists out all foreign keys of a primary key

Let's say the "user_id" field on "table_users" is primary key for 10 foreign keys on 10 other tables. I want to rename the field of primary key on "table_users", but it doesn't allow me to rename it because there are 10 foreign keys from 10 other tables are linked to it. May I know how to know which of the 10 tables has the foreign keys? What is the sql code to show the 10 tables which has the foreign keys?
I am using phpMyAdmin and InnoDB engine. I know SHOW ENGINE INNODB STATUS can do the job but it show me 1 table for each time, mean I need to repeat rename the primary key field for 10 times and run SHOW ENGINE INNODB STATUS for 10 times to find out all the 10 tables. Is there any other better solution to find out the 10 tables?
You can try querying INFORMATION_SCHEMA database:
select ku.*
from INFORMATION_SCHEMA.table_constraints tc
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku ON
(tc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME and tc.CONSTRAINT_SCHEMA =
ku.CONSTRAINT_SCHEMA )
where constraint_type='FOREIGN KEY' and ku.REFERENCED_TABLE_NAME =
'your_table_name'
As the mysql root user, you can get around this issue using
SET foreign_key_checks = 0;
This disables the constraint system and will allow you to alter your table definition. Of course from there all your foreign key constraints will be broken, and need to be dropped and recreated.
SET foreign_key_checks = 1;
Will turn the constraint system back on.
Mysql also has a data dictionary that can be queried. That was covered fully in This previous question so I'm not going to repeat any of that info.

SQL Server 2008: The columns in table do not match an existing primary key or unique constraint

I need to make some changes to a SQL Server 2008 database.
This requires the creation of a new table, and inserting a foreign key in the new table that references the Primary key of an already existing table. So I want to set up a relationship between my new tblTwo, which references the primary key of tblOne.
However when I tried to do this (through SQL Server Management Studio) I got the following error:
The columns in table 'tblOne' do not
match an existing primary key or
UNIQUE constraint
I'm not really sure what this means, and I was wondering if there was any way around it?
It means that the primary key in tblOne hasn't been properly declared - you need to go to tblOne and add the PRIMARY KEY constraint back onto it.
If you're sure that tblOne does have a PRIMARY KEY constraint, then maybe there are multiple tblOne tables in your DB, belonging to different schemas, and your references clause in your FK constraint is picking the wrong one.
If there's a composite key (which your comment would indicate), then you have to include both columns in your foreign key reference also. Note that a table can't have multiple primary keys - but if it has a composite key, you'll see a key symbol next to each column that is part of the primary key.
If you have a composite key the order is important when creating a FK, and sometimes the order is not how it is displayed.
What I do is go to the Keys section of the table1 and select script primary key as create to clipboard and then create FK using the order as shown in script
I've had this situation that led me to this topic. Same error but another cause. Maybe it will help someone.
Table1
ColA (PK)
ColB (PK)
ColC
Table2
ID (PK)
ColA
COLB
When trying to create foreign key in Table2 I've choose values from combobox in reverse order
Table1.ColB = Table2.ColB
Table1.ColA = Table2.ColA
This was throwing me an error like in topic name. Creating FK keeping order of columns in Primary key table as they are, made error disappear.
Stupid, but.. :)
If you still get that error after you have followed all advice from the above answers and everything looks right.
One way to fix it is by Removing your Primary keys for both tables, Save, Refresh, and add them again.
Then try to add your relationship again.
This Error happened with me When I tried to add foreign key constraint starting from PrimaryKey Table
Simpy go to other table and and create this foreign key constraint from there (foreign key Table)
This issue caught me out, I was adding the relationship on the wrong table. So if you're trying to add a relationship in table A to table B, try adding the relationship in table B to table A.
That looks like you are trying to create a foreign key in tblTwo that does not match (or participate) with any primary key or unique index in tblOne.
Check this link on MSDN regarding it. Here you have another link with a practical case.
EDIT:
Answwering to your comment, I understand you mean there are 2 fields in the primary key (which makes it a composite). In SQL it is not possible to have 2 primary keys on the same table.
IMHO, a foreign key field should always refer to a single register in the referenced table (i.e. the whole primary key in your case). That means you need to put both fields of the tblOne primary key in tblTwo before creating the foreign key.
Anyway, I have investigated a bit over the Internet and it seems SQL Server 2008 (as some prior versions and other RDBMS) gives you the possibility to reference only part of the primary key as long as this part is a candidate key (Not Null and Unique) and you create an unique constraint on it.
I am not sure you can use that in your case, but check this link for more information on it.
I have found that the column names must match.
Example:
So if tblOne has id called categoryId a reference in tblTwo must also be called categoryId.
_tblname, primary key name, foreign key_
tblOne, "categoryId", none
tblTwo, "exampleId", "categoryId"
I noticed this when trying to create foreign key between 2 tables that both had the column name "id" as primary key.
If nothing helps, then this could be the reason:
Considering this case:
Table A:
Column 1 (Primary Key)
Column 2 (Primary Key)
Column 3
Column 4
Table B:
Column a (Primary Key)
Column b
Column c
when you are defining a dependency B to A, then you are forced to respect the order in which the primaries are defined.
That's mean your dependency should look like this:
Table A Table B
Column 1 Column b
Column 2 Column c
AND NOT:
Table A Table B
Column 2 Column c
Column 1 Column b
then this will lead to the error you are encountering.
I've found another way to get this error. This can also happen if you are trying to make a recursive foreign key (a foreign key to the primary key in the same table) in design view in SQL Management Studio. If you haven't yet saved the table with the primary key it will return this message. Simply save the table then it will allow you to create the foreign key.
If you have data in your tables this could be the issue.
In my case I had some data in the Account table that I loaded at 3 pm, and some data in Contact table that I loaded at 3:10 pm, so Contact table had some values that weren't in my Account table yet.
I ended up deleting these values from the contact table and then managed to add a key without any problems.
Kindly also see that there are no existing data inside the table where the primary key is defined while setting the foreign key with another table column.
this was the cause of the error in my case.
I had to take backup empty the table set the relationship and then upload the data back.
sharing my experience
Was using ms sql smss

MySQL Error Code: 1005

I am trying to add foreign keys to my table but receiving this error.
Error Code: 1005 Can't create table 'william.#sql-88c_3' (errno: 150)
I have 3 tables. employee, client and Contract.
employe [employee_no PK] , Client[customer_no PK] contract [contract_no PK]
I want to have Foreign keys for contract as contract [contract_no PK, employee_no FK], customer_no FK]
I tried to do directly it failed, I am now trying the alter statement.Is anything wrong with the Alter script?
ALTER TABLE contract
ADD CONSTRAINT `employee_no_fk2` FOREIGN KEY (`employee_no`) REFERENCES `employee`
(`employee_no`);
ALTER TABLE contract
ADD CONSTRAINT `Customer_no_fk2` FOREIGN KEY (`Customer_no`) REFERENCES `client`
(`Customer_no`);
Most of such error will be related to data type miss match or so.. If you could go through these links.. it might help you i guess.. Check-this
... also Check-this
As they say in the second link:
The first place you should look is whether the data types agree
between the foreign key and primary key columns.
mysql> SHOW engine innodb STATUS;
------------------------
LATEST FOREIGN KEY ERROR
------------------------
100130 17:16:57 Error IN FOREIGN KEY CONSTRAINT OF TABLE sampledb/#sql-4a0_2:
FOREIGN KEY(member_type)
REFERENCES common_lookup(common_lookup_id):
Cannot find an INDEX IN the referenced TABLE WHERE the
referenced COLUMNS appear AS the FIRST COLUMNS, OR COLUMN types
IN the TABLE AND the referenced TABLE do NOT MATCH FOR CONSTRAINT.
make sure that one of the key field that you are trying to reference does not have an index and/or is not a primary key. and the two key fields type and/or size should be an exact match also make sure that both tables are InnoDB tables.
This can happen due to two reasons
Table creation failed because a foreign key constraint was not correctly formed or
Datatype mismatch in the constraints.
the below link would be helpful
http://dev.mysql.com/doc/refman/5.0/en/innodb-error-codes.html
Last time I encountered this, it was the constraints: referenced table key type was 'int' and referring table had 'unsigned int' referring field by mistake, instead of int.

Foreign key referencing a 2 columns primary key in SQL Server

This question is pretty much similar to this one, but for SQL Server 2005 :
I have 2 tables in my database:
--'#' denotes the primary key
[Libraries]
#ID #Application Name
1 MyApp Title 1
2 MyApp Title 2
[Content]
#ID Application LibraryID Content
10 MyApp 1 xxx
11 MyApp 1 yyy
(the database is obviously much more complex and having this double key makes sense)
Each library is identified by its unique ID and Application name. I'm trying to ensure that each content is properly referencing an existing library.
When creating the constraint (using the Wizard) as
Primary key table Foreign key table
[Libraries] [Content]
ID ---> LibraryID
Application ---> Application
I have the following error:
The columns in table 'Libraries' do
not match an existing primary key or
UNIQUE constraint
Do you have any idea of what is going on? and if it's possible at all using SQL Server? (I can't modify the [Library] table at all)
Thanks a lot for your help!
Of course it's possible to create a foreign key relationship to a compound (more than one column) primary key. You didn't show us the statement you're using to try and create that relationship - it should be something like:
ALTER TABLE dbo.Content
ADD CONSTRAINT FK_Content_Libraries
FOREIGN KEY(LibraryID, Application)
REFERENCES dbo.Libraries(ID, Application)
Is that what you're using?? If (ID, Application) is indeed the primary key on dbo.Libraries, this statement should definitely work.
Luk: just to check - can you run this statement in your database and report back what the output is??
SELECT
tc.TABLE_NAME,
tc.CONSTRAINT_NAME,
ccu.COLUMN_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
INNER JOIN
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
ON ccu.TABLE_NAME = tc.TABLE_NAME AND ccu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
WHERE
tc.TABLE_NAME IN ('Libraries', 'Content')
Note that the fields must be in the same order. If the Primary Key you are referencing is specified as (Application, ID) then your foreign key must reference (Application, ID) and NOT (ID, Application) as they are seen as two different keys.
The key is "the order of the column should be the same"
Example:
create Table A (
A_ID char(3) primary key,
A_name char(10) primary key,
A_desc desc char(50)
)
create Table B (
B_ID char(3) primary key,
B_A_ID char(3),
B_A_Name char(10),
constraint [Fk_B_01] foreign key (B_A_ID,B_A_Name) references A(A_ID,A_Name)
)
the column order on table A should be --> A_ID then A_Name; defining the foreign key should follow the same order as well.
The Content table likely to have multiple duplicate Application values that can't be mapped to Libraries. Is it possible to drop the Application column from the Libraries Primary Key Index and add it as a Unique Key Index instead?
I had the same problem and I think I have the solution.
If your field Application in table Library has a foreign key that references a field in another table (named Application I would bet), then your field Application in table Library has to have a foreign key to table Application too.
After that you can do your composed foreign key.
Excuse my poor english, and sorry if I'm wrong.