📅  最后修改于: 2023-12-03 14:47:34.742000             🧑  作者: Mango
In SQL, an alternate key is a column or a combination of columns that can uniquely identify a record within a table, similar to a primary key. However, unlike the primary key, an alternate key may not be selected as the main identifier of a table. It provides an alternative means to uniquely identify a record when the primary key is not suitable or has not been defined.
CREATE TABLE employees (
emp_id INT,
emp_email VARCHAR(100) UNIQUE, -- Alternate key
emp_name VARCHAR(100),
emp_department VARCHAR(50),
emp_salary DECIMAL(10,2),
...
);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
...
FOREIGN KEY (customer_id) REFERENCES customers (customer_id), -- Primary key reference
FOREIGN KEY (order_number) REFERENCES invoices (order_number) -- Alternate key reference
);
SELECT *
FROM employees
WHERE emp_email = 'john.doe@example.com';
Alternate keys in SQL provide an additional means to uniquely identify records in a table. They ensure data integrity, improve query performance, and enhance database design flexibility. By using alternate keys, you can establish relationships between tables and choose suitable identifiers for your tables based on your requirements.