views:

392

answers:

2

How to define your specified attribute like StudentId in student table as Primary key in sqlite

+4  A: 
CREATE TABLE Student(
  id INTEGER PRIMARY KEY,
  first_name TEXT, 
  last_name TEXT
);

From the Sqlite spec:

One exception to the typelessness of SQLite is a column whose type is INTEGER PRIMARY KEY. (And you must use "INTEGER" not "INT". A column of type INT PRIMARY KEY is typeless just like any other.) INTEGER PRIMARY KEY columns must contain a 32-bit signed integer. Any attempt to insert non-integer data will result in an error.

http://www.sqlite.org/datatypes.html

You can also place a primary key on the arbitrary blobish data eg:

CREATE TABLE Student(id PRIMARY KEY, name)

Its a bit risky cause

INSERT INTO Student(1, "hello") 
INSERT INTO Student("1", "hello")

will result in two rows.

If you need a unique constraint on other stuff you can try using the Create Index command

Sam Saffron
And note that you have to do it in a CREATE TABLE statement. SQLite can't change constraints in a ALTER TABLE statement.
lc
@Sinan: Give me a break. First of all, you can't have a PK as anything not integer in SQLite. Secondly, there's one convention that says to separate meaningful data from the row IDs. So you should add an extra column for student ID, not use the PK. Finally, you assuming things about the OP's schema is no better than the answerer. Write a new answer, but you have no right to mark this down.
lc
@Ic: "you can't have a PK as anything not integer in SQLite" is quite incorrect -- you certainly can have a TEXT PK (it can't be autoincrement of course); where'd you get that idea from?
John Machin
+5  A: 
CREATE TABLE Students (
  StudentId INTEGER PRIMARY KEY,
  Name VARCHAR(80)
)

is one simple way.

Alex Martelli
@Sinan: See my comment above. I also don't see your better suggestion here...
lc
@Alex, note VARCHAR and TEXT are completely interchangable in Sqlite. The limit varchar(80) is meaningless and ignored by Sqlite.
Sam Saffron
@Sam, sure -- "everything's a string" anyway in SQLite (save for the constraint on primary key usefully being integer) -- I still prefer to write my schemas type-carefully so I don't trip up when I'm writing them in MySQL, PostgreSQL, and the like!-)
Alex Martelli