Question

Below is my code for the start of a simple job search database. When i try to actually populate the database using the insert statements, it adds each row multiple times.

CREATE TABLE IF NOT EXISTS Employers (
  Id INTEGER PRIMARY KEY autoincrement,
  Name VARCHAR(20) NOT NULL,
  Industry VARCHAR(20) NOT NULL,
  Description TEXT
  );

CREATE TABLE IF NOT EXISTS Jobs (
  Id INTEGER PRIMARY KEY autoincrement,
  EmpId INTEGER FOREIGN KEY REFERENCES Employers(Id),
  Title VARCHAR(20) NOT NULL,
  Description TEXT,
  Location VARCHAR(20) NOT NULL,
  Ann_sal INT NOT NULL  
  );

INSERT INTO Employers(Name, Industry, Description )
VALUES 
("Touchpoint Global", "IT", "We help achieve efficiency, reliability and accuracy. 
 We are experts at turning complex inputs into simple outputs.");

INSERT INTO Employers(Name, Industry, Description )
VALUES
("TyTech", "IT", "Here at Tytech, we specialise is building unique business solutions from the ground up. We focus on what you want, and how you want it.");

INSERT INTO Jobs( EmpId, Title, Description, Location, Ann_sal )
SELECT emp.Id, "Project Manager", "Project manager needed to oversee all future projects.", "GoldCoast", 80000
FROM Employers emp
WHERE emp.Name="Tytech";

INSERT INTO Jobs( EmpId, Title, Description, Location, Ann_sal )
SELECT emp.Id, "Project Manager", "Project manager needed to oversee all revolutionary projects.", "Kingscliff", 95000
FROM Employers emp
WHERE emp.Name="Touchpoint Global";

INSERT INTO Jobs( EmpId, Title, Description, Location, Ann_sal )
SELECT emp.Id, "Web Designer", "Web designer needed for upcoming business solution project.", "Kingscliff", 75750
FROM Employers emp
WHERE emp.Name="Touchpoint Global";

INSERT INTO Jobs( EmpId, Title, Description, Location, Ann_sal )
SELECT emp.Id, "Data Analist", "Data analist needed to review input data during testing phases and maintanence.", "Kingscliff", 70000
FROM Employers emp
WHERE emp.Name="Touchpoint Global";
Was it helpful?

Solution

Your script is executed multiple times. Every repeated execution will insert more records.

To ensure that the tables are empty, you could add the following statements before the INSERTs:

DELETE FROM Employers;
DELETE FROM Jobs;

However, to ensure that the tables are updated if their structure changes, you should drop the IF NOT EXISTS from the CREATE TABLE statements, and ensure they are dropped before these CREATE TABLE statements:

DROP TABLE IF EXISTS Employers;
DROP TABLE IF EXISTS Jobs;

OTHER TIPS

Creating appropriate and meaningful unique indexes will prevent unwanted duplicates from being inserted. Such as on name and industry, or title.

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