SEC S20W1 || Databases and SQL language - Part 1

in #dynamicdevs-s20w12 months ago

Dear Professor,

This is my submission for the Engagement Challenge. I am impressed with this time homework contest relate with Databases and SQL Language. I want to Thank you to professor @kouba01 to organizing such a valuable contest.

IMG_9148.jpeg
Image Source

Exercise 1

For each of the following statements, validate each proposition by putting the letter V if it is correct or F if it is incorrect.

Q1) A column corresponds to:

• an index: F
• an elementary property of a real-world
object: V

• a real-world object: F

Instead of being a simple property, a column in MySQL usually reflects an attribute of an actual object, such its name or age.

Mark the letter V in front of the correct word to complete the following sentence:

Q2) A ……….. is a set of data related to the same subject (or entity) and structured in a table format.

• Database: F
• Table: V
• Row: F

A table makes comparison and analysis easier by arranging data into rows and columns and clearly showing relevant information.

Q3) Among the following propositions, which correspond to a primary key?

• A field that does not accept duplicates: V
• Allows identifying information to retrieve
it: V

• First record in a table: F

In database parlance, this type of field is called a "primary key" or "unique identifier". It guarantees that every record is unique and that it may be effectively accessed or retrieved by utilizing its unique value.

Q4) In SQL, to ensure data integrity in a child table after modifying the primary key value of a parent table, we use the clause:

• CHECK: F
• ON UPDATE CASCADE: V
• ON DELETE CASCADE: F

By automatically updating foreign key values in the child table to correspond with modifications in the parent table's primary key and maintaining referential consistency, the ON UPDATE CASCADE clause guarantees data integrity.

Q5) Integrity constraints on a column are:

• PRIMARY KEY: V
• CHECK: V
• FOREIGN KEY: V
• REFERENCES: V

Data accuracy and consistency are guaranteed by integrity constraints such as PRIMARY KEY, CHECK, FOREIGN KEY, and REFERENCES. The primary key ensures unique identity, the foreign key preserves relational integrity, the referential linkages between tables are enforced by REFERENCES, and values are validated by CHECK.

Q6) In SQL, which clauses placed after the data type of a field ensure that the content of this field is unique?

• PRIMARY KEY: V
• UNIQUE: V
• NOT NULL: F
• CONSTRAINT: F

Both UNIQUE and PRIMARY KEY guarantee uniqueness; UNIQUE permits more than one null value, whereas PRIMARY KEY only permits unique, non-null values.

Q7) In SQL, the Drop Table command allows:

• Deleting integrity constraints on a table
only: F
• Deleting a table: V
• Deleting one or more rows from a table:
F
• Deleting one or more columns from a table: F

A table and its contents are permanently removed from the database by using the DROP TABLE command, which also frees up resources and space.


Exercise 2:

To describe the employees of a company and their distribution among different functions, the following table has been created:

codempnomempprenempdnempniveaucodfctintfct
E001TOUNSISafa1980-01-10Master20Finance
E002KEFIAli1981-09-12High School10Administrative
E003BEJIMohamed1977-04-15High School20Finance
E004TOUATILamia1965-06-21Technician20Security
E005SOUSSILeila1982-11-28Master10Administrative
E006SFAXILotfi1988-06-09Master30Legal

Description of Columns

ColumnDescriptionColumnDescription
codempEmployee codednempEmployee's date of birth
nomempEmployee's last nameniveauRecruitment level
prenempEmployee's first namecodfctFunction code
intfctFunction title

• This table suffers from anomalies from its creation. Identify the anomalies in this structure and explain their origins.

Identifying Redundancy and Update Anomalies: The present table structure contains both function-related information (function code and title) and recruitment-level information, which may result in redundancy and update anomalies.For example, if a function title changes, it must be changed in all records where that function appears.

Insertion Errors: Adding a new function or recruitment level necessitates inserting numerous records. For example, if a new function is added, you must insert numerous entries, which may result in inconsistency if the function details are not updated consistently.

To correct the anomalies, we propose the following management rules:

R1: An employee is assigned to only one function, and a function can include several employees.
R2: An employee has only one recruitment level, and a recruitment level concerns several employees.

Question: Provide a textual representation of this database.

For the DBMS to take into account that an employee can occupy a position in the company for a determined period, and may occupy the same position at different times,

R1 becomes: An employee can hold one or more functions, and for each assignment, the start and end dates of the assignment are recorded.

Question: Provide the textual representation of this database.

