How to Create a Primary Key in SQL
A primary key is a column or set of columns that uniquely identifies each row in a table. It's an important part of database design, as it ensures that no two rows in the table have the same data. So, how do you create a primary key in SQL? Let's take a look!
The Solution
The solution is to use the CREATE TABLE statement with the PRIMARY KEY clause. This clause takes a single argument, which is the name of the column or set of columns that you want to use as the primary key. For example, if you wanted to create a table called users with a primary key on the id column, you would use the following query:
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name VARCHAR(255),
age INTEGER
);
Examples
Let's look at a few examples of how this statement can be used. Suppose you have a table called orders with the following data:
order_id | customer_id | order_date |
---|---|---|
1 | 1 | 2020-01-01 |
2 | 1 | 2020-01-02 |
3 | 2 | 2020-01-03 |
4 | 3 | 2020-01-04 |
If you wanted to create a primary key on the order_id column, you would use the following query:
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
order_date DATE
);
Additional Info
The CREATE TABLE statement with the PRIMARY KEY clause is supported by most major databases, including MySQL, PostgreSQL, and SQL Server. However, the syntax may vary slightly depending on the database you are using. For more information, check out the documentation for your particular database. 🤓