How to ALTER TABLE to add CHECK constraint? - sql

I want to ALTER my already created ZIPCODE table so that the sales_tax_applied field can never have a negative value. Here is the code for my already created table:
CREATE TABLE ZIPCODE
(
city VARCHAR(50) NOT NULL,
state CHAR(2) NOT NULL,
zipcode VARCHAR(20) NOT NULL,
sales_tax_applied DECIMAL(10,4) NOT NULL,
PRIMARY KEY (zipcode)
);
What is the code for me to be able to do this? NOTE: all fields must be NOT NULL.
Thank you

You would do:
alter table zipcode add constraint chk_zipcode_sales_tax_applied
check (sales_tax_applied >= 0);
You can also add this into the create table statement in multiple ways, such as:
CREATE TABLE ZIPCODE (
city VARCHAR(50) NOT NULL,
state CHAR(2) NOT NULL,
zipcode VARCHAR(20) NOT NULL,
sales_tax_applied DECIMAL(10,4) NOT NULL,
PRIMARY KEY (zipcode),
constraint chk_zipcode_sales_tax_applied check (sales_tax_applied >= 0)
);

Related

Make a column required if other column is of certain value

What I have:
CREATE TABLE [dbo].[User]
(
[id] INT NOT NULL PRIMARY KEY,
[name] VARCHAR(50) NOT NULL,
[postcode] INT NOT NULL,
[phone] INT NULL
)
What I want is that the phone number is required ONLY if the postcode is higher than 40000. If postcode is smaller than 40000, user can insert the phone number, although it is not required.
How do I do this?
You can use a check constraint:
CREATE TABLE [dbo].[User]
(
[id] INT NOT NULL PRIMARY KEY,
[name] VARCHAR(50) NOT NULL,
[postcode] INT NOT NULL,
[phone] INT NULL,
CONSTRAINT CHK_Postcode CHECK (postcode >= 4000 OR Phone IS NOT NULL)
);
This needs to be handled from the front end inserting values into the Database. Insert Query on one column based on another in the DB for the same table is not possible.

How to make (patient id) forgein key in table of bill?

