SQL constraint “at least one of two attributes” - sql

I need to create a table User with telephone_number and e_mail_adress columns. Each row must have at least one of those columns set. It could have both or just one, but it must have at least one of them.
How can I express that constraint in SQL?

create table Users (
/* Whatever */
TelephoneNumber varchar(2000) null,
EmailAddress varchar(5) null,
constraint CK_AtLeastOneContact CHECK (
TelephoneNumber is not null or
EmailAddress is not null
)
)
You may want to adjust the data types :-)

Related

How to make the default selection of a value in sql out of multiple choices?

I have a column in my SQL table i.e. Gender and there can be one of two possible values for it, 'M' and 'F'.
For those values, I am able to pass two values by using a check constraint as option when creating the table:
Gender varchar(6) CHECK (Gender IN ('M', 'F'))
Also, one of those value is defined as the default:
Gender varchar(6) DEFAULT 'M'
But here, if I am trying to merge those two queries while table creation, I am not getting the output. I want to pass two choices for column value and default as 'M'.
Both can be used as part of the create table syntax:
create table t(gender char(1) default('M') check(gender in ('M','F')));
Demo Fiddle
You can easily use both in the CREATE TABLE statement - and preferably, define explicit names for your constraints!
CREATE TABLE Person
(
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Gender CHAR(1) NOT NULL
CONSTRAINT CHK_Person_Gender CHECK (Gender IN ('M', 'F'))
CONSTRAINT DF_Person_Gender DEFAULT ('M')
)

How do I create a IF statement creating a table in Postgres?

I'm creating a table and I need a check constraint to validate the posibles values given a string value. I'm creating this table:
CREATE TABLE cat_accident (
acc_type VARCHAR(30) NOT NULL CHECK(acc_type = 'Home accident' OR acc_type = 'Work accident'),
acc_descrip VARCHAR(30) NOT NULL
);
So basically I want to validate if acc_type is equal to Home accident, then acc_descrip can be or 'Intoxication' OR 'burns' OR 'Kitchen wound', OR if acc_type is equal to Work Accident, then acc_descrip can be OR 'freezing' OR 'electrocution'.
How do I write that constraint?
Use a CHECK constraint with a CASE expression:
CREATE TABLE cat_accident (
acc_type VARCHAR(30) NOT NULL,
acc_descrip VARCHAR(30) NOT NULL
CHECK(
CASE acc_type
WHEN 'Home accident' THEN acc_descrip IN ('Intoxication', 'burns', 'Kitchen wound')
WHEN 'Work accident' THEN acc_descrip IN ('freezing', 'electrocution')
END
)
);
See the demo.
I'd suggest implementing this with a lookup table:
CREATE TABLE l_accident_description(
description_id VARCHAR(5) PRIMARY KEY,
description_full VARCHAR(30) NOT NULL UNIQUE,
location VARCHAR(30)
);
INSERT INTO l_accident_description
(description_id,description_full,location)
VALUES
('INTOX','Intoxication','Home Accident'),
('BURNS','Burns','Home Accident'),
('K_WND','Kitchen wound','Home Accident'),
('FREEZ','Freezing','Work Accident'),
('ELECT','Electrocution','Work Accident');
That way you can encode the relationship you want to encode into cat_accident, but if the details ever change, it's only a matter of inserting/deleting/updating rows in your lookup table. This implementation has the added benefit that you're not storing as much data repetitively in your table (just a VARCHAR(5) code rather than a VARCHAR(30) string). The table construction then becomes (with added primary key):
CREATE TABLE cat_accident (
cat_accident_id PRIMARY KEY,
acc_descrip VARCHAR(5) NOT NULL REFERENCES l_accident_description(description_id)
);
Any time you wanted to know whether the accident Home/Work, this could be accomplished with a query joining the lookup table. Joining lookup tables is more in the spirit of good database construction, rather than hard-coding checks to tables that may easily change or grow more complex as the database grows.
In fact, the ideal solution might be to create two lookup tables here, with l_accident_description in turn referencing a location lookup, but for simplicity's sake I've shown how it might be accomplished with one.

I am trying to VIEW 4 columns from 2 different tables I have already created in Oracle Live SQL

I want to use the VIEW command to display these 4 columns in one single schema. I have tried making a single VIEW with the first 3 columns, because they are from the the same table. Adding the one other column is where I'm struggling. I have tried the ALTER function but a VIEW schema doesn't seem to have the same edit privileges as a table would. I hope that makes sense.
create table PATIENTINFO (
PatientID number not null,
FirstName varchar2(50) not null,
LastName varchar2(50) not null,
Address varchar2(50),
City varchar2(50),
State varchar2(50),
ZipCode number(5),
Phone number(10) not null ,
Email varchar2(50),
MemberID number not null,
constraint pk_departments primary key (PatientID)
)
create table LABORDER (
LabOrderNumber number not null,
OrDate date not null,
ReqBloodTest varchar2(15) not null,
Reason varchar(50),
PatientID number not null,
constraint pk_laborder primary key (LabOrderNumber),
constraint fk_laborder_patientid foreign key (PatientID)
references PATIENTINFO (PatientID)
)
CREATE VIEW PatientBlood AS
SELECT FirstName, LastName, PatientID
FROM PATIENTINFO
Write the query you want and then create a view out of it. I started by writing the query below and then prefixed it with CREATE OR REPLACE VIEW. The example below has some randomly selected columns, change it to whatever columns you need. I chose to name my columns in the view definition, you can omit that but also do a million other things as stated in the docs
Side note: don't use mixed case for identifiers like column names/table names. It is confusing. In your case it didn't matter since you didn't use quotes, so they're case insensitive and the view below will work even though the identifiers are all lower case.
CREATE OR REPLACE VIEW laborder_v (
labordernumber,
patientid,
lastname
) AS
SELECT o.labordernumber,
p.patientid,
p.lastname
FROM laborder o
JOIN patientinfo p ON o.patientid = p.patientid;

