[Solved] Problem with UNIQUE CONSTRAINT in SQL code

Creating tables and queries
Post Reply
johlson
Posts: 17
Joined: Wed May 27, 2015 4:51 am

[Solved] Problem with UNIQUE CONSTRAINT in SQL code

Post by johlson »

There is a table (t_Orchestra) within a database. I wish to prevent duplicate entries into the txtOrchestra_Name_(Original_Language) field. I have attempted to accomplish this with the following SQL code: ALTER TABLE "t_Orchestra" ADD CONSTRAINT Orch_Name_unique UNIQUE ("txtOrchestra_Name_(Original_Language)"). This fails with the message “Unexpected token: " in statement [ALTER TABLE]". Can someone explain what I am doing wrong? Any help would be greatly appreciated.
Last edited by johlson on Thu Aug 27, 2015 4:35 am, edited 1 time in total.
johlson
OpenOffice Version 4.1.1 on Windows 10
User avatar
Villeroy
Volunteer
Posts: 31279
Joined: Mon Oct 08, 2007 1:35 am
Location: Germany

Re: Problem with UNIQUE CONSTRAINT in SQL code

Post by Villeroy »

The documentation suggests this:

Code: Select all

ALTER TABLE <tablename> ADD [CONSTRAINT <constraintname>] UNIQUE (<column list>);
<names> are placeholders for actual names of tables, fields and aliases in double quotes.
[brackets] mean that something is optional. You can leave it out completely. The [] are not written
Anything written (round braces) refers to a single named item which could be a list of many named items as well. The () need to be written.

Simply replacing all <names> with your actual names in double-quotes I get this:

Code: Select all

ALTER TABLE "t_Orchestra" ADD CONSTRAINT "Orch_Name_unique" UNIQUE ( "txtOrchestra_Name_(Original_Language)" );
Please, edit this topic's initial post and add "[Solved]" to the subject line if your problem has been solved.
Ubuntu 18.04 with LibreOffice 6.0, latest OpenOffice and LibreOffice
User avatar
MTP
Volunteer
Posts: 1620
Joined: Mon Sep 10, 2012 7:31 pm
Location: Midwest USA

Re: Problem with UNIQUE CONSTRAINT in SQL code

Post by MTP »

You can also use the GUI to create constraints. Open the table in edit mode, click on Tools->Index Design, click the top left icon in the popup window for "new index", name it, choose your column in the dropdown box, then make sure to check the box "Unique".
OpenOffice 4.1.1 on Windows 10, HSQLDB 1.8 split database
johlson
Posts: 17
Joined: Wed May 27, 2015 4:51 am

Re: Problem with UNIQUE CONSTRAINT in SQL code

Post by johlson »

As usual, Villeroy was spot on in his solution. Many thanks. Thanks also to HTP, whose solution I did not test, but will keep in mind.
johlson
OpenOffice Version 4.1.1 on Windows 10
Post Reply