I try to create three tables by using website suport compiler any code but I have a problem in the table of the bill.
When I run it I get to error show me it is near in foreign key
These are codes of three tables
CREATE TABLE patient (
Patient Id (5) Primary key,
Name Varchar (20) Not null ,
Age Int Not null ,
Weight Int Not null ,
Gender Varchar (10) Not null,
Address Varchar (50) Not null ,
Disease Varchar (20) Not null
);
CREATE TABLE doctors (
DoctorId Varchar (5) Primary key,
Doctorname Varchar (15) Not null,
Dept Varchar (15) Not null
);
CREATE TABLE bill (
Bill_no Varchar (50) Primary key,
Patient_Id Varchar (5) Foreign key,,
doctor_charge Int Not null,
patient_type Varchar (10) null,
no_of_days Int null,
lab_charge Int null,
bill Int Not null
);
Patient Table
CREATE TABLE patient
(
patient_id VARCHAR (5) PRIMARY KEY,
name VARCHAR (20) NOT NULL,
age INT NOT NULL,
weight INT NOT NULL,
gender VARCHAR (10) NOT NULL,
address VARCHAR (50) NOT NULL,
disease VARCHAR (20) NOT NULL
);
Errors
No data type has been assigned in Patient id column (Patient Id (5)
Primary key)
Patient id column name contains spaces. You need to
enclose the column name in double quotes or replace space with something else
(ex: _). It's not recommended to use spaces.
A column name with space
CREATE TABLE tablename ("column name" datatype);
Doctors Table
CREATE TABLE doctors
(
doctorid VARCHAR (5) PRIMARY KEY,
doctorname VARCHAR (15) NOT NULL,
dept VARCHAR (15) NOT NULL
);
Bill Table
CREATE TABLE bill
(
bill_no VARCHAR (50) PRIMARY KEY,
patient_id VARCHAR (5),
doctor_charge INT NOT NULL,
patient_type VARCHAR (10) NULL,
no_of_days INT NULL,
lab_charge INT NULL,
bill INT NOT NULL,
FOREIGN KEY (patient_id) REFERENCES patient(patient_id)
);
Errors
The way you have assigned foreign key is wrong. Please refer this and this article for more information. (Patient_Id Varchar (5) Foreign key,,)
There are two commans in the Patient_Id column (Patient_Id Varchar (5) Foreign key,,)
You have to provide reference of the table for which you want to use the reference key.
For example, you have table Persons which has Primary key PersonID, in that case if you want to use that as foreign key in another table, lets say Orders.
In Oracle
CREATE TABLE Orders (
OrderID numeric(10) not null,
OrderNumber numeric(10) not null,
PersonID numeric(10) not null,
CONSTRAINT fk_person_id
FOREIGN KEY (PersonID )
REFERENCES Persons(PersonID )
Your Case :
CREATE TABLE bill
( Bill_no Varchar (50) Primary key,
Patient_Id Varchar (5),
doctor_charge Int Not null,
patient_type Varchar (10) null,
no_of_days Int null,
lab_charge Int null,
bill Int Not null,
CONSTRAINT fk_patient_id
FOREIGN KEY (Patient_Id)
REFERENCES patient(Patient_Id)
);
Remove the 'Foreign Key' from the table creation script.
Add this to your SQL script:
ALTER TABLE [Bill] WITH CHECK ADD CONSTRAINT [FK_Bill_Patient] FOREIGN KEY([Patient_Id])
REFERENCES [Patient] ([Patient_Id])
GO
ALTER TABLE [Bill] CHECK CONSTRAINT [FK_Bill_Patient]
GO
The words FOREIGN KEY are only needed for introducing the name of the FK constraint. Since your other constraints are not named, you might as well skip that part and go straight to REFERENCES.
If you specify a foreign key constraint as part of the column definition, you can omit the datatype to allow it to inherit from its parent at the time of creation, which I think is good practice as the types will automatically match.
We use VARCHAR2 in Oracle, not VARCHAR.
You don't need to specify NULL for columns that are allowed to be null.
I am not sure a 5-character string is a good datatype for a unique ID. How will you generate the values? Normally an auto-incrementing sequence number simplifies this.
create table doctors
( doctorid varchar2(5) primary key
, doctorname varchar2(15) not null
, dept varchar2(15) not null );
create table patients
( patient_id varchar2(5) primary key
, name varchar2(20) not null
, age integer not null
, weight integer not null
, gender varchar2(10) not null
, address varchar2(50) not null
, disease varchar2(20) not null );
create table bills
( bill_no varchar2(50) primary key
, patient_id references patients -- Allow datatype to inherit from parent
, patient_type varchar2(10)
, no_of_days integer
, lab_charge integer
, bill integer not null );

how to avoid empty entries in sql?

CREATE TABLE emp3(
id int(3) auto_increment,
first_name varchar(30) NOT NULL,
last_name varchar(30),
email varchar(20) not null unique,
PRIMARY KEY (id)
)
This is my table.
if i insert query like this insert into emp3 values(3,' ','',''); it is getting stored in the table.
but i should avoid this.How can i do it?
You can add constraints according to your needs:
CREATE TABLE emp3(
id int(3) auto_increment,
first_name varchar(30) NOT NULL,
last_name varchar(30),
email varchar(20) not null unique,
PRIMARY KEY (id)
);
ALTER TABLE emp3
ADD CONSTRAINT check_name_not_blank CHECK ((first_name<>'')),
ADD CONSTRAINT check_email_not_blank CHECK ((email<>''))
you yould avoid empty strings in your columns with a constraint like
ALTER TABLE emp3 WITH CHECK
ADD CONSTRAINT [CK_emp3] CHECK
(
([first_name]<>'') AND
([last_name]<>'') AND
([email ]<>'')
)
you can do this just by setting them as Not Null
CREATE TABLE emp3(
id int(3) auto_increment,
first_name varchar(30) NOT NULL,
last_name varchar(30),
email varchar(20) not null unique,
PRIMARY KEY (id)
)

postgresql syntax error when creating a table

Hey everyone I need some help with creating tables. I have the script below and it creates a few tables. When i try to run the script it give me this error:
psql:script.sql:10: ERROR: syntax error at or near "Group"
LINE 6: CREATE TABLE Group(
Can anyone tell me what is going on?
CREATE TABLE Group(
name varchar(40) PRIMARY KEY NOT NULL
);
CREATE TABLE Artist(
name varchar(30) PRIMARY KEY NOT NULL,
birthplace varchar(20) NOT NULL,
age int NOT NULL CHECK (age > 0),
style varchar(20) NOT NULL
);
CREATE TABLE Artwork(
title varchar(40) PRIMARY KEY NOT NULL,
artist varchar(30) NOT NULL references Artist(name),
group_name varchar(40) NOT NULL references Group(name),
year int NOT NULL CHECK (year > 0),
type varchar(30) NOT NULL,
price money NOT NULL,
);
CREATE TABLE Customer(
cust_id int PRIMARY KEY NOT NULL,
name varchar(40) NOT NULL,
address varcahr(60) NOT NULL,
amount money NOT NULL CHECK(amount > 0),
like_artist varchar(30) NOT NULL references Artist(name),
like_group varchar(40) NOT NULL references Group(name)
);
it had a lot of problems
this worked for me. In postgres, names that are not all lowercase need to be double quoted. also some of your table names are reserved words, money can't be > and int, and there was a comma out of place.
CREATE TABLE "group"( name varchar(40) PRIMARY KEY NOT NULL );
CREATE TABLE artist( name varchar(30) PRIMARY KEY NOT NULL, birthplace varchar(20) NOT NULL, age int NOT NULL CHECK (age > 0), style varchar(20) NOT NULL );
CREATE TABLE artwork( title varchar(40) PRIMARY KEY NOT NULL, artist varchar(30) NOT NULL references artist(name),
group_name varchar(40) NOT NULL references "group"(name), year int NOT NULL CHECK (year > 0), type varchar(30) NOT NULL, price money NOT NULL );
CREATE TABLE customer( cust_id int PRIMARY KEY NOT NULL, name varchar(40) NOT NULL, address varchar(60) NOT NULL,
amount money NOT NULL CHECK(amount > cast(0.0 as money)), like_artist varchar(30) NOT NULL references artist(name), like_group varchar(40) NOT NULL references "group"(name) );

i used the program SQL Fiddle and it keeps telling me that the table doesn't exist,what can i do to fix the two tables referencing each other?

the Staff table references the branch table
CREATE TABLE Staff(
StaffNo VARCHAR(5) NOT NULL,
firstName VARCHAR(15) NOT NULL UNIQUE,
lastName VARCHAR(15) NOT NULL,
position VARCHAR(10) NOT NULL,
salary INTEGER
DEFAULT 3000,
CHECK (salary BETWEEN 3000 AND 25000),
email VARCHAR(25),
branchNo CHAR(6) NOT NULL,
PRIMARY KEY (StaffNo),
FOREIGN KEY (branchNo) REFERENCES Branch (branchNo));
and at the same time the branch table references the Staff table
create table Branch(
branchNo char(6) not null primary key,
street varchar(30) not null,
city varchar(20),
postCode char(5) not null,
ManagerNo varchar(5) not null,
foreign key (ManagerNo) references Staff(StaffNo));
Since your tables reference each other in the Foreign Keys you will get an error on either table creation if the other table has not been created yet. I would suggest that you remove the creation of the FOREIGN KEYs to separate ALTER TABLE statements:
CREATE TABLE Staff(
StaffNo VARCHAR(5) NOT NULL,
firstName VARCHAR(15) NOT NULL UNIQUE,
lastName VARCHAR(15) NOT NULL,
position VARCHAR(10) NOT NULL,
salary INTEGER
DEFAULT 3000,
CHECK (salary BETWEEN 3000 AND 25000),
email VARCHAR(25),
branchNo CHAR(6) NOT NULL,
PRIMARY KEY (StaffNo)
);
create table Branch(
branchNo char(6) not null primary key,
street varchar(30) not null,
city varchar(20),
postCode char(5) not null,
ManagerNo varchar(5) not null
);
alter table staff
add constraint fk1_branchNo foreign key (branchNo) references Branch (branchNo);
alter table branch
add constraint fk1_ManagerNo foreign key (ManagerNo) references Staff (StaffNo);
See SQL Fiddle with Demo
You can remove one reference from one table and keep the other.then you can retrieve data using the remainig reference.Is there any problem with that?