How to prevent a input of certain letters using Oracle

The code is the category of the video, it is represented by one upper case character, excluding I, O,
Q, V, Y and Z, followed by a numeric character.
So far, I took a guess and got this. Any suggestions on how to fix it?
create table channelTable (
channelID number NOT NULL,
ChannelName varchar(100) NOT NULL,
ChannelDate date NOT NULL,
UserName varchar(100) NOT NULL UNIQUE,
TopicCode varchar(4) NOT NULL);
CONSTRAINT channelID_pk PRIMARY KEY (channelID)
CONSTRAINT c_topicCode LIKE '[A-Za-z][0-9] NOT (I,O,Q,N,Y,Z)
);
Some comments:
NOT NULL is not needed for PRIMARY KEY columns.
In Oracle, use VARCHAR2().
Then, I would suggests regular expressions. If the value is supposed to be exactly two characters, then declare it as such:
create table channelTable (
channelID number,
ChannelName varchar(100) NOT NULL,
ChannelDate date NOT NULL,
UserName varchar2(100) NOT NULL UNIQUE,
TopicCode char(2) NOT NULL;
CONSTRAINT channelID_pk PRIMARY KEY (channelID)
CONSTRAINT check (REGEXP_LIKE(c_topicCode, '^[A-HJ-NPR-UYZ][0-9]$')
);
Or perhaps more simply:
CONSTRAINT REGEXP_LIKE(c_topicCode, '^[A-Z][0-9]$') AND NOT REGEXP_LIKE(c_topicCode, '^[IOQNYZ]'))
All that said, I would rather see a table of TopicCodes that is populated with the correct values. Then you can just use a foreign key relationship to define the appropriate codes.
Use the regular expression ^[A-HJ-MPR-X]\d$ to match an upper-case character excluding I,O,Q,N,Y,Z followed by a digit:
CREATE TABLE channels (
id number CONSTRAINT channel__id__pk PRIMARY KEY,
Name varchar(100) CONSTRAINT channel__name__nn NOT NULL,
DateTime date CONSTRAINT channel__date__nn NOT NULL,
UserName varchar(100) CONSTRAINT channel__username__NN NOT NULL
CONSTRAINT channel__username__U UNIQUE,
TopicCode varchar(4),
CONSTRAINT channel__topiccode__chk CHECK ( REGEXP_LIKE( topiccode, '^[A-HJ-MPR-X]\d$' ) )
);
db<>fiddle
Also, you don't need to call the table channeltable just call it channels and you don't need to prefix the column names with the table name and you can name all the constraints (rather than relying on system generated constraint names which makes it much harder to track down issues when you are debugging).
Consider the following check constrait:
create table channelTable (
...
topicCode varchar(4) not null
check(
substr(c_topicCode, 1, 1) not in ('I', 'O', 'Q', 'V', 'Y', 'Z')
and regexp_like(topicCode, '^[A-Z]\d')
),
...
);
The first condition ensures that the code does not start with one of the forbidden characters, the second valides that it stats with an upper alphabetic character, followed by a number.
To avoid using two conditions, an alternative would be to list all allowed characters in the first position:
check(regexp_like(topicCode, '^[ABCDEFGHJKLMNPRSTUVWX]\d'))
This works in Oracle, and in very recent versions of MySQL.

SQL Server 2014 : help creating tables

I am new to MSSQL 2014 Server, my professor listed these steps to make a table, I don't know the proper steps to create tables in the pictures listed below, please help.
Create and populate (insert values) the following tables per table description and data values provided
DEPARTMENT
EMPLOYEE
PROJECT
ASSIGNMENT
Add a SQL Comment to include /* * Your First Name_Your Last Name* */ when inserting corresponding values for each table.
What I tried so far:
CREATE TABLE DEPARTMENT(
DepartmentName Text(35) PRIMARY KEY,
BudgetCode Text(30) NOT NULL,
OfficeNumber Text(15) NOT NULL,
Phone Text(12) NOT NULL, );
I have put this to my query and the error is
Msg 2716, Level 16, State 1, Line 1 Column, parameter, or variable #1: Cannot specify a column width on data type text.
Try this(I assume that your table exists in dbo schema):
IF OBJECT_ID(N'dbo.DEPARTMENT', N'U') IS NOT NULL
BEGIN
DROP TABLE DEPARTMENT
END
GO
CREATE TABLE DEPARTMENT(
DepartmentName varchar(35) PRIMARY KEY,
BudgetCode varchar(30) NOT NULL,
OfficeNumber varchar(15) NOT NULL,
Phone varchar(12) NOT NULL
);
You can not define width for Text data type. In case which you need to define width you can use char or varchar data types. Also keep in mind that if you need to work with Unicode characters then you will need to use nchar or nvarchar instead.