Q3. What is a primary key and a foreign key?
A primary key uniquely identifies each row in a table. Its values are unique and can't be NULL, and a table has exactly one. A foreign key is a column that references the primary key of another table, linking the two.
Together they model relationships: an orders table's customer_id foreign key points at the customers table's primary key, so every order belongs to a real customer. The database enforces that link.
CREATE TABLE customers (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
id INT PRIMARY KEY AUTO_INCREMENT,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(id)
);| Primary key | Foreign key | |
|---|---|---|
| Purpose | Identify a row uniquely | Link to another table's row |
| Uniqueness | Always unique | Can repeat |
| NULL allowed | No | Yes (unless declared NOT NULL) |
| Count per table | One | Many |
Key point: The follow-up is usually 'what does the foreign key enforce?'. Answer: it blocks orphan rows and can cascade deletes.
Q19. How do you write comments in MySQL?
MySQL supports three comment styles: a double dash followed by a space for a single line, a hash for a single line, and slash-star ... star-slash for a block that can span lines.
Comments matter in interviews when you annotate a tricky query to show your reasoning, which many reviewers score positively.