Question

I have a table with 3 columns A(, B, C) and have 2 constraints

  1. A and B should be jointly unique which I have done by defining a unique constraint.
  2. For any given value in A, there can be only one True in C. (A, C=True) has to be unique. I need help in defining the second constraint.

e.g Data set

A : B C

a1 : b1 : False

a1 : b2 : True

a1 : b3 : False

a2 : b1 : True

a2 : b2 : False

a2 : b3 : False

Was it helpful?

Solution

I don't think this can be expressed in a database-portable way without changing the schema. Partial index can do this:

CREATE UNIQUE INDEX One_C_Per_A_Idx ON Table(A) WHERE C;

But it is only available on PostgreSQL and SQL Server (and simulated with functional index on Oracle). With PostgreSQL back-end you can use postgresql_where keyword argument to Index (see docs) to define partial index in SQLAlchemy.

A portable way is to split this into at least two tables, converting explicit boolean column into an implicit "present in the referencing table" expression. SQL:

CREATE TABLE my_table (
    a integer NOT NULL,
    b integer NOT NULL,
    PRIMARY KEY (a, b)
);

CREATE TABLE flagged (
    a integer NOT NULL PRIMARY KEY,
    b integer NOT NULL,
    FOREIGN KEY (a, b) REFERENCES my_table(a, b)
);

Query to get equivalent of the original table:

SELECT t.a, t.b, f.a IS NOT NULL AS c
FROM my_table t LEFT OUTER JOIN flagged f ON t.a = f.a AND t.b = f.b;

I'll omit SQLAlchemy model definitions for now, because I am not sure which solution suits your needs the best.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top