Why do I receive error 1241 when trying to Create and Insert data into a new table (on phpMyAdmin)? - sql

I am trying to create a new table and insert values into it however I keep receiving "#1241 - Operand should contain 1 column(s)".
Please could someone help to identify what is wrong with my code as I am unsure what this error is referencing?
The code I am inserting into the phpMyAdmin database under the SQL tab. I have tried to remove the auto increment attributes and have tried looking at other examples to check my syntax, but I can't spot the issue. Some guidance on this would be greatly appreciated.
The code I entered begins like this:
# AppSoft Project - Greg Roberts
DROP table if exists Department;
DROP table if exists Role;
DROP table if exists User;
DROP table if exists Appraisal;
DROP table if exists Question;
DROP table if exists Answer;
CREATE table Department(
DeptID int NOT NULL AUTO_INCREMENT,
DeptName varchar(30) NOT NULL,
primary key (DeptID));
INSERT into Department values(
(00, 'SuperAdmin'),
(01, 'Support Staff'),
(02, 'Teaching Staff'),
(03, 'SLT'));
CREATE table Role(
RoleID int NOT NULL AUTO_INCREMENT,
RoleTitle varchar(30) NOT NULL,
primary key (RoleID));
INSERT into Role values(
(00, 'SuperAdmin'),
(01, 'Office Administrator'),
(02, 'Teaching Partner'),
(03, 'Mid Day Supervisor'),
(04, 'Cooks'),
(05, 'Cleaners'),
(06, 'Maintenance'),
(07, 'Teacher'),
(08, 'Department Head'),
(09, 'SENCO'),
(10, 'Head Teacher'),
(11, 'Executive Head'));
Error Code that Occurs

You dont need to insert primary keys, if they are set to auto_increment.
DeptID int NOT NULL AUTO_INCREMENT
Just insert the department name, there are no additional braces required for Values.
INSERT into Department( DeptName) values
('SuperAdmin'),
('Support Staff'),
('Teaching Staff'),
('SLT');
You would need to do the same for Role table as well.
Also if you try to insert 0 into the primary key, it will actually insert 1 you can read about it in the Standard Docs
you seem to be getting the error because your first record inserts 1 into the table and then your second record tries to insert 1 again in the primary key column

Related

How to fix an SQL design

I'm doing the study of a medical software. This software asks the patients questions about their symptoms and from them it can determine the possible pathologies. My study involves comparing the symptoms and pathologies found by the software with those from the hospital.
In order to make my work easier, I decided to enter the data in a database made with javadb on netbeans 8.2.
But it seems like that I did something wrong since my statement doesn't work.
I thank you in advance anybody who would take the time to help me.
SQL design:
Create table Patients(
nip varchar(32) primary key,
sexe varchar(8) not null,
age int not null,
dateArrivee timestamp not null,
constraint ck_sexe check(sexe='Male' or sexe='Female'),
constraint ck_age check (age>=0)
);
Create table Symptoms(
symptomID int primary key generated always as identity (start with 1,
increment by 1),
nip varchar(32) not null,
symptom varchar(64),
origin varchar(16) not null,
foreign key (nip) references Patients(nip),
constraint ck_origin check (origin='SOFTWARE' or origin='HOSPITAL')
);
Create table Pathologies(
pathologyID int primary key generated always as identity (start with 1,
increment by 1),
nip varchar(32) not null,
pathology varchar(64),
origin varchar(16) not null,
foreign key (nip) references Patients(nip),
constraint ck_origin check (origin='SOFTWARE' or origin='HOSPITAL')
);
Values entered:
Insert into Patients values ('001','Male', 25, '2019-05-27 14:00:00');
Insert into Patients values ('002', 'Female', 30, '2019-05-26 15:00:00');
Insert into Symptoms values (, '001', 'Headache', 'SOFTWARE');
Insert into Pathologies values (,'001', 'Fever', 'SOFTWARE');
Insert into Symptoms values (,'001', 'Stomache', 'HOSTPITAL');
Insert into Pathologies values (, '001', 'Gastro-enteritis', 'HOSPITAL');
Insert into Symptoms values(,'002', 'Headache', 'SOFTWARE');
Insert into Pathologies values (,'002', 'Unknow', 'SOFTWARE');
SQL statement:
Select *
from (Patients inner join
Symptoms
on Patients.nip = Symptoms.nip
) inner join
Pathologies
on Symptoms.nip = Pathologies.nip
where Symptoms.origin = 'MEDVIR' and
Pathologies.origin = 'MEDVIR';
So sorry I forgot to put the errors I'm getting.
SQL design:
First I have an error concerning the auto_incrementation, even thought this was the good method. It says that the syntax is incorrect near the 'generated'.
Values entered:
Here I have an error concerning the a wrong syntax near the coma (',').
SQL statement:
Lastly I have an error saying that the object 'Patients' is unavaible.
If I am not wrong, you are trying to fetch entries where 'Origin' = 'MEDVIR'
Although, none of your insert statements have Origin as 'MEDVIR'
Please check below,
Select *
from (Patients inner join
Symptoms
on Patients.nip = Symptoms.nip
) inner join
Pathologies
on Symptoms.nip = Pathologies.nip
where Symptoms.origin IN ('SOFTWARE', 'HOSPITAL') and
Pathologies.origin IN ('SOFTWARE', 'HOSPITAL');
Also, some of your INSERT statement has an extra comma before the values, which would cause a syntax error.

