SEC S20W2 || Databases and SQL language - Part 2

kouba01 -

Created by @kouba01 using Canva & PhotoFilter

Dear Steemians,

After a first week full of learning and discoveries about databases and SQL language, we are pleased to invite you to participate in the second week of the SEC S20W2 competition, which continues this exciting journey.

In this second part, we will dive deeper into the concepts introduced during the first week, focusing on the DQL (Data Query Language) and DML (Data Manipulation Language). While the first week laid a solid foundation on tables, relationships, and primary keys, this new phase will allow you to further explore SQL commands to query, insert, update, and delete data with ease.

This week is a logical continuation of the previous one but introduces more interactive and practical concepts in the world of databases. You will have the opportunity to apply what you’ve learned while discovering advanced techniques to manipulate your data more efficiently.

We invite you not to miss this opportunity to strengthen your knowledge and showcase your skills within the community. Get ready to face new challenges and share your results with everyone!

Good luck to all, and may this second week be as fruitful as the first!

Data Query and Manipulation Language (DQL+DML)

I. Data Query Language

  1. General Syntax

SQL is both a data manipulation language and a data definition language. However, data definition is typically managed by the database administrator, which is why most people using SQL primarily focus on the data manipulation language, specifically the data query language, which allows them to select the data they are interested in.

The main command in the data query language is the SELECT command.

The SELECT command is based on relational algebra, performing data selection operations on several relational tables through projection. Its general syntax is as follows:

SELECT [ALL] | [DISTINCT] <list of attributes> | * FROM <list of tables>
[WHERE <condition>]
[GROUP BY <list of attributes>] [HAVING <group condition>] [ORDER BY <list of sort attributes>];

2. Projection

A projection is an instruction that allows you to select a set of attributes from a table.

Syntax:

SELECT [ALL] | [DISTINCT] <list of attributes> | * FROM <the table>;

Examples:

Note: DISTINCT is used to eliminate duplicates. By default, all tuples are retrieved (ALL).


3. Restrictions

A restriction selects rows that satisfy a logical condition applied to their attributes. In SQL, restrictions are expressed using the WHERE clause followed by a logical condition using logical operators (AND, OR, NOT), arithmetic operators (+, -, *, /, %), arithmetic comparators (=, !=, >, <, >=, <=), and predicates (NULL, IN, BETWEEN, LIKE, ...).

These operators apply to numeric values, character strings, and dates.

Note: Character strings and date constants must be enclosed in single quotes ('...'), unlike numbers.

Syntax:

SELECT [ALL] | [DISTINCT] <list of attributes> | * FROM <the table>
WHERE <condition>;

At the WHERE clause level, the following predicates apply:

Examples:

Note: The LIKE predicate allows string comparisons using wildcard characters:

To select clients whose names have an 'E' in the second position:

WHERE ClientName LIKE "_E%"

Provide the names of customers who do not have an address.


4. Expressions, Aliases, and Functions

a. Expression
SQL expressions work with attributes, constants, and functions. Arithmetic operators can link these elements (+, -, *, /). Expressions can appear:

b. Alias
Aliases allow renaming attributes or tables.

SELECT attr1 AS alias1, attr2 AS alias2, ...
FROM table1 alias t1, table2 alias t2…;

For attributes, the alias corresponds to the column titles in the query result. It is often used for calculated attributes (expressions).
Note: The AS keyword is optional.

c. Function
The following table lists some predefined functions:

Function NameFunction Role
AVGAverage
SUMSum
MINMinimum
MAXMaximum
COUNT(*)Number of rows
COUNT(Attr)Number of non-null values for the attribute
COUNT([DISTINCT] Attr)Number of distinct non-null values for the attribute

Application:

Provide the value of products in stock.

We can express this query without specifying the keyword AS:

SELECT NP, (Qtes * PU) "Total Value"
FROM Product;

We only put the result column names in quotes if they contain spaces:

SELECT NP, (Qtes * PU) Value
FROM Product;

In both queries, NP refers to the product name, Qtes to the quantity, and PU to the unit price. The first query uses quotes because "Total Value" contains a space, while the second query does not require quotes as the column name "Value" does not have any spaces.

Provide the average unit price of the products.


5. Selection with Join

