Sample Header Ad - 728x90

Database Administrators

Q&A for database professionals who wish to improve their database skills

Latest Questions

2 votes
1 answers
1033 views
Adding a check constraint on a new column with default value on a large table
I have a large table (1–2m rows) and need to add a column. It is an integer column with a default of `0`. I am also adding a check constraint that `column >= 0`. Currently, I am making the change in these steps: 1. Add the column with the default 2. Add a check constraint with `NOT VALID` so it does...
I have a large table (1–2m rows) and need to add a column. It is an integer column with a default of 0. I am also adding a check constraint that column >= 0. Currently, I am making the change in these steps: 1. Add the column with the default 2. Add a check constraint with NOT VALID so it doesn't lock the table 3. VALIDATE CONSTRAINT A coworker brought up that Postgres could be smart enough to know that adding a column with a default and then, in the same transaction, immediately adding the check constraint. Since the default passes the check constraint, all rows are guaranteed (I think?) to pass and so it wouldn't need to do a full table scan. Is that correct? Are there better ways of doing this?
Chris (121 rep)
Jul 15, 2020, 06:34 PM • Last activity: Jun 29, 2025, 08:00 PM
2 votes
1 answers
230 views
Create Constraint To Ensure Date Range Is Within Another Date Range
I am trying to create a scheduling application, and part of it requires the date range of a row to be within the date range of a row in another table, which it is referencing via a foreign key. Note: This is Postgres. The schema is as follows: ```none table_1: id Serial name Varchar date_range DATER...
I am trying to create a scheduling application, and part of it requires the date range of a row to be within the date range of a row in another table, which it is referencing via a foreign key. Note: This is Postgres. The schema is as follows:
table_1:
id Serial
name Varchar
date_range DATERANGE
table_2:
id Serial
name Varchar
date_range DATERANGE
table_1_id - Foreign Key, this references the id of a record in table 1.
I am trying to figure out how to write a check constraint that enforces the rule that the date_range in table_2 has to be within the date_range of table_1.
lucifer34 (21 rep)
Feb 8, 2024, 09:41 PM • Last activity: Jun 11, 2025, 01:03 PM
1 votes
1 answers
69 views
How do I check a date in a DB2 table?
Is it possible to include a check for a date in a Db2 table? I have tried: ```sql CREATE TABLE customers ( id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, email VARCHAR(60) NOT NULL UNIQUE, -- etc dob date, -- Db2: CHECK (dob SQL Error [42621]: A check constraint or generated column that is def...
Is it possible to include a check for a date in a Db2 table? I have tried: ```sql CREATE TABLE customers ( id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, email VARCHAR(60) NOT NULL UNIQUE, -- etc dob date, -- Db2: CHECK (dob SQL Error : A check constraint or generated column that is defined with "current_date" is invalid Perhaps there’s a workaround?
Manngo (3145 rep)
Mar 9, 2025, 06:05 AM • Last activity: Mar 9, 2025, 01:42 PM
8 votes
3 answers
749 views
How do I add a trusted check constraint quickly
I'm adding a check constraint to a large table because I want to prepare to switch it into a partitioned table using partition switching. The check is a simple inequality check on a column and there is an index on that column. But when I add the constraint, SQL Server still performs a scan of the wh...
I'm adding a check constraint to a large table because I want to prepare to switch it into a partitioned table using partition switching. The check is a simple inequality check on a column and there is an index on that column. But when I add the constraint, SQL Server still performs a scan of the whole table. Is it possible to add the constraint quickly and keep it trusted? I hoped it would be possible because of the index. Here is a reproduction that shows that scan:
USE tempdb;
GO

SELECT * 
INTO MY_MESSAGES
FROM sys.messages;

CREATE CLUSTERED INDEX IX_MY_MESSAGES ON dbo.MY_MESSAGES(message_id);

SET STATISTICS IO ON;
ALTER TABLE dbo.MY_MESSAGES
	ADD CONSTRAINT CK_mymessages CHECK (message_id < 50000);
SET STATISTICS IO OFF;

DROP TABLE IF EXISTS dbo.MY_MESSAGES;
This is shown in the messages tab:
Table 'MY_MESSAGES'. Scan count 1, logical reads 10955
Michael J Swart (2235 rep)
Nov 26, 2024, 03:45 PM • Last activity: Nov 28, 2024, 08:25 AM
0 votes
2 answers
69 views
How to only allow a boolean to be true if another boolean in the same row is true in MariaDB?
I have two boolean columns in my table. One called IsUnlisted and one called IsPrivate. I only want to allow IsPrivate to be 1 (TRUE) if IsUnlisted is 1 (TRUE) as well using a check constraint. I am using MariaDB which shares most things with mysql.
I have two boolean columns in my table. One called IsUnlisted and one called IsPrivate. I only want to allow IsPrivate to be 1 (TRUE) if IsUnlisted is 1 (TRUE) as well using a check constraint. I am using MariaDB which shares most things with mysql.
Garbg (13 rep)
Sep 24, 2024, 10:23 PM • Last activity: Sep 28, 2024, 12:54 AM
0 votes
0 answers
75 views
Is it frowned upon to have check constraints only applicable to a subset of rows?
At my place of work we are running into an issue, we have many parameters stored in a table like so. | ModelParameterValueID | ModelParameterID | ModelID | CurrentValue | Updated Date | | --- | --- | --- | --- | --- | | 187883 | 81 | 10849 | TEMPSTR | 26-Jul-24 | `ModelParameterID = 81` corresponds...
At my place of work we are running into an issue, we have many parameters stored in a table like so. | ModelParameterValueID | ModelParameterID | ModelID | CurrentValue | Updated Date | | --- | --- | --- | --- | --- | | 187883 | 81 | 10849 | TEMPSTR | 26-Jul-24 | ModelParameterID = 81 corresponds to a string parameter in our database. Our technicians have some models that need the CurrentValue nulled, but only for that modelParameterID. We have a CHECK in place that makes sure CurrentValue is not Null, so I surmised to myself that if we could have a conditional CHECK that allowed CurrentValue to be Null only if ModelParameterID = 81 then this issues would not be there. So I contacted our database administrator and asked him if a change of this kind would be possible. He said > It is not good practice to have a constraint defined like that based on a particular value in another column. I asked him to explain but he would not. Could someone explain as to why something like this is frowned upon? And if it indeed is not good practice, then what would an alternative be?
mhabes (1 rep)
Sep 26, 2024, 01:41 PM • Last activity: Sep 27, 2024, 08:06 AM
2 votes
3 answers
685 views
Check constraint to guarantee ltree ancestors
I ran into an issue where we had a tree structure that looked like this: ```sql select title, tree_path from my_table where tree_path <@ '3'; title | tree_path ----------------------- item A | 3 item B | 3.1.1 item C | 3.1.2 item D | 3.1.3 ``` I somehow lost anything at 3.1 so all `tree_path <@ '3.1...
I ran into an issue where we had a tree structure that looked like this:
select title, tree_path from my_table where tree_path <@ '3';

title    | tree_path
-----------------------
item A   | 3
item B   | 3.1.1
item C   | 3.1.2
item D   | 3.1.3
I somehow lost anything at 3.1 so all tree_path <@ '3.1' were orphaned. Is there some sort of constraint I can write that would ensure that a node's ancestors exist?
lorddev (123 rep)
Jun 16, 2021, 01:27 AM • Last activity: Mar 15, 2024, 05:39 PM
-3 votes
1 answers
383 views
Getting in this error what i have to change Column check constraint 'machine_chk_2' references other
CREATE TABLE machine.machine ( m_id INT PRIMARY KEY, mname VARCHAR(20) NOT NULL, mprice FLOAT CHECK (mprice > 0), mcost FLOAT CHECK (mcost < mprice) );
CREATE TABLE machine.machine ( m_id INT PRIMARY KEY, mname VARCHAR(20) NOT NULL, mprice FLOAT CHECK (mprice > 0), mcost FLOAT CHECK (mcost < mprice) );
user285924 (1 rep)
Feb 6, 2024, 05:58 AM • Last activity: Feb 6, 2024, 07:02 AM
3 votes
0 answers
253 views
Why can't I combine CHECK constraint with ON UPDATE CASCADE?
Given table A: CREATE TABLE `A` ( `id` int NOT NULL, PRIMARY KEY (`id`) ); when I try to create this second table B: CREATE TABLE `B` ( `id` int NOT NULL, `val1` int, PRIMARY KEY (`id`), CONSTRAINT `a_nonsense_foreign_key` FOREIGN KEY (`val1`) REFERENCES `A` (`id`) ON UPDATE CASCADE, CONSTRAINT `a_n...
Given table A: CREATE TABLE A ( id int NOT NULL, PRIMARY KEY (id) ); when I try to create this second table B: CREATE TABLE B ( id int NOT NULL, val1 int, PRIMARY KEY (id), CONSTRAINT a_nonsense_foreign_key FOREIGN KEY (val1) REFERENCES A (id) ON UPDATE CASCADE, CONSTRAINT a_nonsense_check CHECK (val1 > 10) ); I get the following error message: SQL Error [HY000]: (conn=6) Function or expression 'val1' cannot be used in the CHECK clause of a_nonsense_check If i change the ON UPDATE CASCADE to ON UPDATE RESTRICT I get no errors. Another observation is that ON DELETE CASCADE doesn't generate errors. Why is it that the CHECK constraint cannot be combined with the ON UPDATE CASCADE statement? Can I find this behaviour in the documentation somewhere? I am using MariaDB and I believe the standard engine is InnoDB. **And a short disclaimer:** I am new to databases, and the root of this problem might be an XY-problem. I am, however, curious to why this limitation exists or if I am doing something wrong :)
Jonatan G (31 rep)
Dec 17, 2023, 09:46 PM
1 votes
2 answers
94 views
Correct (as in normalized) way to express a relationship between 3 tables with complex(?) constraints?
I'll be using Postgres for the examples, but feel free to show examples in other databases if needed. The simplified schema: ```sql create table factory ( id serial primary key, detail text not null ); create table process ( id serial primary key, detail text not null ); create table item ( id seria...
I'll be using Postgres for the examples, but feel free to show examples in other databases if needed. The simplified schema:
create table factory (
  id serial primary key,
  detail text not null
);

create table process (
  id serial primary key,
  detail text not null
);

create table item (
  id serial primary key,
  detail text not null
);
I'll refer Factory as [F], Process as [P] and Item as [I]. The schema has the following conceptual relationships: - Each Process is exclusive to one Factory, so [P] n -> 1 [F] - Each Item is exclusive to one Factory, so [I] n -> 1 [F] - Each Item can be made by multiple Processes, so [P] n -> 1 [I] To express this relationships I came up with:
create table factory_item_process (
  factory_id integer not null references factory(id),
  process_id integer not null references process(id),
  item_id integer not null references item(id),
  constraint pk_factory_item_process primary key (
    factory_id, process_id, item_id
  ),
  constraint uq_factory_item_process_process unique (process_id)
);
This takes care of [P] n -> 1 [I] and [P] n -> 1 [F], but doesn't solve [I] n -> 1 [F]. There is no way to convey [I] n -> 1 [F] with unique key constraints, so I created a simple function that checks if [I] already belongs to an [F]:
create function in_other_factories(
  factory_id integer, 
  item_id integer
) returns boolean
language sql returns null on null input
  return true in (
    select 
      true 
    from factory_item_process
    where factory_id  $1
      and item_id = $2
  );
alter table factory_item_process 
  add constraint chk_factory_item check(not in_other_factories(factory_id, item_id));
What is right & wrong about this to express these relationships? Making a check with a user-defined function is a code smell. I don't if the tables are correctly normalized. I chose to use another table for this relationship because this relationship will have attributes that are exclusive to itself.
Cidos (21 rep)
Nov 9, 2023, 03:49 PM • Last activity: Nov 15, 2023, 02:55 PM
6 votes
1 answers
10522 views
Column constraint based on values in another column
I have a PostgreSQL table `phase_steps`, with the following example rows: phase_step_id|step_type|step_status| -------------+---------+-----------+ 1| RESEARCH| | 2| SURVEY| | Update values to the `step_status` column depend on what value the `step_type` value is. When `step_type` is 'RESEARCH', onl...
I have a PostgreSQL table phase_steps, with the following example rows: phase_step_id|step_type|step_status| -------------+---------+-----------+ 1| RESEARCH| | 2| SURVEY| | Update values to the step_status column depend on what value the step_type value is. When step_type is 'RESEARCH', only values of 'COMPLETE' or 'INCOMPLETE' can be entered for step_status values. When step_type is 'SURVEY', only values of 'ASSIGNED' or 'NOT ASSIGNED' can be entered for step_status values. I tried to manage the 'RESEARCH' step_status constraints with this procedure:
create or replace function insert_step_status_value() returns trigger as $$
	begin
		if (new.step_status != 'COMPLETE') or (new.step_status != 'INCOMPLETE')
		from phase_steps where step_type = 'RESEARCH'
		then
			raise exception 'Status value not in range for this phase step';
		end if;
		return new;
	end;
$$ language plpgsql;

create trigger check_step_status_value before update on phase_steps
for each row execute procedure insert_step_status_value();
However, an insert like update jobs.phase_steps set step_status_lu = 'INCOMPLETE' where phase_step_id = 1; gives an error: > SQL Error [P0001]: ERROR: Status value not in range for this phase step > Where: PL/pgSQL function insert_step_status_value() line 6 at RAISE Thoughts?
Rudy Stricklan (167 rep)
Aug 11, 2021, 10:43 PM • Last activity: Nov 11, 2023, 06:17 AM
9 votes
2 answers
6098 views
CHECK constraint for array column to verify length > 0
I'm playing with postgres table validation rules and trying to set a `CHECK` constraint for an array column. An idea is to allow only arrays with length > 0. Here is how I want to implement it: create table words_table ( id serial primary key, words varchar(20)[] CHECK (array_length(words, 1) > 0) )...
I'm playing with postgres table validation rules and trying to set a CHECK constraint for an array column. An idea is to allow only arrays with length > 0. Here is how I want to implement it: create table words_table ( id serial primary key, words varchar(20)[] CHECK (array_length(words, 1) > 0) ); But looks like it doesn't work. O_o insert into words_table (words) values ('{}'); //INSERT 0 1 How to implement such a constraint?
Alex Fruzenshtein (311 rep)
Aug 19, 2017, 10:57 AM • Last activity: Oct 9, 2023, 12:09 AM
0 votes
2 answers
325 views
DATE Constraint is ignored on insert
I must be missing something somewhere.. Azure SQL ``` DispatchedOn is a DateTime column ALTER TABLE [table] WITH CHECK ADD CONSTRAINT [CK_ReportDate6MonthRollGreater] CHECK ((CONVERT([date],[DispatchedOn])>='2022-12-07')) GO ALTER TABLE [table] CHECK CONSTRAINT [CK_ReportDate6MonthRollGreater] GO ``...
I must be missing something somewhere.. Azure SQL
DispatchedOn is a DateTime column

ALTER TABLE [table] WITH CHECK ADD CONSTRAINT [CK_ReportDate6MonthRollGreater] CHECK  ((CONVERT([date],[DispatchedOn])>='2022-12-07'))
GO

ALTER TABLE [table] CHECK CONSTRAINT [CK_ReportDate6MonthRollGreater]
GO
I can insert a date of 2022-12-01 enter image description here
tbasallo (187 rep)
Aug 12, 2023, 03:38 PM • Last activity: Aug 13, 2023, 10:21 AM
2 votes
1 answers
109 views
Constraint checks on multiple association tables vs. unique association table that centralizes these constraint checks
I have the following database schema (MySQL 5.7): [![Current database schema 1][1]][1] I have assistants that may be linked to either: - one customer (might evolve to multiple customers in the future, hence the association table) - one or many terminals I want to implement the constraint: an assista...
I have the following database schema (MySQL 5.7): Current database schema 1 I have assistants that may be linked to either: - one customer (might evolve to multiple customers in the future, hence the association table) - one or many terminals I want to implement the constraint: an assistant cannot simultaneously be linked to a customer and a terminal. How to implement this constraint without complex machinery? Instead of thinking about custom functions and triggers, I'm considering the following schema: New database schema The database model looks strange to me, but the association table is now unique and I can implement constraint checks more easily because they relate to a unique table. Other possibility: Alternative database schema Now my assistants are totally separated into two types in the database, with the same columns. What would be the way to go?
Merinorus (23 rep)
Aug 3, 2023, 04:23 PM • Last activity: Aug 4, 2023, 11:10 AM
0 votes
1 answers
43 views
Why constraint fails on preventing the insert statement execution?
I have the following table: ``` -- laravel.spies definition CREATE TABLE `spies` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `surname` varchar(255) NOT NULL, `agency` varchar(255) NOT NULL DEFAULT 'NO-AGENCY', `country_of_operation` varchar(255) DEFAULT NULL, `b...
I have the following table:
-- laravel.spies definition

CREATE TABLE spies (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  name varchar(255) NOT NULL,
  surname varchar(255) NOT NULL,
  agency varchar(255) NOT NULL DEFAULT 'NO-AGENCY',
  country_of_operation varchar(255) DEFAULT NULL,
  birth_date date NOT NULL,
  death_date date DEFAULT NULL,
  created_at timestamp NULL DEFAULT NULL,
  updated_at timestamp NULL DEFAULT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY unique_spy (name,surname,agency,birth_date),
) ENGINE=InnoDB AUTO_INCREMENT=2
       DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
And I inserted the following constraint as well:
ALTER TABLE spies add constraint
         death_date_valid check ( spies.death_date = NULL
           || spies.death_date > spies.birth_date );
And The following insert statement inserts a record. In my case, it should not be able to do that:
INSERT INTO spies (name,surname,birth_date,death_date)
      VALUES ('Namae','Myoji','1980-12-01','1970-12-03');
But it inserted the value instead. Do you know why? What I want to achieve it that death date will have either: * null value * any value that is greater than birth_date
Dimitrios Desyllas (873 rep)
Jul 12, 2023, 07:28 PM • Last activity: Jul 12, 2023, 08:11 PM
24 votes
1 answers
4145 views
Postgres: How is SET NOT NULL "more efficient" than CHECK constraint
In [PostgreSQL docs for Constraints](https://www.postgresql.org/docs/9.5/static/ddl-constraints.html#AEN2531), it says > A not-null constraint is functionally equivalent to creating a check constraint `CHECK (column_name IS NOT NULL)`, but in PostgreSQL creating an explicit not-null constraint is mo...
In [PostgreSQL docs for Constraints](https://www.postgresql.org/docs/9.5/static/ddl-constraints.html#AEN2531) , it says > A not-null constraint is functionally equivalent to creating a check constraint CHECK (column_name IS NOT NULL), but in PostgreSQL creating an explicit not-null constraint is more efficient. I'm wondering * What exactly does it mean by "more efficient"? * What are the detriments of using CHECK (column_name IS NOT NULL) instead of SET NOT NULL? I want to be able add a NOT VALID CHECK constraint and validate it separately (so the AccessExclusiveLock is only held for a short period of time for the adding of the constraint and then a ShareUpdateExclusiveLock is held for the longer validation step): ALTER TABLE table_name ADD CONSTRAINT column_constraint CHECK (column_name IS NOT NULL) NOT VALID; ALTER TABLE table_name VALIDATE CONSTRAINT column_constraint; Instead of: ALTER TABLE table_name ALTER COLUMN column_name SET NOT NULL;
Robin Joseph (341 rep)
Dec 18, 2016, 05:35 PM • Last activity: Apr 19, 2023, 09:36 AM
1 votes
3 answers
352 views
Alter a scalar UDF that is used in a check constraint in SQL Server 2012
I have a check constraint on a column that uses a scalar UDF. I have a requirement where I need to make changes to the UDF. Based on what I know, I need to drop the constraint, make changes to the UDF, and then re-add the constraint. During the period when the constraint is removed, I am concerned t...
I have a check constraint on a column that uses a scalar UDF. I have a requirement where I need to make changes to the UDF. Based on what I know, I need to drop the constraint, make changes to the UDF, and then re-add the constraint. During the period when the constraint is removed, I am concerned that bad data might be inserted into the table. Is there a way to alter the UDF without dropping the constraint? If not, is there a way to prevent bad data from entering the table?
RobMartin (159 rep)
Mar 2, 2023, 04:27 PM • Last activity: Mar 2, 2023, 10:34 PM
0 votes
0 answers
258 views
How to include "CHECK" constraint to backup done via phpMyAdmin?
When I export my database from phpMyAdmin (quick method), it does not include ``CHECK`` constraints. However, when I run `SHOW CREATE TABLE table`, I see the constraints. Moreover, foreign constraints are backed up. In addition, when I take the backup using mysqldump, `CHECK` constraints are include...
When I export my database from phpMyAdmin (quick method), it does not include `CHECK constraints. However, when I run SHOW CREATE TABLE table`, I see the constraints. Moreover, foreign constraints are backed up. In addition, when I take the backup using mysqldump, CHECK constraints are included in the file. **Is there any way to tell phpMyAdmin to include the CHECK constraints in the backup?** I have checked the "custom" method, but I do not see any option.
xerez (1 rep)
Jan 9, 2023, 07:52 PM
8 votes
1 answers
997 views
Why won't this UDF work in this check constraint?
I’m trying to use a UDF as an alternative to using a SELECT command within a check constraint. I need to put a constraint on the report table to ensure the signedBy field is the PK of a personnel record for which there exists a record in the auth table with their personnel number and the authType of...
I’m trying to use a UDF as an alternative to using a SELECT command within a check constraint. I need to put a constraint on the report table to ensure the signedBy field is the PK of a personnel record for which there exists a record in the auth table with their personnel number and the authType of 8 (which would indicate they are authorized to sign reports). My UDF should check for the existence of such a auth record and return a bit (0 if it does not exist, 1 if it does). I'm working on SQL Server Express Edition. I've pretty much re-created my situation at SQLFiddle :
CREATE TABLE personnel(
	personnel INT IDENTITY(1, 1) NOT NULL,
	firstName VARCHAR(20), 
	lastName VARCHAR(20),
	login VARCHAR(20) DEFAULT NULL,
	title varchar(20) DEFAULT NULL,
	initials varchar(4) NOT NULL,
	startDate DATE DEFAULT GETDATE(),
	CONSTRAINT PkPersonnel PRIMARY KEY(personnel),
	CONSTRAINT UqPersonnelFirstNameLastName UNIQUE(firstName, lastName),
	CONSTRAINT UqPersonnelInitials UNIQUE(initials)
);
CREATE TABLE authType(
authType INT NOT NULL IDENTITY(1, 1),
authName varchar(50)
CONSTRAINT PkAuthTypeAuthType PRIMARY KEY(authType)
);
CREATE TABLE auth(
auth INT NOT NULL IDENTITY(1, 1),
personnel INT NOT NULL,
authtype INT NOT NULL,
date date DEFAULT GETDATE()
CONSTRAINT PkAuthAuth PRIMARY KEY(auth)
CONSTRAINT FkAuthAuthType FOREIGN KEY(authtype) REFERENCES authtype(authtype)
);
CREATE FUNCTION checkIfAuthorized (@personnel INTEGER, @authType INTEGER)
RETURNS Bit
AS
BEGIN
    Return Case 
        When Exists (Select 1 FROM auth
                     Where personnel = @personnel AND authtype = @authtype)
            Then 1 Else 0
        End
END
GO
CREATE TABLE report(
	report INTEGER NOT NULL IDENTITY(1, 1),
	iteminJob INTEGER NOT NULL,
	reportDate DATE NOT NULL,
	notes VARCHAR(200),
	signedBy INTEGER NOT NULL,
	reviewedBy INTEGER,
	conformance VARCHAR(30)
	CONSTRAINT PkReport PRIMARY KEY(report),
	CONSTRAINT [Reports must be associated with an item in a job.] FOREIGN KEY(iteminJob) REFERENCES iteminjob(iteminJob),
	CONSTRAINT [Must be signed by an authorized signatory.] CHECK(metrologyTesting.dbo.checkIfAuthorized(signedBy, 8))
);
Whenever creating my report table on SQL Server Express, the error message is: > 'checkIfAuthorized' is not a recognized built-in function name. even though in SSMS's Object Explorer, it's clearly there under [MyDatabase]>Programmability>Functions>Scalar-valued Functions The results on SQLFiddle: > An expression of non-boolean type specified in a context where a > condition is expected, near ')'. ...are even more perplexing to me. The UDF is set up to return a bit. Please refrain from recommending I use triggers instead.
agerber85 (121 rep)
Nov 30, 2022, 08:33 PM • Last activity: Dec 1, 2022, 04:47 PM
0 votes
1 answers
36 views
Ensure value is in list when inserting / updating
is it possible to ensure that a value is in a list of values defined in another table? For instance by using a check constraint? I was thinking about a construct like this: CREATE OR REPLACE TABLE `possible_value` ( id_possible_value INTEGER PRIMARY KEY NOT NULL , concerning_table VARCHAR(50) , conc...
is it possible to ensure that a value is in a list of values defined in another table? For instance by using a check constraint? I was thinking about a construct like this: CREATE OR REPLACE TABLE possible_value ( id_possible_value INTEGER PRIMARY KEY NOT NULL , concerning_table VARCHAR(50) , concerning_column VARCHAR(50) , value VARCHAR(100) ); CREATE OR REPLACE TABLE event ( id_event INTEGER PRIMARY KEY NOT NULL , id_foreign INTEGER NOT NULL , concerning_table VARCHAR(50) , name VARCHAR(50) , class VARCHAR(20) , CONSTRAINT class_is_possible CHECK( class IN ( SELECT value FROM possible_value WHERE concerning_table = 'event' AND concerning_column = 'class' ) ) ); But I think a check constraint cannot access information from another table. Thanks in advance Markus
Markus (101 rep)
Oct 15, 2022, 08:46 PM • Last activity: Oct 16, 2022, 05:54 PM
Showing page 1 of 20 total questions