Introduction
A PRIMARY KEY constraint makes sure each row in a table is unique and easy to find. It helps keep data organized and prevents duplicates.
CREATE TABLE table_name ( column_name datatype PRIMARY KEY, other_column datatype );
CREATE TABLE Students ( StudentID INT PRIMARY KEY, Name VARCHAR(100) );
CREATE TABLE Orders ( OrderID INT, ProductID INT, PRIMARY KEY (OrderID, ProductID) );
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, Email VARCHAR(255) UNIQUE );
CREATE TABLE Books ( BookID INT PRIMARY KEY, Title VARCHAR(100), Author VARCHAR(100) ); INSERT INTO Books (BookID, Title, Author) VALUES (1, '1984', 'George Orwell'); INSERT INTO Books (BookID, Title, Author) VALUES (2, 'To Kill a Mockingbird', 'Harper Lee'); -- This will fail because BookID 1 already exists INSERT INTO Books (BookID, Title, Author) VALUES (1, 'Brave New World', 'Aldous Huxley'); SELECT * FROM Books;
PRIMARY KEY in a database table?id column during table creation?id INT PRIMARY KEY.id INT. Options B, C, and D have syntax errors or misplaced keywords.CREATE TABLE orders (
order_id INT,
product_id INT,
PRIMARY KEY (order_id, product_id)
);
order_id but different product_id?order_id and product_id together, so uniqueness is checked on the pair.product_id differs, the pair is unique, so both rows can be inserted without error.CREATE TABLE employees (
emp_id INT,
email VARCHAR(100),
PRIMARY KEY emp_id
);
PRIMARY KEY (emp_id).emp_id, causing syntax error.students where each student is uniquely identified by a combination of student_id and campus_id. Which of the following statements correctly enforces this using a PRIMARY KEY?Pass the test and this pattern moves unknown