This involves selecting data from multiple tables that have one or more common attributes. The join is performed through conditions specified in the WHERE clause.

Syntax:

SELECT [ALL] | [DISTINCT] <list of attributes> | * FROM <list of tables>
WHERE Table1.Attrj = Table2.Attrj AND …
AND <condition>;

Examples:


6. Grouping

It is possible to group rows with a common value using the GROUP BY clause and group functions (cf. Function).

Syntax:

SELECT Attr1, Attr2, ..., GroupFunction FROM Table1, Table2, ...
WHERE List_Condition
GROUP BY List_Group
HAVING Condition;

Note: Aggregate functions used alone in a SELECT statement (without GROUP BY) operate on the entire set of selected tuples as if there were only one group.

Examples:


7. Sorting

The result rows of a SELECT statement are returned in an arbitrary order. The ORDER BY clause specifies the order in which the selected rows should be returned.

Syntax:

SELECT Attr1, Attr2, ..., Attrn FROM Table_Name1, Table_Name2, ...
WHERE Condition_List
ORDER BY Attr1 [ASC|DESC], Attr2 [ASC|DESC], ...;

Note: The default sort order is ascending (ASC).

Example:


II. Data Manipulation Language (DML)

The Data Manipulation Language (DML) consists of commands for querying and updating data in tables. Updating includes inserting new data, modifying existing data, and deleting data.

1. Inserting Data

Data can be inserted in two ways:

Syntax:

INSERT INTO Table_Name (Attr1, Attr2, ...)
VALUES (Value1, Value2, ...);

Example:

INSERT INTO Client VALUES ('CL01', 'BATAM', 'Tunis');
INSERT INTO Client VALUES ('CL02', 'BATIMENT', 'Tunis');

Syntax:

INSERT INTO Table_Name (Attr1, Attr2, ...)
VALUES (Value1a, Value1b, ...), (Value2a, Value2b, ...), ...;

Example:

INSERT INTO Client (ClientID, ClientName, ClientAddress)
VALUES ('CL03', 'AMS', 'Sousse'),
       ('CL04', 'GLOULOU', 'Sousse'),
       ('CL05', 'PRODELEC', 'Tunis');

Note: Any omitted attributes will take the default value of NULL. Data is assigned to columns in the order the attributes are declared in the INTO clause.


2. Modifying Data

Using the UPDATE command, you can modify the values of one or more fields in existing rows of a table.

Syntax:

UPDATE Table_Name
SET Attr1 = Expr1, Attr2 = Expr2, ...
WHERE Condition;

Examples:

UPDATE Product
SET Weight = 1
WHERE ProductID = 'P002';
UPDATE Product
SET Quantity = 1.1 * Quantity;

3. Deleting Data

The DELETE command is used to remove rows from a table.

Syntax:

DELETE FROM Table_Name
WHERE Condition;

Here, the FROM clause specifies the table from which rows will be deleted, and the WHERE clause defines the criteria for the rows to be deleted.

Homework :

Exercise 1:

A) For each row presented in the table below, extract the outlier element and provide a brief description of the common point between the remaining three elements. (1 point)

Element 1Element 2Element 3Element 4OutlierCommon Point
UpdateSelectAlterInsert
MaxDescSumAvg
BetweenInCountLike
Primary keyForeign keyUniqueDistinct

B) Answer TRUE or FALSE to the following statements: (1 point)

AffirmationsTrue/False
1. In SQL, it is not possible to delete a table that contains tuples.
2. A DBMS ensures data redundancy.
3. The Data Definition Language (DDL) allows adding integrity constraints to a table.
4. A primary key in one table can be a primary key in another table.
5. In SQL, the ORDER BY clause is used to sort selected columns of a table.
6. A foreign key column can contain NULL values.
7. The PRIMARY KEY constraint includes both UNIQUE and NULL constraints.
8. Referential integrity constraints ensure links between tables in a database.

Exercise 2:

Given the following tables of books and members:

IdTitleAuthorPublisherPagesYearBorrowerReturn_Date
1Notre-dame de ParisVictor HugoGosselin636183112014-05-13
2Les MisérablesVictor HugoLacroix1662186222014-08-28
3Journey to the Center of the EarthJules VerneHetzel186412014-07-10
4Around the World in 80 DaysJules VerneHetzel223187212014-06-10
5House of the DeadFyodor DostoevskyMikhail1276186222014-05-13

