B4J Question Unique Primary Key

Pelky

Active Member
Licensed User
Longtime User
Is there a way to ensure that a column (field) is unique in an sql database?

I have looked at INTEGER PRIMARY KEY but I am looking to ensure a STRING within the Database is unique; ie a name + date of birth

Thank you in advance
 

DarkoT

Active Member
Licensed User
Hi,
which db you are using? SqlLite, MySql or something else? There is only way to check with table description if some field already exists or not... I guess you have xxx tables in database and want to have unique field in one of this tables? Or?
 
Upvote 0

Num3

Active Member
Licensed User
Longtime User
You can create the table with a field with auto_increment + primary key.
The database will increase the field by 1 each time you create a record, you don't need to do anything

B4X:
   CREATE TABLE YOURTABLE
   (
      id INT AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(90),
      birthday VARCHAR(16)
   )

If you want to ensure two fields are unique try this:

B4X:
   CREATE TABLE YOURTABLE
   (
      id INT AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(90),
      birthday VARCHAR(16),
      CONSTRAINT UC_Person UNIQUE (name,birthday)
   )

But be aware, if your try to insert a record that collides there will be errors.

Take a look here W3schools
 
Last edited:
Upvote 0
Top