PostgreSQL table does not exist

drop table Employee;
CREATE TABLE Employee
( EmployeeID integer,
FirstName varchar(24),
LastName varchar(24),
Email varchar(48),
PhoneNumber varchar(12),
HotelID integer
PRIMARY KEY (EmployeeID),
);
INSERT INTO Employee VALUES (1, ‘James’, ‘Jenkins’, ‘jj#gmail.com’, ’0412181111’, 1);
INSERT INTO Employee VALUES (22, ‘Roy’, ‘Bond’, ‘jb#gmail.com’, ‘0418246192’, 1);
INSERT INTO Employee VALUES (14, ‘Rachel’, ‘Green’, ‘rg#gmail.com’, ‘0468129367’, 1);
INSERT INTO Employee VALUES (96, ‘Eddard’, ‘Stark’, ‘es#gmail.com’, ‘0458192716’, 1);
INSERT INTO Employee VALUES (77, ‘Anna’, ‘Nguyen’, ‘an#gmail.com’ , ‘0418238694’, 1);
Error: "psql:employee:1: ERROR: table "employee" does not exist"
What is the way that the error can be fixed?
Link to the entire doc if anyone wants to take a look: https://docs.google.com/document/d/1r4E7yz4XJxLmO3rmkH4YBVOGfYN5PkhcDSJUyuy7qxw/edit?usp=sharing
Your create statement has a comma(,) missing before declaring the primary key. Therefore the table is not getting created. This this:
CREATE TABLE Employee
( EmployeeID integer,
FirstName varchar(24),
LastName varchar(24),
Email varchar(48),
PhoneNumber varchar(12),
HotelID integer,
PRIMARY KEY (EmployeeID),
FOREIGN KEY (HotelID) REFERENCES Hotel
);
The table Employee might not be already created in your database when you are trying to run above snippet. Always have an IF EXISTS check before dropping a table or stored procedure or function.
Your drop query should be.
drop table if exists `Employee`;

How to insert value into foreign key in SQL server? (Avoid the duplicate key.)

I create two table. They connected by primary key and foreign key. When I insert new values, it said cannot insert duplicate key in object. Here are my tables
create table person (
sinNum int primary key not null,
gender varchar(6) not null check (gender in ('male','female')) default 'female',
age int not null check (age>=18 and age<=100),
emailAddr varchar (50) not null,
phoneNum int not null,
)
create table employee (
empId int identity (1,1) unique,
lastName varchar (30) not null,
firstName varchar (30) not null,
sinNum int unique foreign key references person (sinNum),
departmentId int foreign key references department (departmentId),
position varchar (20) not null check (position in ('clerk','assistant','supervisor','manager','director','president')) default'clerk',
baseSalary float not null
)
Here are my insert statements
insert into person (sinNum,gender,age,emailAddr, phoneNum) values (333,
'female', 24, 'dds', 2121)
insert into employee(lastName,firstName, sinNum, departmentId,
position,baseSalary) values ('Snow','John',333,20,'clerk',4000)
Here are the error messages
Violation of PRIMARY KEY constraint 'PK__person__228E26BE3A9512B2'.
Cannot insert duplicate key in object 'dbo.person'. The duplicate key
value is (333).
Can anyone show me the way please? Many thanks
You have not set sinNum as identity. Make it auto incremented and then change your insert query as below.
insert into person (sinNum,gender,age,emailAddr, phoneNum) values ((SELECT ISNULL(MAX(sinNum)+1,0) FROM person WITH(SERIALIZABLE, UPDLOCK)),
'female', 24, 'dds', 2121)
You can use simpler version also, but it doesn't guarantee concurrency:
insert into person (sinNum,gender,age,emailAddr, phoneNum) values (NULL,
'female', 24, 'dds', 2121)
Since sinNum is your primary key, if you try to INSERT a new row containing the same value it will reject you.
Just use the following query to delete the rows before adding it again.
DELETE FROM person WHERE sinNum = 333;
You can also update/merge the row or simply not add it, since you have done it already.
As the column 'sinum' is primary key, you can't define it explicitly.
So please have a try with below.
Insert into person (gender,age,emailAddr, phoneNum) values ( 'female', 24, 'dds', 2121)
Declare #sinnum=IDENT_CURRENT('Person')
If ##error=0
Insert into employee(lastName,firstName, sinnum, departmentId, position,baseSalary) values ('Snow','John',#sinnum,20,'clerk',4000)
Ident_current will save the last inserted primary key value in the mentioned table. Saving that value in a temporary variable, inorder to use the same value as FK in the employee table.
##error used here to ensure insert on employee table only on successful insert made in person table.
What's happening here is that your insert on Person table is violating the primary key constraint. So we can use this exception as an antidote.
You can make use of Try-Catch statement and can implement your further logic in the catch block.
/* You an use #output parameter too */
Declare #output bit=1
BEGIN TRY
insert into person (sinNum,gender,age,emailAddr, phoneNum) values (333,
'female', 24, 'dds', 2121)
insert into employee(lastName,firstName, sinNum, departmentId,
position,baseSalary) values ('Snow','John',333,20,'clerk',4000)
print 'Record inserted in both table'
set #output=1
END TRY
BEGIN CATCH
if error_message() like 'Violation of PRIMARY KEY constraint%'
Begin
/* Do whatever you like to do here */
/* You can delete the existing record if you want */
print 'Record already exists is Person table' --just the intimation
set #output=0
End
else
print 'other exception' --just the intimation
END CATCH
You can delete the existing record in catch block or can make new transaction using #output variable.. Hope it works for you.

SQL auto-validating data when adding it to row

My SQL code is as follows:
CREATE TABLE personsdb
(personID int IDENTITY(1,1) NOT NULL,
personName varchar(50) NOT NULL,
associatedWith varchar(50) NOT NULL,
CONSTRAINT pk_persondb PRIMARY KEY (personID),
CONSTRAINT uq_persondb UNIQUE (associatedWith))
INSERT INTO personsdb
(personID, personName, associatedWith)
VALUES
('John', 'Mary'),
('Jack', 'Maggie'),
('Jeff', 'Marie')
I have a UNIQUE Constraint on the 'associatedWith' column, as I want to make sure that a person in personName can only be associated with one person in associatedWith, i.e. Mary could not be associated with Jeff because Mary is already associated with John.
My query relates to inserting the next row of the table. I want to insert 'Mary' into the personName column, but need a rule that autopopulates or only allows 'John' to be populated in the corresponding 'associatedWith' field, as a person can only be associated with one other person, and as John is already associated with Mary, when Mary is entered into the table, she should automatically be associated with John.
I'm relatively new to SQL but I'd like to figure it out as much as possible myself - if you could hint at a way to do this (in layman's terms) I'd be grateful so that I can go and research and learn how to do this.
Thanks very much in advance for your help.
David
This is a unary relationship which you cannot implement using foreign keys. You'll have to use a trigger. See below for full implementation.
CREATE TABLE dbo.Person(PersonId int not null primary key identity(1, 1), PersonName varchar(20) not null, AssociatedWith varchar(20));
GO
create trigger dbo.AssociationConstraint
ON dbo.Person
FOR INSERT, UPDATE
AS
IF (EXISTS(SELECT TOP(1) 1 FROM inserted i INNER JOIN dbo.Person p on i.PersonName = p.AssociatedWith)
OR EXISTS(SELECT TOP(1) 1 FROM inserted i INNER JOIN dbo.Person p on i.AssociatedWith = p.PersonName))
BEGIN
RAISERROR('Person is already part of a relationship', 16, 1);
ROLLBACK TRANSACTION;
END
GO
insert into dbo.Person(PersonName, AssociatedWith) values('John', 'Mary'), ('Jack', 'Maggie'), ('Jeff', 'Marie');
--this will error
insert into dbo.Person(PersonName, AssociatedWith) values('Mary', 'Jack');

Cannot insert the value NULL into column 'id', even though Column has IDENTITY property

CREATE TABLE Type1
(
TypeID TINYINT NOT NULL IDENTITY(1,1),
TypeName VARCHAR(20) NOT NULL,
Speed VARCHAR(10) NOT NULL
CONSTRAINT TypeID_pk PRIMARY KEY (TypeID)
);
CREATE TABLE Splan
(
PlanID TINYINT NOT NULL IDENTITY(1,1),
TypeID TINYINT NOT NULL,
PlanName VARCHAR(20) NOT NULL,
Quota SMALLINT NOT NULL
CONSTRAINT PlanID_pk PRIMARY KEY (PlanID)
CONSTRAINT TypeID_fk FOREIGN KEY (TypeID) REFERENCES Type1(TypeID)
);
INSERT INTO Type1(TypeName, Speed)
VALUES ('Sample type', '10Mbps'),
('Other type', '50Mbps');
^Up until there its fine
and then when I enter the following it returns "Msg 515, Level 16, State 2, Line 8
Cannot insert the value NULL into column 'TypeID' ..... column does not allows. INSERT fails." Statement terminates
INSERT INTO Splan(PlanName, Quota)
VALUES ('Some sample name', '500GB'),
('sample2, '250GB');
I've tried creating the constraints at both column and table level but the second INSERT statement still refused to enter. Double checked via the GUI and 'TypeID' definitely has an IDENTITY property.
I've looked about everywhere and this errors seems to stem from the lack of an IDENTITY property, yet its present in my creation statements and the error still comes up. Tried removing the seed and increment from IDENTITY, still nothing. Also tried inserting the data one row at a time, nothing there either.
P.S If you haven't noticed the actual names have been substituted and other columns rows have been omitted.
Since you created typID as NOT NULL, Sql is complaining that the default value (NULL) is not acceptable.
Try
INSERT INTO Splan(TypeID, PlanName, Quota)
VALUES (1, 'Some sample name', '500GB'),
(2, 'sample2, '250GB');
Where corresponding records with TypeID = 1 and TypeID = 2 are in your Type1 table.
You are creating 2 tables: Type1 which has a primary key TypeId that is auto generated
and SPlan which has a primary key PlanId that is also auto generated and a foreign key TypeId that must be supplied and cannot be null.
As written you must enter 1 or more records into Type1 first, obtain their TypeIds, then enter those TypeIds into new records in SPlan.
Incidentally, using TINYINT for your primary key data types is perfectly legal but probably a really bad idea if this is anything other than homework.
You need to supply a value for TypeID in your second query because you have a foreign key relationship with the Type1 table and because the TypeID column in the Splan table is also declared NOT NULL.
INSERT INTO Splan(TypeID, PlanName, Quota)
VALUES (1, 'Some sample name', '500GB'),
(2, 'sample2, '250GB');
Try inserting both records in a transaction using SCOPE_IDENTITY
begin tran
INSERT INTO Type1(TypeName, Speed)
VALUES ('Sample type', '10Mbps')
DECLARE #id INT = SCOPE_IDENTITY();
INSERT INTO Splan(TypeID, PlanName, Quota)
VALUES (#id, 'Some sample name', '500GB')
commit