Table 1: Books

IdLast NameFirst NameEmail
1DUPONTJeanJean.dupont@gmail.com
2MARTINPaulPaul.martin@gmail.com

Table 2: Members

  1. Fill in the table below by providing the result returned or the query to obtain the result: (1 point)
QueryResult
SELECT count(Pages) "Count", sum(Pages) "Total Pages" FROM books
SELECT * FROM books WHERE Year IN (SELECT Year FROM books WHERE Id=2) AND Id<>2
  1. For each of the following propositions, validate each answer by marking the box with V for true or F for false. (1.5 points)

a) By executing the SQL query: UPDATE books SET Title = "Title1"; the DBMS:
□ Modifies the Title field of the first record in the books table to Title1.
□ Modifies the Title field of all records in the books table to Title1.
□ Displays an error message due to the absence of the WHERE clause.

b) The SQL query:
SELECT Title FROM books WHERE MONTH(Return_Date) in (5,6) AND YEAR(Return_Date) = 2014; is equivalent to:
SELECT Title FROM books WHERE Return_Date between "2014-05-01" AND "2014-06-30";
SELECT Title FROM books WHERE Return_Date >= "2014-05-01" OR Return_Date <= "2014-06-30";
SELECT Title FROM books WHERE Return_Date between "2014-05-01" OR "2014-06-30";

c) By executing the SQL query: SELECT Author, count(*) FROM books GROUP BY Title; the DBMS:
□ Displays the number of authors per title.
□ Displays the number of books per author.
□ Does not work.

d) By executing the SQL query: DELETE FROM books WHERE Pages = Null; the DBMS:
□ Deletes the Pages column.
□ Deletes the rows where the page count is not provided.
□ Does not work.


Exercise 3: (5.5 points)

Consider the medical laboratory database "analysis" defined by the following simplified textual representation:

PATIENT (idPatient, last_name, first_name, age, city)
The Patient table contains all the patients who have undergone analyses in the laboratory.

ANALYSIS (idAnalysis, name, price, min_value, max_value)
The Analysis table contains all the analyses the lab can perform.

DOCTOR (idDoctor, last_name, city, specialty)
The Doctor table contains all currently practicing doctors recorded in the database.

REPORT (idReport, idDoctor#, idPatient#, date)
The Report table contains patient analysis reports.

RESULT_REPORT (idReport#, idAnalysis#, value, status)
The ResultReport table contains the results of the analysis reports.

Write the SQL queries to:

Contest Guidelines

Post can be written in any community or in your own blog.

Post must be #steemexclusive.

Use the following title: SEC S20W2 || Databases and SQL language - Part 2

Participants must be verified and active users on the platform.

Post must be more than 350 words. (350 to 500 words)

The images used must be the author's own or free of copyright. (Don't forget to include the source.)

Participants should not use any bot voting services, do not engage in vote buying.

The participation schedule is between Monday, September 16 , 2024 at 00:00 UTC to Sunday, - September 22, 2024 at 23:59 UTC.

Community moderators would leave quality ratings of your articles and likely upvotes.

The publication can be in any language.

Plagiarism and use of AI is prohibited.

Participants must appropriately follow #club5050 or #club75 or #club100.

Use the tags #dynamicdevs-s20w2 , #country (example- #tunisia, #Nigeria) #steemexclusive.

Use the #burnsteem25 tag only if you have set the 25% payee to @null.

Post the link to your entry in the comments section of this contest post. (very important).

Invite at least 3 friends to participate in this contest.

Strive to leave valuable feedback on other people's entries.

Share your post on Twitter and drop the link as a comment on your post.

Your article must get at least 10 upvotes and 5 valid comments to count as valid in the contest, so be sure to interact with other users' entries

Rewards

SC01/SC02 would be checking on the entire 16 participating Teaching Teams and Challengers and upvoting outstanding content. Upvote is not guaranteed for all articles. Kindly take note.

At the end of the week, we would nominate the top 5 users who had performed well in the contest and would be eligible for votes from SC01/SC02.

Important Notice: The selection of the five should be based solely on the quality of their post. Number of comments is no longer a factor to be considered.


Best Regards,
Dynamic Devs Team