We propose to add a table named "bonus" to record performance bonuses awarded to each employee during a year, with the fields AnneePrime as the year of the bonus and PrimeRend as the value of the bonus. To do this, we must respect the new management rule R3: An employee can receive performance bonuses during the same year.

Question: Provide the textual representation for this table.

Here is my answer for the Exercise 2,

Identifying Anomalies

Redundancy and Update Anomalies:

Function Information: For every employee designated to a certain function, the intfct (Function title) is repeated. There may be discrepancies if a function's title changes because all records containing that function will need to be changed. Information about the Recruitment Level: Each employee receives the same niveau (Recruitment level), which could lead to redundancy if the description of the Recruitment Level changes.

Insertion Anomalies:
It may be inefficient and error-prone to ensure that all relevant personnel records are updated when new functions or recruitment levels are added.

Anomalies of Deletion: If there is no other record connecting the removal of a function or recruitment level to its specifics, information may be lost. Modified Database Structure First Textual Illustration:

Corrected Database Structure

Initial Textual Representation:

Employee Table:

codemp: Employee code (Primary Key)
nomemp: Employee's last name
prenemp: Employee's first name
dnemp: Employee's date of birth

Function Table:

codfct: Function code (Primary Key)
intfct: Function title

Recruitment Level Table:

niveau: Recruitment level (Primary Key)

Employee Function Assignment Table:

codemp: Employee code (Foreign Key from Employee Table)
codfct: Function code (Foreign Key from Function Table)
start_date: Start date of the function assignment
end_date: End date of the function assignment (can be NULL if currently assigned)
Primary Key: (codemp, codfct, start_date)
With New Requirements for Multiple

Assignments and Bonuses

Employee Table:

codemp: Employee code (Primary Key)
nomemp: Employee's last name
prenemp: Employee's first name
dnemp: Employee's date of birth
Function Table:

codfct: Function code (Primary Key)
intfct: Function title

Recruitment Level Table:

niveau: Recruitment level (Primary Key)

Employee Function Assignment Table:

codemp: Employee code (Foreign Key from Employee Table)
codfct*: Function code (Foreign Key from Function Table)
*start_date: Start date of the function assignment
end_date: End date of the function assignment (can be NULL if currently assigned)
Primary Key: (codemp, codfct, start_date)

Bonus Table:

codemp: Employee code (Foreign Key from Employee Table)
AnneePrime: Year of the bonus
PrimeRend: Value of the bonus
Primary Key: (codemp, AnneePrime)

This format eliminates redundancy, sets off employee data from function and recruiting level specifics, and facilitates the effective tracking of numerous assignments and performance bonuses.


Exercise 3

Let’s consider the database "GestElections," which contains information about the elections of the foundation council members of a high school. It is described by the following simplified textual representation:

| Electeur (NumElv, NomPrenElv, AgeElv) |
| Candidat (NumCand, NumList#, Appelation) |
| Liste (NumList, DesList, NbrCand) |
| Voter (NumCand#, NumList#, NumElv#) |

Description of the columns in the tables

ColumnDescriptionData TypeSizeMandatoryTable
NumElvNumber of an elector studentAuto-increment3YesElecteur
NomPrenElvElector student's full nameText20YesElecteur
AgeElvElector student’s age [12..20]Numeric2NoElecteur
NumCandNumber of a candidate studentNumeric2YesCandidat
NumListList numberNumeric1YesListe
AppelationCandidate's designationText20YesCandidat
DesListUnique designation of a listText20YesListe
NbrCandNumber of candidates [1..6]Numeric2NoListe

The database administrator asks you to help create and modify the structure of the tables indicated above.
Therefore, provide the SQL commands to:

• Create the "GestElections" database:

• Create the various tables in the "GestElections" database.

• Add a "Datevote" column representing the current date to the "Voter" table.

• Expand the "Appelation" column of the "Candidat" table to 30 characters.

• Split the "NomPrenElv" column of the "Electeur" table into a "LastName" and "FirstName," each of 15 characters (both fields are mandatory).

The head of the high school wants to compile statistics on votes according to the gender of the elector (boy or girl) but cannot find results.

What can be proposed to him?
Write your proposal in SQL.

Here's a list of SQL commands to complete the requested tasks:

  1. Create the "GestElections" Database
    sql code:-
    CREATE DATABASE GestElections;

Screenshot_2024_0916_001002.png
Screenshot was taken by me.

  1. Create the Various Tables in the "GestElections" Database
    sql code:-
    USE GestElections;

CREATE TABLE Electeur (
NumElv INT AUTO_INCREMENT PRIMARY KEY,
LastName VARCHAR(15) NOT NULL,
FirstName VARCHAR(15) NOT NULL,
AgeElv INT
);

CREATE TABLE Candidat (
NumCand INT PRIMARY KEY,
NumList INT NOT NULL,
Appelation VARCHAR(20) NOT NULL,
FOREIGN KEY (NumList) REFERENCES Liste(NumList)
);

CREATE TABLE Liste (
NumList INT PRIMARY KEY,
DesList VARCHAR(20) NOT NULL,
NbrCand INT
);

CREATE TABLE Voter (
NumCand INT,
NumList INT,
NumElv INT,
Datevote DATE,
PRIMARY KEY (NumCand, NumList, NumElv),
FOREIGN KEY (NumCand) REFERENCES Candidat(NumCand),
FOREIGN KEY (NumList) REFERENCES Liste(NumList),
FOREIGN KEY (NumElv) REFERENCES Electeur(NumElv)
);

  1. For the "Voter" table, add a "Datevote" column. (This phase and the Datevote column definition are part of the CREATE TABLE Voter command.)
  1. Increase the length of the "Candidat" table's "Appelation" column to 30 characters.

SQL code:-

ALTER TABLE Candidat
MODIFY Appelation VARCHAR(30) NOT NULL;

  1. Divide the "NomPrenElv" Column into "LastName" and "FirstName" in the "Electeur" Table.

SQL code:-
Assuming you have a copy of the data on hand or that dropping and rebuilding the table is OK.Divide the "NomPrenElv" Column into "LastName" and "FirstName" in the "Electeur" Table.

-- Drop existing table
DROP TABLE Electeur;

-- Recreate table with split columns
CREATE TABLE Electeur (
NumElv INT AUTO_INCREMENT PRIMARY KEY,
LastName VARCHAR(15) NOT NULL,
FirstName VARCHAR(15) NOT NULL,
AgeElv INT
);

--If you have a technique for splitting names, you can replicate old data into the new form. Proposal for Gender-based Statistics To collect information based on the gender of the elector (boy or girl), first add a gender column to the Electeur table. Here's how to change the schema and input sample data to allow gender-based queries:

Add Gender Column to Electeur Table:
sql code

ALTER TABLE Electeur
ADD Gender CHAR(1) CHECK (Gender IN ('M', 'F')) NOT NULL;

Update the Electeur Table with Gender Data:
sql code:-
-- Example: Update gender data for existing records
UPDATE Electeur
SET Gender = 'M'
WHERE LastName = 'Smith' AND FirstName = 'John'; -- Use appropriate conditions

Compile Statistics Based on Gender:
sql code:-

-- Count the number of voters by gender

*SELECT Gender, COUNT() AS **
NumberOfVoters
FROM Electeur
JOIN Voter ON Electeur.NumElv = Voter.NumElv
GROUP BY Gender;

By adding a gender column and adjusting the queries, you can easily compile statistics and analyze voting patterns based on gender.

Screenshot_2024_0915_074346.png
Screenshot was taken from my laptop screen

I would like to invite @shiftitamanna, @ripon0630 and @kyrie1234 to take part in this wonderful contest.

Thank you for giving a time!

Sort:  
Thank you,@arshani for publishing an article using our tag #dynamicdevs-s20w1. We have accessed your article and we present the result of the assessment below.

Criteria Remark
#steemexclusive
Free of Plagiarism
AI Article ✅ Original (Human text!)
Bot free
Comment/Recommendation

Question 1: Validation of the propositions

You have understood and validated the propositions by distinguishing the correct answers from the incorrect ones. The explanations on the columns, the primary keys and the integrity constraints are very well formulated.

Question 2: Anomalies in the structure of the employee table

Your analysis of anomalies related to redundancy and updates is precise. The creation of separate tables for functions and recruitment levels is well thought out and allows for an improvement in the structure of the database.

## Question 3: SQL table manipulation

Your SQL commands to create the "GestElections" database and its tables are correct and well structured. The addition of the "Datevote" column, the expansion of the "Appelation" column and the division of the "NomPrenElv" field are well executed.

Proposal for voting statistics by gender

Your proposal to add a "Gender" column and update the data is relevant and well justified. This allows for effective analysis of votes based on gender.


Overall, your answers show a very good command of relational databases and SQL manipulation. They are clear, precise and demonstrate a good understanding of the underlying concepts. underlying.

Total| 8/10

Coin Marketplace

STEEM 0.19
TRX 0.18
JST 0.033
BTC 87161.65
ETH 3057.00
USDT 1.00
SBD 2.75