---
title: "How do you get a double-column unique key as foreign key?"  
description: "How do you get a double-column unique key as foreign key?"  
author: "Utpal Vishwas"  
published: 2023-07-31  
updated: 2023-08-01  
canonical: https://www.mindstick.com/forum/159400/how-do-you-get-a-double-column-unique-key-as-foreign-key  
category: "mssql server"  
tags: ["database", "sql server", "sql"]  
reading_time: 2 minutes  

---

# How do you get a double-column unique key as foreign key?

How do you get a double-[column](https://www.mindstick.com/forum/33860/how-to-calculate-column-summary-in-sql-server) [unique key](https://answers.mindstick.com/qa/116303/explain-database-primary-key-vs-unique-key) as a [foreign key](https://www.mindstick.com/blog/174/foreign-key-self-reference-constraint)?

## Replies

### Reply by Aryan Kumar

To get a double column [unique](https://www.mindstick.com/blog/12870/how-to-be-unique-in-business) key as [foreign](https://yourviews.mindstick.com/story/2164/here-are-the-best-foreign-universities-for-higher-education) key, you can use the following SQL statement:

SQL

```plaintext
ALTER TABLE child_table
ADD CONSTRAINT foreign_key_constraint
FOREIGN KEY (column_1, column_2)
REFERENCES parent_table (column_1, column_2);
```

For example, if you have the following two tables:

SQL

```plaintext
CREATE TABLE languages (
  language_id INT NOT NULL AUTO_INCREMENT,
  iso_639_1 CHAR(2) NOT NULL,
  main_flag VARCHAR(20) NOT NULL,
  PRIMARY KEY (language_id),
  UNIQUE KEY languages_un (iso_639_1, main_flag)
);

CREATE TABLE tests (
  test_id INT NOT NULL AUTO_INCREMENT,
  test_name VARCHAR(50) NOT NULL,
  iso_639_1 CHAR(2) NOT NULL,
  main_flag VARCHAR(20) NOT NULL,
  PRIMARY KEY (test_id),
  FOREIGN KEY (iso_639_1, main_flag) REFERENCES languages (iso_639_1, main_flag)
);
```

Then you can use the following SQL statement to create a foreign key constraint on the `iso_639_1` and `main_flag` columns in the `tests` table:

SQL

```plaintext
ALTER TABLE tests
ADD CONSTRAINT test_language_fk
FOREIGN KEY (iso_639_1, main_flag)
REFERENCES languages (iso_639_1, main_flag);
```

This will ensure that the `iso_639_1` and `main_flag` columns in the `tests` table reference a valid row in the `languages` table.

Here are some things to keep in mind when creating a foreign key constraint on a double column unique key:

- The two columns in the child table must be the same data type as the two columns in the parent table.
- The two columns in the child table must be unique in the child table.
- The two columns in the parent table must be unique in the parent table.


---

Original Source: https://www.mindstick.com/forum/159400/how-do-you-get-a-double-column-unique-key-as-foreign-key

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
