List of commits:
Subject Hash Author Date (UTC)
Travail sur intégration des exos dans les notes. c5a6676f85953c7bec9bb2de99bed3552ecf52af aubert@math.cnrs.fr 2018-05-20 05:04:30
Les exercises compilent :-) d4230fce5210d1d8905a42d11634e49e82217541 aubert@math.cnrs.fr 2018-05-19 19:09:56
Progrès sur exercises. 40dd86cdc624209a2282d4437921f46325c2cfa1 aubert@math.cnrs.fr 2018-05-19 18:34:07
Working on exercises. 42549c8d28249f1ecf85dd21f6d004ae63c533ad aubert@math.cnrs.fr 2018-05-19 05:43:04
Working on incorporating the exercises. f32148faeb8b11425fe9a57770db9bc85ae02c34 aubert@math.cnrs.fr 2018-05-19 04:51:37
working on sum for exo. 5fb55d2c31b06161ade3a7cae707485d8c02447a aubert@math.cnrs.fr 2018-05-18 21:12:56
Adding various small notes. 5eac6e0b19441fca9a3f70f239d5cbbc4d769976 aubert@math.cnrs.fr 2018-05-17 20:37:14
First pass over! ea1e4f6ddabd91287d10384dc8f28565a762526b aubert@math.cnrs.fr 2018-05-17 19:26:28
Working on notes on normal forms. 58bfcedc6bd6336592a5f93a43ffc0aaf64fa8f6 aubert@math.cnrs.fr 2018-05-16 16:40:12
Initial commit, draft of lecture notes. 200d2739bca881d60c7c9381b16f5a4d6384ff29 aubert@math.cnrs.fr 2018-05-16 15:35:36
Commit c5a6676f85953c7bec9bb2de99bed3552ecf52af - Travail sur intégration des exos dans les notes.
Author: aubert@math.cnrs.fr
Author date (UTC): 2018-05-20 05:04
Committer name: aubert@math.cnrs.fr
Committer date (UTC): 2018-05-20 05:04
Parent(s): d4230fce5210d1d8905a42d11634e49e82217541
Signer:
Signing key:
Signing status: N
Tree: 66a15695d59431393de525cc32a6557db009db1f
File Lines added Lines deleted
exercises/sum.md 138 1761
notes/00_Doc_Notes.md 2 1
notes/00_sum.md 1895 524
notes/Makefile 1 1
File exercises/sum.md changed (mode: 100644) (index 503c092..c6f2a50)
... ... pandoc sum.md --pdf-engine=xelatex --toc --filter pandoc-numbering --top-level-d
45 45
46 46 --> -->
47 47
48 Exercise +.#
49
50 What does it mean to say that `SQL` is at the same time a "data definition language" and a "data manipulation language"?
51
52
53 Solution +.#
54
55 It can specify the conceptual and internal schema, **and** it can manipulate the data.
56
57
58 Exercise +.#
59
60 Name three kind of objects (for lack of a better word) a `CREATE` statement can create.
61
62
63 Solution +.#
64
65 Database (schema), table, view, assertion, trigger, etc.
66
67
68 Exercise +.#
69
70 Write a `SQL` statement that adds a primary key constraint to an attribute named `Id` in an already existing table named `STAFF`.
71
72
73 Solution +.#
74
75 `ALTER TABLE STAFF ADD PRIMARY KEY(Id);`
76
77
78 Exercise +.#
79
80 Complete the following table wo different examples when asked for examples:
81
82 \begin{tabular}{m{6cm} | m{6cm} }
83 \hline
84 \rowcolor{lgray}
85 Data Type & Examples \\
86 \hline
87 Int & $4$, $-32$\\
88 \hline
89 Char(4) & %\blank[width=1.9em]{'trai', 'plol'}
90 \\
91 \hline
92 % \blank[width=1.9em]{VarChar(10)}
93 & 'Train', 'Michelle'\\
94 \hline
95 Bit(4) & % \blank[width=1.9em]{ B'1010', B'0101'}
96 \\
97 \hline
98 % \blank[width=1.9em]{Boolean}
99 & TRUE, UNKNOWN\\
100 \hline
101 \end{tabular}
102
103
104
105 Exercise +.#
106
107 Explain what the following SQL statement does
108
109 ```mysql
110 CREATE SCHEMA Faculty;
111 ```
112
113 Solution +.#
114
115 It creates a schema, i.e., a database, named "Faculty".
116
117
118 Exercise +.#
119
120 If I want to enter January 21, 2016, as a value for an attribute with the `DATE` datatype, what value should I enter?
121
122
123 Solution +.#
124
125 `DATE`'2016-01-21'
126
127
128 Exercise +.#
129
130 Write a statement that inserts the values "Thomas" and "$4$" into the table `TRAINS`.
131
132
133 Solution +.#
134
135 ```sql
136 INSERT INTO TRAINS VALUES('Thomas', 4);
137 ```
138
139
140 Exercise +.#
141
142 If `PkgName` is a primary key, what can you tell about the number of rows returned by the following statement?
143 ```sql
144 SELECT * FROM MYTABLE WHERE PkgName = 'MySQL';
145 ```
146
147
148 Solution +.#
149
150 Yes.
151
152
153 Exercise +.#
154
155 What is the difference between an implicit, an explicit, and a semantic constraint?
156
157
158 Solution +.#
159
160 The textbook reads, pp. 67 - 69:
161
162 #. Constraints that are inherent in the data model. We call these inherent model-based constraints or implicit constraints.
163 #. Constraints that can be directly expressed in schemas of the data model, typically by specifying them in the DDL (data definition language, see Section 2.3.1). We call these schema-based constraints or explicit constraints.
164 #. Constraints that cannot be directly expressed in the schemas of the data model, and hence must be expressed and enforced by the application programs. We call these application-based or semantic constraints or business rules.
165
166
167 Exercise +.#
168
169 If you want every tuple referencing the tuple you're about to delete to be deleted as well, what mechanism should you use?
170
171
172 Solution +.#
173
174 We should use a referential triggered action clause, `ON DELETE CASCADE`.
175
176
177 Exercise +.#
178
179 If a database designer is using the `ON UPDATE SET NULL` for a foreign key, what mechanism is he implementing (i.e., describe how the database will react a certain operation)?
180
181
182 Solution +.#
183
184 If the referenced tuple is updated, then the attribute of the referencing relation are set to NULL.
185
186
187 Exercise +.#
188
189 If the following is part of the design of a table:
190
191 ```sqlmysql
192 FOREIGN KEY (DptNumber) REFERENCES DEPARTMENT(DptNumber) ON DELETE SET DEFAULT ON UPDATE CASCADE
193 ```
194
195 What happen to the row whose foreign key `DptNumber` is set to $3$ if
196
197 #. the row in the `DEPARTEMENT` table with primary key `DptNumber` set to \(3\) is deleted?
198 #. the row in the `DEPARTEMENT` table with primary key `DptNumber` set to \(3\) as its value for `DptNumber` updated to \(5\)?
199
200
201
202 Solution +.#
203
204 The department number is set to the default value.
205
206 The department number is updated accordingly.
207
208
209 Exercise +.#
210
211 If the following is part of the design of a `WORKER` table:
212
213 ```sqlmysql
214 FOREIGN KEY WORKER(DptNumber) REFERENCES DEPARTMENT(DptNumber) ON UPDATE CASCADE
215 ```
216
217 Admitting there is a row in the `WORKER` table whose foreign key `DptNumber` is set to $3$, what would happen if
218
219 #. We tried to delete the row in the `DEPARTEMENT` table with primary key `DptNumber` set to \(3\)?
220 #. We tried to change the value of `DptNumber` of the row in the `DEPARTEMENT` table with primary key `DptNumber` set to \(3\)?
221
222
223
224 Exercise +.#
225
226 Given a relation `TOURIST(Name, EntryDate, Address)`, write a `SQL` statement printing the name and address of all the tourists who entered the territory after the 15 September, 2012.
227
228
229 Solution +.#
230
231 ```sqlmysql
232 SELECT Name, Address
233 FROM TOURIST
234 WHERE EntryDate > DATE'2012-09-15';
235 ```
236
237
238
239
240 Exercise +.#
241
242 What is the fully qualified name of an attribute? Give an example.
243
244
245 Solution +.#
246
247 The name of the relation with the name of its schema and a period beforehand. myDB.MYTABLE, EMPLOYEE.name, etc.
248
249
250 % Exercise +.#
251
252 If `DEPARTMENT` is a database, what is `DEPARTMENT.*`?}
253
254
255 Solution +.#
256
257 All the tables in that database.
258
259
260 Exercise +.#
261
262 What is a multi-set? What does it mean to say that SQL treats tables as multisets?
263
264
265 Solution +.#
266
267 A set where the same value can occur twice.
268 The same tuple can occur twice in a table.
269
270
271 Exercise +.#
272
273 What is the difference between those two queries?
274 ```sqlmysql
275 SELECT ALL * FROM MYTABLE;
276 ```
277 and
278 ```sqlmysql
279 SELECT DISTINCT * FROM MYTABLE;
280 ```
281 How are the results the same? How are they different?
282
283
284 Solution +.#
285
286 All will print the duplicate, distinct will eliminate them.
287
288 Problem +.#
289
290 *This exercise assume you successfully completed Problem~2 of Homework 1.*
291
292 1. Connect to your MySQL DBMS as `testuser`:
293 - **In windows**, open a command prompt (search for "cmd") and type
294
295 ```bat
296 cd "C:\Program Files\MySQL\MySQL Server 5.7\bin"
297 ```
298 - **In Linux**, open a shell (as a normal user)
299
300 Then, in both cases, type
301
302 ```plain
303 mysql -u testuser -p
304 ```
305
306 and enter the password `password`.
307 If you are prompted with a message
308
309 ```bash
310 ERROR 1045 (28000): Access denied for user 'testuser'@'localhost' (using password: YES)
311 ```
312
313 then you probably typed the wrong password.
314 Otherwise, you should see a welcoming message from MySQL / MariaDB and a prompt.
315 2. Create a new database called `HW_2Q1`
316
317 ```sqlmysql
318 CREATE DATABASE HW_2Q1;
319 ```
320 3. List the databases
321
322 ```sqlmysql
323 SHOW DATABASES;
324 ``` Make sure `HW_2Q1` is a part of it.
325 4. Remove ("drop") the database, using
326
327 ```sqlmysql
328 DROP DATABASE HW_2Q1;
329 ```
330 In the future, we will refer to the commands \ref{item-connect}.\ and \ref{item-create}.\ as "log-in as `testuser`" and create a database `HW_2Q1`.
331
332
333
334 Problem +.#
335
336 The goal of this problem is to learn where to find the documentation of your DBMS, and to have a first look at the syntax of SQL commands.
337
338 You can consult your textbook, Table~5.2, p. 140 (6th edition) or Table~7.2, p. 235 (7th edition), for a very quick summary of the most common commands.
339 Make sure you are familiar with the Backus–Naur form (BNF) notation commonly used:
340 \begin{itemize}
341 \item non-terminal symbols (i.e., variables, parameters) are enclosed in angled brackets,
342 ```plain
343 <...>
344 ```
345
346 \item optional parts are shown in square brackets,
347 ```plain
348 [...]
349 ```
350
351 \item repetitons are shown in braces
352 ```plain
353 {...}
354 ```
355
356 \item alternatives are shown in parenthesis and separated by vertical bars,
357
358 ```plain
359 (...|...|...)
360 ```
361
362 \end{itemize}
363
364 The most complete lists of commands are probably at
365 \begin{itemize}
366 \item \url{https://mariadb.com/kb/en/library/sql-statements/} and
367 \item \url{https://dev.mysql.com/doc/refman/5.7/en/sql-syntax.html}
368 \end{itemize}
369 Those are the commands implemented in the DBMS you are actually using.
370 Since there are small variations from one implementation to the other, it's better to take one of this link as a reference in the future.
371
372
373 Problem +.#
374
375 \emph{This exercise, and the following ones, assume you successfully completed Problem~\ref{setup}.}
376
377 Log in as `testuser` and create a database `HW_2Q3`.
378
379 1. We will first set-up our meta-data (i.e., the schema, the structure where our tables will be, and the tables themselves).
380
381 Let us first tell MySQL that we want to use that database
382 ```sqlmysql
383 USE HW_2Q3;
384 ```
385 and ask what it contains
386 ```sqlmysql
387 SHOW TABLES;
388 ```
389 Now, create a first table named `NAME`
390
391 ```sqlmysql
392 CREATE TABLE NAME(
393 FName VARCHAR(15),
394 LName VARCHAR(15),
395 Id INT,
396 PRIMARY KEY(Id)
397 );
398 ```
399
400
401 Note that the `SQL` syntax and your DBMS are completely fine with your statement spreading over multiple lines.
402 Let us create a second table, named `ADDRESS`
403
404 ```sqlmysql
405 CREATE TABLE ADDRESS(
406 StreetName VARCHAR(15),
407 Number INT,
408 Habitants INT,
409 PRIMARY KEY(StreetName, Number)
410 );
411 ```
412
413
414 To make sure those two tables were actually created, we can use
415
416 ```sqlmysql
417 SHOW TABLES;
418 ```
419 But how to make sure that you entered the attributes correctly?
420 One way to make sure is to enter the command
421
422 ```sqlmysql
423 show create table name;
424 ```
425
426 ```sqlmysql
427 DESC ADDRESS;
428 ```
429 and to examine carefully the message printed. You should read
430
431 ```sqlmysql
432 +------------+-------------+------+-----+---------+-------+
433 | Field | Type| Null | Key | Default | Extra |
434 +------------+-------------+------+-----+---------+-------+
435 | StreetName | varchar(15) | NO | PRI | NULL| |
436 | Number | int(11) | NO | PRI | NULL| |
437 | Habitants | int(11) | YES | | NULL| |
438 +------------+-------------+------+-----+---------+-------+
439 ```
440
441 If you believe there is a mistake, you can erase ("drop") the \emph{table} (not the whole database, as we did in Problem~1) using
442
443 ```sqlmysql
444 DROP TABLE ADDRESS;
445 ```
446 and then re-create it. Of course, you can do the same for the `NAME` table.
447
448 Now, let us add a foreign key to the `ADDRESS` table:
449
450 ```sqlmysql
451
452 ALTER TABLE ADDRESS
453 ADD FOREIGN KEY (Habitants)
454 REFERENCES NAME(Id);
455 ```
456
457 And observe the modification:
458 ```sqlmysql
459 DESC ADDRESS;
460 ```
461
462
463
464 2. This second part is about data, i.e., filling our tables with actual information.
465 We begin by adding some data in the `NAME` table:
466 ```sqlmysql
467 INSERT INTO NAME VALUES ('Barbara', 'Liskov', 003);
468 INSERT INTO NAME VALUES ('Tuong Lu', 'Kim', 004);
469 INSERT INTO NAME VALUES ('Samantha', NULL, 080);
470 ```
471
472
473 To display the data we just inserted, we can use:
474 ```sqlmysql
475 SELECT * FROM NAME;
476 ```
477
478
479 Do you notice anything regarding the values we entered for the `Id` attribute?
480
481 We can add some data into the `ADDRESS` table (using a different syntax):
482 ```sqlmysql
483 INSERT INTO ADDRESS (StreetName, Number, Habitants)
484 VALUES
485 ('Armstrong Drive', 10019, 003),
486 ('North Broad St.', 23, 004),
487 ('Robert Lane', 120, NULL);
488 ```
489
490
491 And let's use our first update command:
492 ```sqlmysql
493 UPDATE ADDRESS SET Habitants = 3 WHERE Number = 120;
494 ```
495
496
497
498 3.
499 Now, do the following:
500 1. Have a look at the formal definition of the
501 ```sqlmysql
502 ALTER
503 ```
504 command, at \url{https://dev.mysql.com/doc/refman/5.7/en/alter-table.html} or \url{https://mariadb.com/kb/en/library/alter-table/}.
505 2. Draw the relations corresponding to that database, including the domains and primary, as well as foreign, keys.
506 3. Write a
507
508 ```sqlmysql
509 SELECT
510 ```
511 statement that returns the
512 ```sqlmysql
513 Id
514 ```
515 number of the person whose first name is "Samantha".
516 % SELECT Id FROM NAME WHERE FName = 'Samantha';
517 4. Write a statement that violate the entity integrity constraint. What is the error message returned?
518 % ERROR 1062 (23000): Duplicate entry '80' for key 'PRIMARY'
519 5. Execute an `UPDATE` statement that violate the referential integrity constraint. What is the error message returned?
520 % ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`HW_2Q3`.`ADDRESS`, CONSTRAINT `fk_id` FOREIGN KEY (`Habitants`) REFERENCES `name` (`Id`))
521 6. Write a statement that violate another kind of constraint. Explain what constraint you are violating, and explain the error message.
522 % ERROR 1136 (21S01): Column count doesn't match value count at row 1
523
524 Problem +.#
525 Log in as `testuser` and create a database `HW_2Q4`. Tell MySQL that you want to use that database, and create a table (I will assume you named it `EXAMPLE` in the following, but you are free to name it the way you want) with at least two attributes that have different data types. Don't declare a primary key yet. Answer the following:
526
527 #. Add a tuple to your table using
528
529 ```sqlmysql
530 INSERT INTO EXAMPLE VALUES(X, Y);
531 ```
532 where "X" and "Y" are values with the right type.
533 Try to add this tuple again. What do you observe? (You can use
534
535 ```sqlmysql
536 SELECT * FROM EXAMPLE;
537 ```
538 to observe what is stored in this table.)
539 #. Alter your table to add a primary key, using
540
541 ```sqlmysql
542 ALTER TABLE EXAMPLE ADD PRIMARY KEY (Attribute);
543 ```
544 where `Attribute` is the name of the attribute you want to be a primary key. What do you observe?
545 #. Empty your table using
546 ```sqlmysql
547 DELETE FROM EXAMPLE;
548 ``` and alter your table to add a primary key, using the command we gave at the previous step. What do you observe?
549 #. Try to add the same tuple twice. What do you observe?
550 <!--
551 %#. Now, create \emph{another table} (just one attribute and no primary key is fine) and try to create a foreign key pointing to the attribute in `EXAMPLE` that is not the primary key.
552 % What do you observe?
553 % => Messy, they get an error message if the attribute is not the primary key or if the datatype isn't the same, or if the command is not properly formatted... The error message is too vague for them to learn anything.
554 -->
555
556 Solution +.#
557
558
559 ```sqlmysql
560 CREATE TABLE EXAMPLE(
561 X VARCHAR(15),
562 Y INT);
563 ```
564
565
566
567 ```sqlmysql
568 INSERT INTO EXAMPLE VALUES('Train', 4);
569 ```
570
571
572 OK to insert same tuple twice.
573
574 ```sqlmysql
575 ALTER TABLE EXAMPLE ADD PRIMARY KEY (X);
576 ERROR 1062 (23000): Duplicate entry 'Train' for key 'PRIMARY'
577 ```
578
579
580
581
582 %%%%% 03
583
584
585 Exercise +.#
586
587 Describe what the star do in the statement `SELECT ALL * FROM MYTABLE;`.
588
589
590 Solution +.#
591
592 It selects all the attributes.
593
594
595
596 Exercise +.#
597
598 What is wrong with the statement `SELECT * WHERE Name = 'CS' FROM DEPARTMENT;`?
599
600
601 Solution +.#
602
603 You can't have the `WHERE` before `FROM`.
604
605
606
607 Exercise +.#
608
609 When is it useful to use a select-project-join query?
610
611
612 Solution +.#
613
614 We use those query that projects on attributes using a selection and join conditions when we need to look for information gathered in multiple tables.
615
616
617 Exercise +.#
618
619 When is a tuple variable useful?
620
621
622 Solution +.#
623
624 It makes the distinction between two different copies of the same relation, it is useful when we want to select a tuple in a relation that is in a particular relation with a tuple in the same relation.
625
626 cf. \url{https://stackoverflow.com/a/7698796/2657549}:
627 They are useful for saving typing, but there are other reasons to use them:
628 \begin{itemize}
629 \item If you join a table to itself you must give it two different names otherwise referencing the table would be ambiguous.
630 \item It can be useful to give names to derived tables, and in some database systems it is required... even if you never refer to the name.
631 \end{itemize}
632
633
634 Exercise +.#
635
636 Write a query that changes the name of the professor whose login is 'caubert' to 'Hugo Pernot' in the table `PROF`.
637
638
639 Solution +.#
640
641 `UPDATE PROF SET Name = 'Hugo Pernot' WHERE Login = 'caubert';`
642
643
644 Exercise +.#
645
646 Can an `UPDATE` statement have a `WHERE` condition using an attribute that isn't the primary key? If no, justify, if yes, tell what could happen.
647
648
649 Solution +.#
650
651 Yes, we could update more than one tuple at a time.
652
653
654 Exercise +.#
655
656 What is a multi-set?
657 What does it mean to say that `SQL` treats tables as multisets?
658
659
660 Solution +.#
661
662 A set where the same value can occur twice.
663 The same tuple can occur twice in a table.
664
665
666 Exercise +.#
667
668 What is the difference between those two queries?
669 ```sqlmysql
670 SELECT ALL * FROM MYTABLE;
671 ```
672 and
673 ```sqlmysql
674 SELECT DISTINCT * FROM MYTABLE;
675 ```
676 How are the results the same? How are they different?
677
678
679 Solution +.#
680
681 `ALL` will print the duplicate, `DISTINCT` will eliminate them.
682
683
684 Exercise +.#
685
686 What are the possible meanings or interpretations for a `NULL` value?
687
688
689 Solution +.#
690
691 Unknown value, unavailable / withheld, N/A.
692
693
694
695 Exercise +.#
696
697 What are the values of the following expressions (i.e., do they evaluate to `TRUE`, `FALSE`, or `UNKNOWN`)?
698
699 `TRUE AND FALSE`\hspace{2.2em}
700 `TRUE AND UNKNOWN`\hspace{2.2em}
701 `NOT UNKNOWN`\hspace{2.2em}
702 `FALSE OR UNKNOWN`
703
704
705
706 Solution +.#
707
708 `FALSE`, `UNKNOWN`, `UNKNOWN`, `FALSE`
709
710
711 Exercise +.#
712
713 What comparison expression should you use to test if a value is different from `NULL`?
714
715
716 Solution +.#
717
718 `IS NOT`
719
720
721 Exercise +.#
722
723 Explain this query:
724
725 ```sqlmysql
726 SELECT Login
727 FROM PROF
728 WHERE Department IN ( SELECT Major
729 FROM STUDENT
730 WHERE Login = 'jrakesh');
731 ```
732
733
734 Solution +.#
735
736 It list the login of the professors teaching in the department where the student whose login is "jrakesh" is majoring.
737
738
739 Exercise +.#
740
741 What is wrong with this query?
742
743 ```sqlmysql
744 SELECT Name
745 FROM STUDENT
746 WHERE Login IN ( SELECT Code
747 FROM Department
748 WHERE head = 'aturing');
749 ```
750
751
752
753
754
755 Solution +.#
756
757 It tries to find a `Login` in a `Code`!
758
759
760 Exercise +.#
761
762 Write a query that returns the number of row (i.e., of entries, of tuples) in a table named `BOOK`.
763
764
765 Solution +.#
766
767 `SELECT COUNT(*) FROM BOOK;`
768
769
770 Exercise +.#
771
772
773 Consider the following `SQL` code:
774
775 ```sqlmysql
776 CREATE TABLE COMPUTER(
777 Id VARCHAR(20) PRIMARY KEY,
778 Model VARCHAR(20)
779 );
780 CREATE TABLE PRINTER(
781 Id VARCHAR(20) PRIMARY KEY,
782 Model VARCHAR(20)
783 );
784 CREATE TABLE CONNEXION(
785 Computer VARCHAR(20),
786 Printer VARCHAR(20),
787 PRIMARY KEY(Computer, Printer),
788 FOREIGN KEY (Computer) REFERENCES COMPUTER(Id),
789 FOREIGN KEY (Printer) REFERENCES PRINTER(Id)
790 );
791
792 INSERT INTO COMPUTER VALUES
793 ('A', 'DELL A'),
794 ('B', 'HP X'),
795 ('C', 'ZEPTO D'),
796 ('D', 'MAC Y');
797 INSERT INTO PRINTER VALUES
798 ('12', 'HP-140'),
799 ('13', 'HP-139'),
800 ('14', 'HP-140'),
801 ('15', 'HP-139');
802 INSERT INTO CONNEXION VALUES
803 ('A', '12'),
804 ('A', '13'),
805 ('B', '13'),
806 ('C', '14');
807 ```
808
809
810 Write a query that returns … (in parenthesis, the values returned \emph{in this set-up}, but you have to be general)
811
812 1. … the number of computers connected to the printer whose id is '13' (i.e., \(2\) ).
813 2. … the number of different models of printers (i.e., \(2\)).
814 3. … the model(s) of the printer connected to the computer whose id is 'A' (i.e., 'HP-140' and 'HP-139').
815 4. … the id of the computer(s) not connected to any printer (i.e., 'D').
816
817
818
819 Exercise +.#
820 Write a query that returns the sum of all the values stored in the `Pages` attribute of a `BOOK` table.
821
822
823 Solution +.#
824
825 `SELECT SUM(Pages)FROM BOOK;`
826
827
828
829 Exercise +.#
830 Write a query that adds a `Pages` attribute of type `INT` into a (already existing) `BOOK` table.
831
832
833 Solution +.#
834
835 `ALTER TABLE BOOK ADD COLUMN Pages INT;`
836
837
838 Exercise +.#
839
840 Write a query that removes the default value for a `Pages` attribute in a `BOOK` table.
841
842
843 Solution +.#
844
845 `ALTER TABLE BOOK ALTER COLUMN Pages DROP DEFAULT;`
846
847 Problem +.#
848
849 Create the `PROF`, `STUDENT`, `DEPARTMENT` and `GRADE` tables as during the lecture.
850 Populate them with some data.
851
852 1. Create a `LECTURE` table as follows:
853 \begin{itemize}
854 \item It should have four attributes, `Name`, `Instructor`, `Code`, and \texttt{Year}, of type `VARCHAR(25)` for the two first, `YEAR(4)`, and `CHAR(5)`.
855 \item The \texttt{Year} and `Code` attributes should be the primary key (yes, have \emph{two} attributes be the primary key).
856 \item The `Instructor` attribute should be a foreign key referencing the `Login` attribute in `PROF`.
857 \end{itemize}
858 2. Populate the `LECTURE` table with some made-up data.
859 3. Add two columns to the `GRADE` table, using
860 ```sqlmysql
861 ALTER TABLE GRADE
862 ADD COLUMN LectureCode CHAR(5),
863 ADD COLUMN LectureYear YEAR(4);
864 ```
865
866 4. Use `DESCRIBE` and `SELECT` to observe the schema of the `GRADE` table and its rows (i.e., tuples).
867 Is that what you would have expected?
868 5. Add a foreign key in `GRADE`, using
869
870 ```sqlmysql
871 ALTER TABLE GRADE
872 ADD FOREIGN KEY (LectureYear, LectureCode)
873 REFERENCES LECTURE(Year, Code);
874 ```
875
876 6. Update the tuples in `GRADE` with some made-up data: now, every row should contain, on top of a login and a grade, a lecture year and a lecture code.
877 7. Write `SELECT` statements answering the following questions (where XXX and YY should be relevant values considering your data):
878 1. "I taught class XXX in YYYY, could you give me the logins and grades of the students who took it?"
879 2. "Could you list the instructors who taught in YYYY?" (and, please, avoid duplicates)
880 3. "Could your list the name and grade of all the student who took class XXX (no matter the year)?"
881 4. "Could you tell me which years was the class XXX taught?"
882 5. "Could you list the classes taught the same year as class XXX?"
883 6. "Could you print the name of the students who registered after Ava Alyx?"
884 7. "How many departments' heads are teaching this year?"
885
886
887 %Solution +.#
888
889 ```sqlmysql
890 CREATE TABLE LECTURE(
891 Name VARCHAR(25),
892 Instructor VARCHAR(25),
893 Year YEAR(4),
894 Code CHAR(5),
895 PRIMARY KEY(Year, Code),
896 FOREIGN KEY (Instructor) REFERENCES PROF(Login)
897 );
898
899 INSERT INTO LECTURE VALUES
900 ('Intro to CS', 'caubert', 2017, '1304'),
901 ('Intro to Algebra', 'perdos', 2017, '1405'),
902 ('Intro to Cyber', 'aturing', 2017, '1234');
903
904 ALTER TABLE GRADE ADD COLUMN LectureCode CHAR(5),
905 ADD COLUMN LectureYear YEAR(4);
906
907 DESCRIBE GRADE;
908
909 SELECT * FROM GRADE;
910
911 ALTER TABLE GRADE ADD FOREIGN KEY (LectureYear, LectureCode) REFERENCES LECTURE(Year, Code);
912
913 UPDATE GRADE SET LectureCode = '1304', LectureYear = 2017 WHERE Login = 'jrakesh' AND Grade = '2.85';
914 UPDATE GRADE SET LectureCode = '1405', LectureYear = 2017 WHERE Login = 'svlatka' OR (Login = 'jrakesh' AND Grade = '3.85');
915 UPDATE GRADE SET LectureCode = '1234', LectureYear = 2017 WHERE Login = 'aalyx' OR Login = 'cjoella';
916
917 SELECT Login, Grade FROM Grade WHERE Lecturecode='1304' and LectureYear = '2017';
918
919 SELECT DISTINCT Instructor FROM LECTURE WHERE year = 2017;
920
921 SELECT Name, Grade FROM STUDENT, GRADE WHERE GRADE.LectureCode = 1405 AND STUDENT.Login = GRADE.Login;
922
923 SELECT Year FROM Lecture WHERE Code = '1234';
924
925 SELECT Name FROM LECTURE WHERE Year IN (SELECT Year FROM LECTURE WHERE CODE = '1234');
926
927 SELECT B.name FROM STUDENT AS A, STUDENT AS B WHERE A.Name = 'Ava Alyx' AND A.Registered > B.Registered;
928
929 SELECT COUNT(DISTINCT PROF.Name) AS 'Head Teaching This Year' FROM LECTURE, DEPARTMENT, PROF WHERE Year = 2017 AND Instructor = Head AND Head = PROF.Login;
930 ```
931
932
933 %%%%% 04
934
935
936 Exercise +.#
937
938 What could be the decomposition of an attribute used to store an email address? When could that be useful?
939
940
941 Solution +.#
942
943 Name / extension.
944 To have statistics about the extensions, to sort the username by length, etc.
945
946
947 Exercise +.#
948
949 Draw the ER diagram for a "COMPUTER" entity that has one multivalued attribute "Operating\_System", a composite attribute "Devices" (decomposed into "Keyboard" and "Mouse") and an "Id" key attribute.
950
951
952 Solution +.#
953
954 \begin{tikzpicture}[node distance=7em]
955 \node[entity] (computer) {COMPUTER};
956 \node[attribute] (pid) [left of=computer] {\key{Id}} edge (computer);
957 \node[multi attribute] (os) [above of=computer] {Operating\_System} edge (computer);
958 \node[attribute] (devices) [right of=computer] {Devices} edge (computer);
959 \node[attribute] (mouse) [above right of=devices] {Mouse} edge (devices);
960 \node[attribute] (keyboard) [right of=devices] {Keyboard} edge (devices);
961 \end{tikzpicture}
962
963
964 Exercise +.#
965
966 Draw the ER diagram for a "CELLPHONE" entity that has a composite attribute "Plan" (decomposed into "Carrier" and "Price"), a "Mobile\_identification\_number" key attribute, and a multi-valued "App\_Installed" attribute.
967
968
969 Solution +.#
970
971 \begin{tikzpicture}[node distance=7em]
972 \node[entity] (cellphone) {CELLPHONE};
973 \node[attribute] (mid) [left of=cellphone] {\key{MIN}} edge (cellphone);
974 \node[multi attribute] (app) [above of=cellphone] {App\_Installed} edge (cellphone);
975 \node[attribute] (plan) [right of=cellphone] {Plan} edge (cellphone);
976 \node[attribute] (carrier) [above right of=plan] {Carrier} edge (plan);
977 \node[attribute] (price) [right of=plan] {Price} edge (plan);
978 \end{tikzpicture}
979
980
981
982 Exercise +.#
983
984 Name one difference between a primary key in the relational model, and a key attribute in the ER model.
985
986
987 Solution +.#
988
989 There can be more than one key in the ER model.
990
991
992 Exercise +.#
993
994 What is the difference between an entity type and a weak entity type?
995
996
997 Solution +.#
998
999 The weak entity type doesn't have a primary key.
1000
1001
1002 Exercise +.#
1003
1004 What is the degree of a relationship type?
1005
1006
1007 Solution +.#
1008
1009 The number of participating entity types.
1010
1011
1012 Exercise +.#
1013
1014 What is a self-referencing, or recursive, relationship type? Give two examples.
1015
1016
1017 Solution +.#
1018
1019 A relationship type where the same entity type participates more than once.
1020 On rooms, "is to the left of", on persons, "is married to".
1021
1022
1023 Exercise +.#
1024
1025 What does it mean for a binary relationship type "Owner" between entity types "Person" and "Computer" to have a cardinality ration $M:N$?
1026
1027
1028 Solution +.#
1029
1030 That a person can own multiple computers, and that a computer can have multiple owners.
1031
1032
1033 Exercise +.#
1034
1035 What are the two possible structural constraints on a relationship type?
1036
1037
1038 Solution +.#
1039
1040 Cardinality ration and participation constraints.
1041
1042
1043 Exercise +.#
1044
1045 Under what condition(s) can an attribute of a binary relationship type be migrated to become an attribute of one of the participating entity type?
1046
1047
1048 Solution +.#
1049
1050 When the cardinality is $1 : N$, $1 : 1$ or $N : 1$.
1051
1052
1053 Exercise +.#
1054
1055 What is a partial key?
1056
1057
1058 Solution +.#
1059
1060 For a weak entity attribute, it is the attribute that can uniquely identify weak entites that are related to the same owner entity.
1061
1062
1063 Exercise +.#
1064
1065 For the following binary relationships, suggest cardinality ratios based on the common-sense meaning of the entity types.
1066
1067 **Entity 1** | **Cardinality Ratio** | **Entity 2** |
1068 | --- | :---: | --- |
1069 STUDENT | | MAJOR
1070 CAR | | TAG
1071 INSTRUCTOR | | LECTURE
1072 INSTRUCTOR | | OFFICE
1073 COMPUTER | | OPERATING\_SYSTEM
1074
1075
1076 Solution +.#
1077
1078 N:1 , 1 : 1, 1 : N , 1:N, M : N
1079
1080
1081 Exercise +.#
1082
1083 Give an example of a binary relationship type of cardinality $1 : N$.
1084
1085
1086 Solution +.#
1087
1088 SUPERVISION, a recursive relationship on EMPLOYEE.
1089
1090
1091 Exercise +.#
1092
1093 Give an example of a binary relationship type of cardinality $N:1$, and draw the corresponding diagram (you don't have to include details on the participating entity types).
1094
1095
1096 Solution +.#
1097
1098 \begin{tikzpicture}[node distance=7em]
1099 \node[relationship] (contains){BELONGS};
1100 \node[entity] (burger) [left = 1cm of contains] {HAND} edge node[above] {$N$} (contains);
1101 \node[entity] (ingredient) [right = 1cm of contains] {PERSON} edge node[above]{$1$} (contains);
1102 \end{tikzpicture}
1103
1104
1105
1106 Exercise +.#
1107
1108 Draw an ER diagram with a single entity type, with two stored attributes and one derived attribute. In your answer, it should be clear that the value for the derived attribute will always be obtained from the value(s) for the other attribute(s).
1109
1110
1111 Solution +.#
1112
1113
1114 \begin{tikzpicture}[node distance=7em]
1115 \node[entity] (person) {PERSON};
1116 \node[attribute] (ssn) [left of=person] {\key{SSN}} edge (person);
1117 \node[attribute] (dob) [above of=person] {Date\_Of\_Birth} edge (person);
1118 \node[derived attribute] (age) [right of=person] {Age} edge (person);
1119 \end{tikzpicture}
1120
1121
1122
1123 Exercise +.#
1124
1125 Draw an ER diagram expressing the total participation of an entity type "BURGER" in a binary relation "CONTAINS" between "BURGER" and "INGREDIENT".
1126 What would be the ratio of such a relation?
1127
1128
1129 Solution +.#
1130
1131 \begin{tikzpicture}[node distance=7em]
1132 \node[relationship] (contains){CONTAINS};
1133 \node[entity] (burger) [left = 1cm of contains] {BURGER} edge[total] node[above] {$N$} (contains);
1134 \node[entity] (ingredient) [right = 1cm of contains] {INGREDIENT} edge node[above]{$M$} (contains);
1135 \end{tikzpicture}
1136
1137
1138 Exercise +.#
1139
1140 Convert the following ER diagram into a relational model:
1141
1142 \begin{tikzpicture}[node distance=7em]
1143 \node[relationship] (contains){STAYS\_AT};
1144 \node[entity] (person) [above = 1cm of contains] {PERSON} edge node[right] {$N$} (contains);;
1145 \node[attribute] (ssn) [left of=person] {\key{SSN}} edge (person);
1146 \node[attribute] (dob) [above = .5cm of person] {Date\_Of\_Birth} edge (person);
1147 \node[entity] (burger) [below of= contains] {PLACE} edge node[right] {$1$} (contains);
1148 \node[attribute] (dob) [below = .5cm of burger] {\key{Address}} edge (burger);
1149 \node[attribute] (ssn) [left of=burger] {Rooms} edge (burger);
1150 \end{tikzpicture}
1151
1152
1153 Solution +.#
1154
1155 \begin{tikzpicture}[node distance=7em]
1156 \node[relationship] (contains){CONTAINS};
1157 \node[entity] (burger) [left = 1cm of contains] {BURGER} edge[total] node[above] {$N$} (contains);
1158 \node[entity] (ingredient) [right = 1cm of contains] {INGREDIENT} edge node[above]{$M$} (contains);
1159 \end{tikzpicture}
1160
1161
1162 Exercise +.#
1163
1164 Why do weak entity type have a total participation constraint?
1165
1166
1167 Solution +.#
1168
1169 Otherwise, we couldn't identify entities in it without owner entity.
1170
1171 Problem +.#
1172
1173
1174 Consider the ER schema for the MOVIES database in Figure~\ref{fig:movies}.
1175
1176 \begin{figure}
1177 \begin{tikzpicture}
1178 \node (a) at (0,0) {\includegraphics[page=1,width=1\textwidth]{img/te.pdf}};
1179 \fill[white] (-8.3, 6.5) rectangle (-3.5, 4);
1180 \end{tikzpicture}
1181 \caption{An ER diagram for a MOVIES database schema.} \label{fig:movies}
1182 \end{figure}
1183
1184 Assume that MOVIES is a populated database.
1185 ACTOR is used as a gender-netral term.
1186 Given the constraints shown in the ER schema, respond to the following statements with \emph{True} or \emph{False}.
1187 Justify each answer.
1188
1189 #. There are no actors in this database that have been in no movies.
1190 #. There might be actors who have acted in more than ten movies.
1191 #. Some actors could have done a lead role in multiple movies.
1192 #. A movie can have only a maximum of two lead actors.
1193 #. Every director have to have been an actor in some movie.
1194 #. No producer has ever been an actor.
1195 #. A producer cannot be an actor in some other movie.
1196 #. There could be movies with more than a dozen actors.
1197 #. Producers can be directors as well.
1198 #. A movie can have one director and one producer.
1199 #. A movie can have one director and several producers.
1200 #. There could be some actors who have done a lead role, directed a movie, and produced some movie.
1201 #. It is impossible for a director to play in the movie (s)he directed.
1202
1203
1204
1205 Solution +.#
1206
1207 #. true
1208 #. true
1209 #. true
1210 #. true
1211 #. false
1212 #. false
1213 #. false
1214 #. true
1215 #. true
1216 #. true
1217 #. true
1218 #. true
1219 #. false
1220
1221
1222 Problem +.#
1223
1224 Draw the ER diagram for the following situation:
1225 A car-insurance company wants to have a database of accidents.
1226 An accident involves cars, drivers, and it has several aspects: the moment and place where it took place, the amount of damages, and a (unique) report number.
1227 A car has a license, a model, a year, and an owner.
1228 A driver has an id, an age, a name, and an address.
1229
1230 One of the interesting choice is: should "accident" be an entity type or a relationship type?
1231
1232 Solution +.#
1233
1234 \includegraphics[page=1,width=1\textwidth]{img/p.pdf}
1235
1236 OR
1237
1238
1239
1240 \begin{tikzpicture}[node distance=7em]
1241 \node[entity] (person) {Person};
1242 \node[attribute] (pid) [left of=person] {\key{id}} edge (person);
1243 \node[attribute] (name) [above left of=person] {Name} edge (person);
1244 \node[attribute] (address) [below left of=person] {address} edge (person);
1245
1246 \node[relationship] (owns) [above right of=person] {Owns} edge node[above, sloped]{$M$} (person);
1247 \node[entity] (car) [above right of=owns] {Car} edge node[above, sloped]{$N$} (owns);
1248 \node[attribute] (licence) [above left of=car] {\key{licence}} edge (car);
1249 \node[attribute] (model) [above of =car] {model} edge (car);
1250 \node[attribute] (year) [above right of =car] {year} edge (car);
1251
1252 \node[relationship] (accident) [right = 5cm of person] {Accident} edge[total] node[above, sloped]{$M$} (person);
1253 \node[attribute] (report_number) [below of = accident] {\key{Report Number}} edge (accident);
1254 \node[attribute] (time) [right of = accident] {Time} edge (accident);
1255 \node[attribute] (place) [below right of = accident] {Place} edge (accident);
1256 \node[attribute] (damage_amount) [above right of = accident] {Damage\_Amount} edge (accident);
1257
1258 \draw (car) edge[total] node[above, sloped]{$N$} (accident);
1259 \end{tikzpicture}
1260
1261
1262
1263 Problem +.#
1264
1265
1266 Apply the ER-to-Relation mapping to your ER diagram from the previous problem.
1267
1268
1269 %%% 05
1270
1271
1272 Exercise +.#
1273
1274 What is insertion anomaly? Give an example.
1275
1276
1277 Solution +.#
1278
1279
1280 When you have to invent a primary key or add a lot of `NULL` value to be able to add a tuple.
1281 I want to add a room in my DB, but the only place where rooms are listed are as an attribute on a Instructor table, so I have to "fake" an instructor to add a room.
1282
1283
1284 Exercise +.#
1285
1286 Why should we avoid attributes whose value will often be `NULL`?
1287 Can the usage of `NULL` be completely avoided?
1288
1289
1290 Solution +.#
1291
1292 Because they waste space, and because they are ambiguous (N/A, or unknown, or not communicated?).
1293 No, it is necessary sometimes.
1294
1295
1296 Exercise +.#
1297
1298 Consider the following relation:
1299
1300 \begin{tabular}{p{3em} l}
1301 & PROF(\underline{SSN}, Name, Department, Bike\_brand)
1302 \end{tabular}
1303
1304 Why is it a poor design to have a "Bike\_brand" attribute in such a relation?
1305 How should we store this information?
1306
1307
1308 Solution +.#
1309
1310 Because it will be `NULL` most of the time.
1311 In a separate table.
1312
1313
1314 Exercise +.#
1315
1316 Consider the following relation:
1317
1318 \begin{tabular}{p{3em} l}
1319 & STUDENT(\underline{SSN}, Name, \(…\), Sibling\_On\_Campus)
1320 \end{tabular}
1321
1322 Why is it a poor design to have a "Sibling\_On\_Campus" attribute in such a relation?
1323 How should we store this information?
1324
1325
1326 Solution +.#
1327
1328 Because it will be `NULL` most of the time, and because students could have more than one sibling on campus.
1329 In a separate table.
1330
1331
1332 Exercise +.#
1333
1334 Consider the following relational database schema:
1335
1336 \begin{tabular}{p{3em} l}
1337 & STUDENT(\underline{Login}, Name, \(…\), Major, Major\_Head)\\
1338 & DEPARTMENT(\underline{Code}, Name, Major\_Head)
1339 \end{tabular}
1340
1341 Assuming that "Major" is a foreign key referencing "DEPARTMENT.Code", what is the problem with that schema? How could you address it?
1342
1343
1344 Solution +.#
1345
1346 Major\_Head will give update anomalies.
1347 By putting the Head of the department in the DEPARTMENT relation only, i.e., removing it from STUDENT.
1348
1349
1350 Exercise +.#
1351
1352 Consider the relation \(R(A , B, C, D, E, F)\) and the following functional dependencies:
1353
1354 #. \(F \to \{D, C\}, D \to \{B, E\}, \{B, E\} \to A\)
1355 #. \(\{A, B\} \to \{C, D\}, \{B, E\} \to F\)
1356 #. \(A \to \{C, D\}, E \to F, D \to B\)
1357
1358 For each set of functional dependency, give a key for \(R\). We want a key, so it has to be minimal.
1359
1360
1361 Solution +.#
1362
1363 #. \(F\)
1364 #. \(\{A, B, E\}\)
1365 #. \(\{A, E\}\)
1366
1367
1368 Exercise +.#
1369
1370 Consider the relation \(R(A, B, C, D, E, F)\) and the following functional dependencies:
1371 \[ A \to \{D, E\}, D \to \{B, F\}, \{B, E\} \to A, \{A,C\} \to \{B, D, F\}, A \to F\]
1372 Answer the following:
1373
1374 #. How many candidate keys is there? List them.
1375 #. How many transitive dependencies can you find? Give them and justify them.
1376
1377
1378 Solution +.#
1379
1380 #. \(\{A, C\}\),
1381 #. \(A \to F\) by \(A \to D, D\to F\).
1382
1383
1384 Exercise +.#
1385
1386 Consider the relation \(R(A, B, C, D)\) and answer the following:
1387
1388 #. If \(\{A, B\}\) is the only key, is \(\{A, B\} \to \{C,D\}, \{B, C\} \to D\) a 2NF? List the nonprime attributes and justify.
1389 #. If \(\{A, B, C\}\) is the only key, is \(A \to \{B, D\}, \{A, B, C\} \to D\) a 2NF? List the nonprime attributes and justify.
1390
1391
1392 Solution +.#
1393
1394 #. Yes. \(C\) and \(D\) are non prime, and they fully depend on \(\{A,B\}\).
1395
1396 #. No. \(D\) is the only non prime, and it depends only on \(A\).
1397
1398
1399 Exercise +.#
1400
1401 Consider the relation \(R(A, B, C, D, E, F)\) with candidate keys \(\{A, B\}\) and \(C\). Answer the following:
1402
1403 #. What are the prime attributes in \(R\)?
1404 #. Is \(\{C,D\} \to E\) a fully functional dependency?
1405 #. Write a set of functional dependencies containing at least one transitive depency, and justify your answer.
1406
1407
1408 Solution +.#
1409
1410 #. \(A,B,C\)
1411 #. No, because we can remove \(D\),
1412 #. \(A \to D\), \(D \to E\) and \(A \to E\)
1413
1414
1415 Exercise +.#
1416
1417 Consider the relation \(R(A , B, C, D, E)\) and the following functional dependencies:
1418
1419 #. \(C \to D, \{C, B\} \to A, A \to \{B, C, D\}, B \to E\)
1420 #. \(\ A \to \{C, D\}, C \to B, D \to E, \{E, C\} \to A\)
1421 #. \(\{A, B\} \to D, D \to \{B, C\}, E \to C\)
1422
1423 For each one, give one candidate key for \(R\).
1424
1425
1426 Solution +.#
1427
1428 #. \(\{B, C\}\), \(A\)
1429 #. \(A\), \(\{C,E\}\),
1430 #. \(\{A, D, E\}\), \(\{A, B, E\}\)
1431
1432
1433 Exercise +.#
1434
1435 Consider the relation \(R(A, B, C, D, E)\) and answer the following:
1436
1437 1. If \(\{A, B\}\) is the primary key, is \(B \to E, C \to D\) a 2NF?% List the nonprime attributes and justify.
1438 2. If \(\{A\}\) is the primary key, is \(B \to C, B \to D\) a 2NF?% List the nonprime attributes and justify.
1439
1440
1441 Solution +.#
1442
1443 1. No. \(C, D, E\), and \(E\) has a partial relation to \(B\)
1444
1445 2. Yes. Since the primary key is a singleton, it is obvious.
1446
1447 Exercise +.#
1448
1449 Consider the relation \(R(A, B, C, D, E, F)\), and let \(\{B, D\}\) be the primary key, and have additionnaly the functional dependencies \(\{A, D\} \to E, C \to F\).
1450 This relation is not in 3NF, can you tell why?
1451
1452
1453 Solution +.#
1454
1455 \(\{B, D\} \to C \to F\) breaks the 3NF.
1456
1457 Exercise +.#
1458
1459 Consider the relation \(R(A, B, C, D)\) and answer the following:
1460
1461 1. If \(A\) is the only key, is \(A \to \{B,C,D\}, \{A, B\} \to C, \{B, C\} \to D\) a 3NF? List the nonprime attributes and justify.
1462 2. If \(B\) is the only key, is \(B \to \{A, C, D\}, A \to \{C, D\}, \{A, C\} \to D\) a 3NF? List the nonprime attributes and justify.
1463
1464
1465 Solution +.#
1466
1467 1. No. \(B\), \(C\) and \(D\) are non prime, \(A \to \{B,C\} \to D\) breaks the 3NF.
1468
1469 2. No. \(A\), \(B\) and \(D\) are non prime, \(B \to \{A,C\} \to D\) breaks the 3NF.
1470
1471
1472 Problem +.#
1473 Consider the following relation, and its functional dependencies:
1474
1475 \begin{tabular}{l}
1476 CAR\_SALE(\underline{Car\_no}, Date\_sold, \underline{Salesman\_no}, Commission, Discount\_amt)
1477 \end{tabular}
1478
1479 \begin{tabular}{rcl}
1480 \{Car\_no, Salesman\_no\} & \(\to\)& \{Date\_sold, Commission, Discount\_amt\}\\
1481 Date\_sold & \(\to\)& Discount\_amt\\
1482 Salesman\_no & \(\to\)& Commission
1483 \end{tabular}
1484
1485 Based on the given primary key, is this relation in 1NF, 2NF, or 3NF? Why or why not? Normalize it completely. Then draw an ER diagram for the resulting schema.
1486
1487
1488 Solution +.#
1489
1490 This relation satisfies 1NF but not 2NF (Car\_no \(\to\) Date\_sold and Salesman\_no \(\to\) Commission so these two attributes are not fully functional dependent on the primary key) and not 3NF.
1491
1492 To normalize,
1493
1494 2NF:
1495 \begin{tabular}{l}
1496 Car\_Sale1(Car\_no, Date\_sold, Discount\_amt)\\
1497 Car\_Sale2(Car\_no, Salesman\_no)\\
1498 Car\_Sale3(Salesman\_no,Commission)
1499 \end{tabular}
1500 3NF:
1501 \begin{tabular}{c}
1502 Car\_Sale1-1(Car\_no, Date\_sold)\\
1503 Car\_Sale1-2(Date\_sold, Discount\_amt)\\
1504 Car\_Sale2(Car\_no, Salesman\_no)\\
1505 Car\_Sale3(Salesman\_no,Commission)
1506 \end{tabular}
1507
1508
1509 Problem +.#
1510
1511 This problem asks you to convert business statements into dependencies.
1512 Consider the following relation:
1513 \begin{center}
1514 BIKE(Serial\_no, Manufacturer, Model, Batch, Wheel\_size, Retailer)
1515 \end{center}
1516
1517 Each tuple in the relation BIKE contains information about a bike with a serial number, made by a manufacturer, with a particular model number, released in a certain batch, which has a certain wheel size, and is sold by a certain retailer.
1518 \begin{itemize}
1519 \item Write each of the following dependencies as a functional dependency (I give you the first one as an example):
1520
1521 1. A retailer can't have two bikes of the same model from different batches.
1522
1523 \emph{solution:} \{Retailer, Model\} \(\to\) Batch
1524
1525 2. The manufacturer and serial number uniquely identifies the bike and where it is sold.
1526 3. A model number is registered by a manufacturer and therefore can't be
1527 used by another manufacturer.
1528 4. All bikes in a particular batch are of the same model.
1529 5. All bikes of a certain model have
1530 the same wheel size.
1531
1532 \item Based on those statements, what could be a key for this relation?
1533 \item Assuming all those functional dependencies hold, and taking the primary key you identified at the previous step, what is the degree of normality of this relation? Justify your answer.
1534 \end{itemize}
1535
1536
1537 Solution +.#
1538
1539 \begin{itemize}
1540 \item
1541 1. \{ Manufacturer, Serial\_no \} \(\to\) \{ Model, Batch, Wheel\_size, Retailer\}
1542 2. Model \(\to\) Manufacturer
1543 3. Batch \(\to\) Model
1544 4. \{Model, Manufacturer\} \(\to\) Wheel\_size
1545
1546 \item \{Manufacturer, Serial\_no \}
1547 \item If every attribute is atomic, it is in second nf.
1548 \{ Manufacturer, Serial\_no \} \(\to\) Batch \(\to\)Model breaks the 3NF.
1549
1550 \end{itemize}
1551
1552
1553
1554 Problem +.#
1555
1556 Consider the relations \(R\) and \(T\) below, and their functional dependencies (on top of the one induced by the primary keys):
1557
1558 \begin{tabular}{l}
1559 R(\underline{EventId}, \underline{Email}, Time, Date, Location, Status)\\
1560 T(\underline{Invno}, Subtotal, Tax, Total, Email, Lname, Fname, Phone)
1561 \end{tabular}
1562
1563 \begin{tabular}{r c l}
1564 \{EventId, Email\} & \(\to\) & Status\\
1565 EventId & \(\to\) & \{Time, Date, Location\}\\
1566 Invno & \(\to\) & \{Subtotal, Tax, Total, Email\}\\
1567 Email & \(\to\) & \{Fname, Lname, Phone\}
1568 \end{tabular}
1569
1570 Normalize the relations to 2NF and 3NF. Show all relations at each stage (2NF and 3NF) of the normalization process.
1571
1572
1573 Solution +.#
1574
1575 TO BE WRITTEN
1576
1577 48
1578 49
1579 50 Problem +.# Problem +.#
1580 51
1581 Consider the following relation for published books:
1582 \begin{center}
1583 BOOK (Book\_title, Book\_type, Author\_name, List\_price, Author\_affil, Publisher)
1584 \end{center}
1585
1586 Suppose we have the following dependencies:
1587
1588 \begin{center}
1589 \begin{tabular}{r c l}
1590 Book\_title & \(\to\) & \{ Publisher, Book\_type \}\\
1591 Book\_type & \(\to\) & List\_price\\
1592 Author\_name & \(\to\) & Author\_affil
1593 \end{tabular}
1594 \end{center}
1595
1596 \begin{itemize}
1597 \item What would be a suitable key for this relation?
1598 \item How could this relation not be in first normal form? Explain your answer.
1599 \item This relation is not in second normal form: explain why and normalize it.
1600 \item Is the relations you obtained at the previous step in third normal form? Explain why, and normalize them if needed.
1601 \end{itemize}
1602
1603
1604
1605 Solution +.#
1606
1607 \begin{itemize}
1608 \item \{Book Title, Author Name\}
1609 \item If an attribute is composite or multi-valued.
1610 \item Because of \{ Book\_title \}\(\to\) \{ Publisher, Book\_type \}.
1611 We can normalize it as
1612 (Book Title, Publisher, Book Type, List Price), (Author Name, Author Affiliation), (Author Name, Book Title).
1613 \item Because of \{Book title\} \(\to\) \{ Book\_type\} \(\to\) \{ List\_price\}\\
1614 (Book Title, Publisher, Book Type) and (Book Type, List Price), (Author Name, Author Affiliation), (Author Name, Book Title).
1615
1616 \end{itemize}
1617 52
1618 53
1619 54 %%% 06 %%% 06
1620 55
1621 56
1622 Exercise +.#
1623
1624 Consider the relation \(R(A, B, C, D, E)\) and the functional dependencies \( \{A, B\} \to C, B \to D, C \to E\).
57 Exercise +.#
58 ~ Consider the relation \(R(A, B, C, D, E)\) and the functional dependencies \( \{A, B\} \to C, B \to D, C \to E\).
1625 59 Answer the following: Answer the following:
1626 60
1627 61 1. \(A\) by itself is not a primary key, but what is the only key that contains \(A\)? 1. \(A\) by itself is not a primary key, but what is the only key that contains \(A\)?
 
... ... Solution +.#
1643 77
1644 78
1645 79
1646 Exercise +.#
1647
1648 What are the two different categories of U.M.L. diagram?
80 Exercise +.#
81 ~ What are the two different categories of U.M.L. diagram?
1649 82
1650 83
1651 Solution +.#
1652
1653 Behaviour and structure
84 Solution +.#
85 ~ Behaviour and structure
1654 86
1655 87
1656 Exercise +.#
1657
1658 Can a \texttt{C++} developer working on Linux and a \texttt{Java} developer working on MacOS use the same class diagram as a basis to write their programs?
88 Exercise +.#
89 ~ Can a \texttt{C++} developer working on Linux and a \texttt{Java} developer working on MacOS use the same class diagram as a basis to write their programs?
1659 90 Justify your answer. Justify your answer.
1660 91
1661 92
1662 Solution +.#
1663
1664 Yes, U.M.L. diagram is language-independent and platform-independent.
1665
93 Solution +.#
94 ~ Yes, U.M.L. diagram is language-independent and platform-independent.
1666 95
1667 Exercise +.#
1668 96
1669 What kind of diagram should we use if we want to \(…\)
97 Exercise +.#
98 ~ What kind of diagram should we use if we want to \(…\)
1670 99
1671 100 1. describe the functional behavior of the system as seen by the user? 1. describe the functional behavior of the system as seen by the user?
1672 101 2. capture the flow of messages in a software? 2. capture the flow of messages in a software?
1673 102 3. represent the workflow of actions of an user? 3. represent the workflow of actions of an user?
1674 103
1675 Solution +.#
1676
1677 1. Use-case
104 Solution +.#
105 ~ 1. Use-case
1678 106 2. Sequence diagram 2. Sequence diagram
1679 107 3. Activity diagram 3. Activity diagram
1680 108
1681 Exercise +.#
109 Exercise +.#
110 ~ Name two reasons why one would want to use a U.M.L. class diagram over an E.-R. diagram to represent a conceptual schema.
1682 111
1683 Name two reasons why one would want to use a U.M.L. class diagram over an E.-R. diagram to represent a conceptual schema.
1684 112
1685
1686 Solution +.#
1687
1688 To use direction for association, to have a common language with someone less knowledgeable of other diagrammatic notations.
113 Solution +.#
114 ~ To use direction for association, to have a common language with someone less knowledgeable of other diagrammatic notations.
1689 115 For the concept of integration. For the concept of integration.
1690 116
1691 117
1692 Exercise +.#
1693
1694 Consider the following diagram:
118 Exercise +.#
119 ~ Consider the following diagram:
1695 120
1696 121 \begin{tikzpicture}[scale = 0.8] \begin{tikzpicture}[scale = 0.8]
1697 122 \begin{class}[text width=7cm]{Flight}{0,0} \begin{class}[text width=7cm]{Flight}{0,0}
 
... ... Give the number of attributes for both classes, and suggest two operations for t
1716 141 Discuss the multiplicities: why did the designer picked those values? Discuss the multiplicities: why did the designer picked those values?
1717 142
1718 143
1719 Solution +.#
1720
1721 \(5\) and \(4\).
144 Solution +.#
145 ~ \(5\) and \(4\).
1722 146
1723 147 getLastFlightNumber() : Integer getLastFlightNumber() : Integer
1724 148
 
... ... A flight could be assigned to no plane, and a plane could not be assigned to a f
1729 153 A plane can be assigned to multiple (or no) flights, but a flight must have at most one plane (and could have none). A plane can be assigned to multiple (or no) flights, but a flight must have at most one plane (and could have none).
1730 154
1731 155
1732 Exercise +.#
1733
1734 Briefly explain the difference between an aggregation and a composition association.
1735
156 Exercise +.#
157 ~ Briefly explain the difference between an aggregation and a composition association.
1736 158
1737 Solution +.#
1738 159
1739 Aggregation: associated class can have an existence of its own.
160 Solution +.#
161 ~ Aggregation: associated class can have an existence of its own.
1740 162
1741 163 Composition association: class doesn't exist without the association. Composition association: class doesn't exist without the association.
1742 164
1743 165
1744 Exercise +.#
1745
1746 How is generalization (or inheritance) represented in a U.M.L. class diagram?
166 Exercise +.#
167 ~ How is generalization (or inheritance) represented in a U.M.L. class diagram?
1747 168 Why is such a concept useful? Why is such a concept useful?
1748 169
1749 170
1750 Solution +.#
1751
1752 \tikz{\draw[>=open triangle 60,->] (0,0) to (1,0);}
171 Solution +.#
172 ~ \tikz{\draw[>=open triangle 60,->] (0,0) to (1,0);}
1753 173 Because it avoids redundancy. Because it avoids redundancy.
1754 174
1755 175
1756 Exercise +.#
1757
1758 Convert the following E.R. diagram into a U.M.L. class diagram:
176 Exercise +.#
177 ~ Convert the following E.R. diagram into a U.M.L. class diagram:
1759 178
1760 179 \begin{tikzpicture}[node distance=8em] \begin{tikzpicture}[node distance=8em]
1761 180 \node[entity] (person) {PILOT}; \node[entity] (person) {PILOT};
 
... ... Note that a car can have at most one driver, \(N\) passengers, \(N\) insurances,
1808 227 2. Convert that E.-R. diagram to a relational database schema. 2. Convert that E.-R. diagram to a relational database schema.
1809 228 3. Convert the E.-R. diagram to a U.M.L. class diagram. Comparing Figure 7.16 with Figure 7.2 from your textbook should guide you. 3. Convert the E.-R. diagram to a U.M.L. class diagram. Comparing Figure 7.16 with Figure 7.2 from your textbook should guide you.
1810 229
1811 Solution +.#
1812
1813 For "Car", we need to create an attribute, like "vin".
230 Solution +.#
231 ~ For "Car", we need to create an attribute, like "vin".
1814 232 For "Car Insurance", "Policy Number" is perfect. For "Car Insurance", "Policy Number" is perfect.
1815 233
1816 234 \colorlet{lightgray}{gray!20} \colorlet{lightgray}{gray!20}
 
... ... In this exercise, we will install and explore the basic functionalities of MySQL
1943 361
1944 362 Problem +.# Problem +.#
1945 363
1946 \emph{This problem requires you to have successfully completed Problem~\ref{probMYSQLW} and Problem~\ref{probERtoREL}.}
364 \emph{This problem requires you to have successfully completed Problem~ \ref{probMYSQLW} and Problem~ \ref{probERtoREL}.}
1947 365
1948 Using the relational database schema you obtained in question~\ref{ERtoREL} of Problem~\ref{probERtoREL}, write the \texttt{SQL} implementation of that database.
1949 Then, using MySQL Workbench, use the "Reverse Engineering" function to obtain a E.E.R. diagram of your database, and compare it with the U.M.L. diagram you draw in question~\ref{ERtoUML} of Problem~\ref{probERtoREL}.
366 Using the relational database schema you obtained in question~ \ref{ERtoREL} of Problem~ \ref{probERtoREL}, write the \texttt{SQL} implementation of that database.
367 Then, using MySQL Workbench, use the "Reverse Engineering" function to obtain a E.E.R. diagram of your database, and compare it with the U.M.L. diagram you draw in question~ \ref{ERtoUML} of Problem~ \ref{probERtoREL}.
1950 368 Apart from the difference inherent to the nature of the diagram (i.e., U.M.L. Vs E.E.R.), how are they the same? How do they differ? Is the automated tool as efficient and accurate as you are? Apart from the difference inherent to the nature of the diagram (i.e., U.M.L. Vs E.E.R.), how are they the same? How do they differ? Is the automated tool as efficient and accurate as you are?
1951 369
1952 370
1953 Solution +.#
1954
1955 <!--
371 Solution +.#
372 ~ <!--
1956 373 \inputminted{sql}{include/sol.sql} \inputminted{sql}{include/sol.sql}
1957 374 \includegraphics{include/mysql_workbench_drawing-crop} \includegraphics{include/mysql_workbench_drawing-crop}
1958 375 --> -->
1959 376
1960 377 <!-- <!--
1961 ```include
378 ~~~include
1962 379 include/sol.sql include/sol.sql
1963 ```
380 ~~~
381
1964 382 --> -->
1965 383
1966 384 **Code à inclure ici** **Code à inclure ici**
 
... ... include/sol.sql
1970 388 %%% 07 %%% 07
1971 389
1972 390
1973 Exercise +.#
1974
1975 What are the technologies that makes it possible for a Java application to communicate with a DBMS?
1976
1977
1978 Solution +.#
1979
1980 API + driver
1981
1982
1983 Exercise +.#
391 Exercise +.#
392 ~ What are the technologies that makes it possible for a Java application to communicate with a DBMS?
1984 393
1985 What JDBC method do you call to get a connection to a database?
1986 394
1987 Solution +.#
395 Solution +.#
396 ~ API + driver
1988 397
1989 DriverManager.getConnection()
1990 398
399 Exercise +.#
400 ~ What JDBC method do you call to get a connection to a database?
1991 401
1992 Exercise +.#
402 Solution +.#
403 ~ DriverManager.getConnection()
1993 404
1994 Briefly explain what the \texttt{next()} method from the \texttt{ResultSet} class does, and what is its return type.
1995 405
1996 Solution +.#
406 Exercise +.#
407 ~ Briefly explain what the \texttt{next()} method from the \texttt{ResultSet} class does, and what is its return type.
1997 408
1998 It checks if there is data to read, and if move the cursor reads it.
409 Solution +.#
410 ~ It checks if there is data to read, and if move the cursor reads it.
1999 411 It returns a Boolean. It returns a Boolean.
2000 412
2001 413
2002 Exercise +.#
414 Exercise +.#
415 ~ How do you submit a `SELECT` statement to the DBMS?
2003 416
2004 How do you submit a `SELECT` statement to the DBMS?
2005 417
418 Solution +.#
419 ~ Using
2006 420
2007 Solution +.#
2008
2009 Using
2010
2011 ```java
421 ~~~{.java}
2012 422 .executeQuery(strSelect) .executeQuery(strSelect)
2013 ```
2014
423 ~~~
2015 424
2016 Exercise +.#
425 Exercise +.#
426 ~ Where is a ResultSet object's cursor initially pointing? How do you move the cursor forward in the result set?
2017 427
2018 Where is a ResultSet object's cursor initially pointing? How do you move the cursor forward in the result set?
2019 428
429 Solution +.#
430 ~ Before the first line.
2020 431
2021 Solution +.#
2022
2023 Before the first line.
2024
2025 ```java
432 ~~~{.java}
2026 433 next() next()
2027 ```
434 ~~~
2028 435
2029 436 method method
2030 437
2031 Exercise +.#
2032
2033 Give three navigation methods provided by `ResultSet`.
438 Exercise +.#
439 ~ Give three navigation methods provided by `ResultSet`.
2034 440
2035 441
2036 Solution +.#
2037
2038 `first()`
442 Solution +.#
443 ~ `first()`
2039 444 `last()` `last()`
2040 445 `next()` `next()`
2041 446 `previous()` `previous()`
 
... ... Solution +.#
2043 448 `absolute(row)` method. `absolute(row)` method.
2044 449
2045 450
2046 Exercise +.#
451 Exercise +.#
452 ~ Explain this JDBC URL format:
2047 453
2048 Explain this JDBC URL format:
2049
2050 ```java
454 ~~~{.java}
2051 455 jdbc:mysql://localhost:3306/HW_NewDB?createDatabaseIfNotExist=true&useSSL=true jdbc:mysql://localhost:3306/HW_NewDB?createDatabaseIfNotExist=true&useSSL=true
2052 ```
2053
456 ~~~
2054 457
2055 Solution +.#
2056
2057 Connect to localhost:3306 and create a new database if needed, and use secure connection.
2058
2059
2060 Exercise +.#
2061
2062 In what class is the `getColumnName()} method?
2063
2064
2065 Solution +.#
458 Solution +.#
459 ~ Connect to localhost:3306 and create a new database if needed, and use secure connection.
2066 460
2067 ResultSetMetaData
2068 461
462 Exercise +.#
463 ~ In what class is the `getColumnName()} method?
2069 464
2070 Exercise +.#
2071 465
2072 What is a prepared statement?
466 Solution +.#
467 ~ ResultSetMetaData
2073 468
2074 469
2075 Solution +.#
470 Exercise +.#
471 ~ What is a prepared statement?
2076 472
2077 A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.
2078 473
474 Solution +.#
475 ~ A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.
2079 476
2080 Exercise +.#
2081 477
2082 In the code below, there are \(5\) errors between line \(11\) and line \(30\). They are \emph{not} subtle Java errors (like misspelling a key word) and do not come from the DBMS (so you should assume that the password is correct, that the database exists, etc.). For each error, highlight it precisely and give a short explanation.
478 Exercise +.#
479 ~ In the code below, there are \(5\) errors between line \(11\) and line \(30\). They are \emph{not} subtle Java errors (like misspelling a key word) and do not come from the DBMS (so you should assume that the password is correct, that the database exists, etc.). For each error, highlight it precisely and give a short explanation.
2083 480
2084 ```java
481 ~~~{.java}
2085 482 import java.sql.*; import java.sql.*;
2086 483
2087 484 public class MyProg{ public class MyProg{
 
... ... ex.printStackTrace();
2118 515 } }
2119 516 } }
2120 517 } }
2121 ```
2122
2123
2124
518 ~~~
2125 519
2126 520 % %
2127 521 %METADATA %METADATA
 
... ... ex.printStackTrace();
2140 534
2141 535 This part will mainly hands on, and ask you to read code. This part will mainly hands on, and ask you to read code.
2142 536 It is important that you learn how to get a working environment for a new technology quickly, for your understanding of this lecture, for the exam, and as a CS major. It is important that you learn how to get a working environment for a new technology quickly, for your understanding of this lecture, for the exam, and as a CS major.
2143 I'll assume that you will have successfully completed those tasks by \hwDateNext, so don't wait and let me know if you had difficulties solving them.
537 I'll assume that you will have successfully completed those tasks , so don't wait and let me know if you had difficulties solving them.
2144 538
2145 539 **References:** **References:**
2146 540
 
... ... In the archive, navigate to \texttt{code/sql/}, open and read \texttt{HW\_ebooks
2156 550
2157 551 Then, open a terminal (or command-line interpreter), navigate to the folder where you stored that file (using `cd`), and type Then, open a terminal (or command-line interpreter), navigate to the folder where you stored that file (using `cd`), and type
2158 552
2159 ```bash
553 ~~~{.bash}
2160 554 mysql -u testuser -p < HW_ebookshop.sql mysql -u testuser -p < HW_ebookshop.sql
2161 ```
2162
2163
555 ~~~
2164 556
2165 557 for linux, or (something like) for linux, or (something like)
2166 558
2167 ```bash
559 ~~~{.bash}
2168 560 "C:\Program Files\MySQL\MySQL Server 5.7\bin\mysql.exe" -u testuser -p < HW_ebookshop.sql "C:\Program Files\MySQL\MySQL Server 5.7\bin\mysql.exe" -u testuser -p < HW_ebookshop.sql
2169 ```
2170
561 ~~~
2171 562
2172 563 for Windows. for Windows.
2173 564
 
... ... You can easily make sure that the database and the table were indeed created, an
2177 568
2178 569 Problem +.# Problem +.#
2179 570
2180 This exercise supposes you successfully completed Problem~\ref{qu:batch}.
571 This exercise supposes you successfully completed Problem~ \ref{qu:batch}.
2181 572 We will compile and execute your first database application, using Java and MySQL. We will compile and execute your first database application, using Java and MySQL.
2182 573 \begin{itemize} \begin{itemize}
2183 574 \item I will assume that you have MySQL installed and set-up as indicated in Homeworks \#1 and \#2. \item I will assume that you have MySQL installed and set-up as indicated in Homeworks \#1 and \#2.
 
... ... We will compile and execute your first database application, using Java and MySQ
2192 583 \item Copy that file in \texttt{code/java/}. \item Copy that file in \texttt{code/java/}.
2193 584 \end{itemize} \end{itemize}
2194 585 \item Open a terminal in that same folder, and compile \texttt{FirstProg.java}, using \item Open a terminal in that same folder, and compile \texttt{FirstProg.java}, using
2195 ```bash
2196 javac FirstProg.java
2197 ```
2198 586
587 ~~~{.bash}
588 javac FirstProg.java
589 ~~~
2199 590
2200 591 (or an equivalent command for windows). (or an equivalent command for windows).
2201 592 Normally, nothing will be printed, but a \texttt{FirstProg.class} file will be created. Normally, nothing will be printed, but a \texttt{FirstProg.class} file will be created.
2202 593 \item Now, execute that program, using \item Now, execute that program, using
2203 ```bash
2204 java -cp .:mysql-connector-java-***-bin.jar FirstProg
2205 ```
2206 594
595 ~~~{.bash}
596 java -cp .:mysql-connector-java-***-bin.jar FirstProg
597 ~~~
2207 598
2208 599 in Linux, or in Linux, or
2209 ```bash
2210 java -cp .;mysql-connector-java-***-bin.jar FirstProg
2211 ```
2212 600
601 ~~~{.bash}
602 java -cp .;mysql-connector-java-***-bin.jar FirstProg
603 ~~~
2213 604
2214 605 in Windows. in Windows.
2215 606 The \texttt{-cp} option lists the places where java should look for the class used in the program: we are explicitely asking java to use the \texttt{mysql-connector-java-***-bin.jar} executable to execute our \texttt{FirstProg} executable. The \texttt{-cp} option lists the places where java should look for the class used in the program: we are explicitely asking java to use the \texttt{mysql-connector-java-***-bin.jar} executable to execute our \texttt{FirstProg} executable.
 
... ... Try to execute \texttt{FirstProg} without that flag, and see what happens.
2217 608 \end{itemize} \end{itemize}
2218 609
2219 610
2220 Solution +.#
611 Solution +.#
2221 612
2222 ```bash
613 ~~~{.bash}
2223 614 $ java FirstProg $ java FirstProg
2224 615 java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/HW_ebookshop java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/HW_ebookshop
2225 616 at java.sql.DriverManager.getConnection(DriverManager.java:689) at java.sql.DriverManager.getConnection(DriverManager.java:689)
2226 617 at java.sql.DriverManager.getConnection(DriverManager.java:247) at java.sql.DriverManager.getConnection(DriverManager.java:247)
2227 618 at FirstProg.main(FirstProg.java:9) at FirstProg.main(FirstProg.java:9)
2228 ```
2229
2230
2231
619 ~~~
2232 620
2233 621 Problem +.# Problem +.#
2234 622
 
... ... Describe at least one common and interesting situation where this model would fa
2308 696 Problem +.# Problem +.#
2309 697 Look at the SQL code below, and then answer the following questions. Look at the SQL code below, and then answer the following questions.
2310 698
2311 ```sqlmysql
699 ~~~{.sqlmysql}
2312 700 CREATE TABLE TRAIN( CREATE TABLE TRAIN(
2313 701 Id VARCHAR(30), Id VARCHAR(30),
2314 702 Model VARCHAR(30), Model VARCHAR(30),
 
... ... ConductorId VARCHAR(20),
2327 715 Day DATE, Day DATE,
2328 716 PRIMARY KEY(TrainId, ConductorId) PRIMARY KEY(TrainId, ConductorId)
2329 717 ); );
2330 ```
2331
2332
718 ~~~
2333 719
2334 720 1. Modify the `CREATE` statement that creates the `TRAIN` table (l. 1--5), so that `Id` would be declared as the primary key. 1. Modify the `CREATE` statement that creates the `TRAIN` table (l. 1--5), so that `Id` would be declared as the primary key.
2335 721 You can write only the line(s) that need to change. You can write only the line(s) that need to change.
 
... ... Your statements should respect all the constraints (including the ones we added
2349 735
2350 736
2351 737 Problem +.# Problem +.#
2352 Suppose we have the relational model depicted in \autoref{fig:coffee}, p.~\pageref{fig:coffee}, with the indicated data in it.
738 Suppose we have the relational model depicted in \autoref{fig:coffee}, p.~ \pageref{fig:coffee}, with the indicated data in it.
2353 739
2354 740 In the following, we will assume that this model was implemented in a DBMS (MySQL or MariaDB), the primary keys being the underlined attributes, and the foreign keys as follow: In the following, we will assume that this model was implemented in a DBMS (MySQL or MariaDB), the primary keys being the underlined attributes, and the foreign keys as follow:
2355 741
 
... ... Write queries that answer the following questions (the last two are bonus):
2405 791 #. "What are the names of the providers of my dark coffees?" #. "What are the names of the providers of my dark coffees?"
2406 792
2407 793
2408 <!--
2409 OK TATA UP TO HERE
2410 -->
2411
2412 794 \begin{figure} \begin{figure}
2413 795
2414 796 **COFFEE** **COFFEE**
 
... ... and the following functional dependencies:
2479 861
2480 862 \begin{center} \begin{center}
2481 863 \begin{tabular}{r c l} \begin{tabular}{r c l}
2482 \{Zip, Brand\} & \(\to\) & \{Phone\}\\
2483 \{Brand\} & \(\to\) & \{Email\}\\
2484 \{ Brand\} & \(\to\) & \{Website\}\\
2485 \{Phone\} & \(\to\) & \{Call\_center\}
864 \{Zip, Brand\} & → & \{Phone\}\\
865 \{Brand\} & → & \{Email\}\\
866 \{ Brand\} & → & \{Website\}\\
867 \{Phone\} & → & \{Call\_center\}
2486 868 \end{tabular} \end{tabular}
2487 869 \end{center} \end{center}
2488 870
 
... ... with the following functional dependencies:
2503 885
2504 886 \begin{center} \begin{center}
2505 887 \begin{tabular}{r c l} \begin{tabular}{r c l}
2506 \{Doctor\_no, Patient\_no, Date\} & \(\to\) & \{Diagnosis\}\\
2507 \{Doctor\_no, Patient\_no, Date\} & \(\to\) & \{Treatment\}\\
2508 \{Treatment, Insurance\} & \(\to\) & \{Charge\}\\
2509 \{Patient\_no\} & \(\to\) & \{Insurance\}
888 \{Doctor\_no, Patient\_no, Date\} & → & \{Diagnosis\}\\
889 \{Doctor\_no, Patient\_no, Date\} & → & \{Treatment\}\\
890 \{Treatment, Insurance\} & → & \{Charge\}\\
891 \{Patient\_no\} & → & \{Insurance\}
2510 892 \end{tabular} \end{tabular}
2511 893 \end{center} \end{center}
2512 894
2513 #. The designer decided not to add the functional dependency \{Diagnosis\} $\to$ \{Treatment\}.
895 #. The designer decided not to add the functional dependency \{Diagnosis\} → \{Treatment\}.
2514 896 Explain what could be the designer's justification, at the level of the mini-world. Explain what could be the designer's justification, at the level of the mini-world.
2515 897 #. Identify a primary key for this relation. #. Identify a primary key for this relation.
2516 898 #. What is the degree of normalization of this relation? #. What is the degree of normalization of this relation?
 
... ... Normalize it to the third normal form if necessary.
2518 900
2519 901
2520 902
2521 Solution +.#
2522
2523 Answer:
903 Solution +.#
904 ~ Answer:
2524 905 Because there are no partial dependencies, the given relation is in 2NF already. This however is not 3NF because the Charge is a nonkey attribute that is determined by another nonkey attribute, Treatment. We must decompose further: Because there are no partial dependencies, the given relation is in 2NF already. This however is not 3NF because the Charge is a nonkey attribute that is determined by another nonkey attribute, Treatment. We must decompose further:
2525 906
2526 907 R (Doctor\_no, Patient\_no, Date, Diagnosis, Treatment) R (Doctor\_no, Patient\_no, Date, Diagnosis, Treatment)
 
... ... A quest have a name, and rewards the characters that completed it with a certain
2538 919
2539 920 Your friend came up with the following code: Your friend came up with the following code:
2540 921
2541 ```sqlmysql
922 ~~~{.sqlmysql}
2542 923 CREATE TABLE CHARACTER( CREATE TABLE CHARACTER(
2543 924 Name VARCHAR(30) PRIMARY KEY, Name VARCHAR(30) PRIMARY KEY,
2544 925 Class VARCHAR(30), Class VARCHAR(30),
 
... ... FOREIGN KEY (Completed_By) REFERENCES CHARACTER(Name)
2558 939 ); );
2559 940
2560 941 ALTER TABLE CHARACTER ADD FOREIGN KEY (Quest_Completed) REFERENCES QUEST(Id); ALTER TABLE CHARACTER ADD FOREIGN KEY (Quest_Completed) REFERENCES QUEST(Id);
2561 ```
942 ~~~
2562 943
2563 944 But there are several problems. But there are several problems.
2564 945
 
... ... A tuple in the KEYBOARD relation contains information about a computer keyboard:
2593 974
2594 975 Problem +.# Problem +.#
2595 976
2596 Consider the E.R. schema of Figure~\ref{fig:erCOUNTRY}, p.~\pageref{fig:erCOUNTRY}.
977 Consider the E.R. schema of Figure~ \ref{fig:erCOUNTRY}, p.~ \pageref{fig:erCOUNTRY}.
2597 978 Map that E.-R. diagram to a relational database schema. Map that E.-R. diagram to a relational database schema.
2598 979
2599
2600
2601 980 ~~~{.sqlmysql caption="A `SQL` Code for a Role-Playing Game"} ~~~{.sqlmysql caption="A `SQL` Code for a Role-Playing Game"}
2602 981 CREATE TABLE CHARACTER( CREATE TABLE CHARACTER(
2603 982 Name VARCHAR(30) PRIMARY KEY, Name VARCHAR(30) PRIMARY KEY,
 
... ... FOREIGN KEY (Completed_By) REFERENCES CHARACTER(Name)
2618 997 ); );
2619 998
2620 999 ALTER TABLE CHARACTER ADD FOREIGN KEY (Quest_Completed) REFERENCES QUEST(Id); ALTER TABLE CHARACTER ADD FOREIGN KEY (Quest_Completed) REFERENCES QUEST(Id);
2621 ```
1000 ~~~
1001
2622 1002 <!-- Add a label? #lst:RPG --> <!-- Add a label? #lst:RPG -->
2623 1003
2624 1004
 
... ... For this relationship, on the left-hand side is the language that borrows a word
2671 1051
2672 1052
2673 1053 Problem +.# Problem +.#
2674 Look at the relational model from Figure~\ref{fig:RelMod}, p.~\pageref{fig:RelMod}, and "reverse-engineer" it to obtain an E.-R. diagram.
1054 Look at the relational model from Figure~ \ref{fig:RelMod}, p.~ \pageref{fig:RelMod}, and "reverse-engineer" it to obtain an E.-R. diagram.
2675 1055
2676 1056
2677 1057
 
... ... When could that be useful?
2687 1067 #. What is the (object-relational) impedance mismatch? Is it an issue that can't be overcome? #. What is the (object-relational) impedance mismatch? Is it an issue that can't be overcome?
2688 1068
2689 1069
2690 Solution +.#
2691
2692 A Delete Anomaly exists when certain attributes are lost because of the deletion of other attributes.
1070 Solution +.#
1071 ~ A Delete Anomaly exists when certain attributes are lost because of the deletion of other attributes.
2693 1072
2694 1073 When storing data, it is best to use multiple data storage technologies, chosen based upon the way data is being used by individual applications or components of a single application. When storing data, it is best to use multiple data storage technologies, chosen based upon the way data is being used by individual applications or components of a single application.
2695 1074
 
... ... Note any unspecified requirements, and make appropriate assumptions to make the
2733 1112
2734 1113
2735 1114 Problem +.# Problem +.#
2736 Consider the UML diagram in Figure~\ref{fig:UML}, p.~\pageref{fig:UML}, and convert it to the relational model.
1115 Consider the UML diagram in Figure~ \ref{fig:UML}, p.~ \pageref{fig:UML}, and convert it to the relational model.
2737 1116 Don't forget to indicate primary and foreign keys. Don't forget to indicate primary and foreign keys.
2738 1117
2739 1118
 
... ... with the following functional dependencies:
2888 1267
2889 1268 \begin{center} \begin{center}
2890 1269 \begin{tabular}{r c l} \begin{tabular}{r c l}
2891 \{Doctor\_no, Patient\_no, Date\} & \(\to\) & \{Diagnosis\}\\
2892 \{Doctor\_no, Patient\_no, Date\} & \(\to\) & \{Treatment\}\\
2893 \{Treatment, Insurance\} & \(\to\) & \{Charge\}\\
2894 \{Patient\_no\} & \(\to\) & \{Insurance\}
1270 \{Doctor\_no, Patient\_no, Date\} & → & \{Diagnosis\}\\
1271 \{Doctor\_no, Patient\_no, Date\} & → & \{Treatment\}\\
1272 \{Treatment, Insurance\} & → & \{Charge\}\\
1273 \{Patient\_no\} & → & \{Insurance\}
2895 1274 \end{tabular} \end{tabular}
2896 1275 \end{center} \end{center}
2897 1276
2898 #. The designer decided not to add the functional dependency \{Diagnosis\} $\to$ \{Treatment\}.
1277 #. The designer decided not to add the functional dependency \{Diagnosis\} → \{Treatment\}.
2899 1278 Explain what could be the designer's justification, at the level of the mini-world. Explain what could be the designer's justification, at the level of the mini-world.
2900 1279 #. Identify a primary key for this relation. #. Identify a primary key for this relation.
2901 1280 #. What is the degree of normalization of this relation? #. What is the degree of normalization of this relation?
 
... ... Normalize it to the third normal form if necessary.
2903 1282
2904 1283
2905 1284
2906 Solution +.#
2907
2908 Answer:
1285 Solution +.#
1286 ~ Answer:
2909 1287 Because there are no partial dependencies, the given relation is in 2NF already. This however is not 3NF because the Charge is a nonkey attribute that is determined by another nonkey attribute, Treatment. We must decompose further: Because there are no partial dependencies, the given relation is in 2NF already. This however is not 3NF because the Charge is a nonkey attribute that is determined by another nonkey attribute, Treatment. We must decompose further:
2910 1288
2911 1289 R (Doctor\_no, Patient\_no, Date, Diagnosis, Treatment) R (Doctor\_no, Patient\_no, Date, Diagnosis, Treatment)
 
... ... A friend of yours want you to review and improve the code for a role-playing gam
2921 1299 The original idea was that each character should have a name, a class (e.g., Bard, Assassin, Druid), a certain amount of experience, a level, one or more weapons (providing bonuses) and can complete quests. The original idea was that each character should have a name, a class (e.g., Bard, Assassin, Druid), a certain amount of experience, a level, one or more weapons (providing bonuses) and can complete quests.
2922 1300 A quest have a name, and rewards the characters that completed it with a certain amount of experience, and sometimes (but rarely) with a special item. A quest have a name, and rewards the characters that completed it with a certain amount of experience, and sometimes (but rarely) with a special item.
2923 1301
2924 Your friend came up with the code presented in \autoref{lst:RPG}, page~\pageref{lst:RPG}, but there are several problems:
1302 Your friend came up with the code presented in \autoref{lst:RPG}, page~ \pageref{lst:RPG}, but there are several problems:
2925 1303
2926 1304 \begin{itemize} \begin{itemize}
2927 1305 \item As of now, a character can have only one weapon. \item As of now, a character can have only one weapon.
 
... ... A tuple in the KEYBOARD relation contains information about a computer keyboard:
2961 1339
2962 1340
2963 1341 Problem +.# Problem +.#
2964 Consider the E.R. schema of Figure~\ref{fig:erCOUNTRY}, p.~\pageref{fig:erCOUNTRY}.
1342 Consider the E.R. schema of Figure~ \ref{fig:erCOUNTRY}, p.~ \pageref{fig:erCOUNTRY}.
2965 1343 Map that E.-R. diagram to a relational database schema. Map that E.-R. diagram to a relational database schema.
2966 1344
2967 1345
 
... ... For this relationship, on the left-hand side is the language that borrows a word
3010 1388 \caption{E.R. Schema for the COUNTRY\_INFO database} \caption{E.R. Schema for the COUNTRY\_INFO database}
3011 1389 \label{fig:erCOUNTRY} \label{fig:erCOUNTRY}
3012 1390 \end{figure} \end{figure}
3013
File notes/00_Doc_Notes.md changed (mode: 100644) (index 67ae82e..1e4ce58)
... ... scrartcl?
11 11 use --top-level-division=chapter? use --top-level-division=chapter?
12 12
13 13
14
15 14 TO DO TO DO
16 15 ======= =======
17 16
 
... ... TO DO
21 20
22 21 - Organize scans (FunDep, ER, UML, Rel, Design, Misc?). - Organize scans (FunDep, ER, UML, Rel, Design, Misc?).
23 22
23 - Add title to problem, and solve their naming / referencing issue.
24
24 25 - Needed to compile: - Needed to compile:
25 26
26 27 - pip install pandoc-numbering https://github.com/chdemko/pandoc-numbering - pip install pandoc-numbering https://github.com/chdemko/pandoc-numbering
File notes/00_sum.md changed (mode: 100644) (index 8a40d34..53b9c2f)
... ... header-includes:
24 24 - \usepackage{fvextra} - \usepackage{fvextra}
25 25 - \DefineVerbatimEnvironment{Highlighting}{Verbatim}{breaklines,commandchars=\\\{\}} - \DefineVerbatimEnvironment{Highlighting}{Verbatim}{breaklines,commandchars=\\\{\}}
26 26 - \definecolor{lgray}{HTML}{e6e7e8} - \definecolor{lgray}{HTML}{e6e7e8}
27 - \usepackage{latex/packages}
27 28 --- ---
28 29
29 30 <!-- <!--
 
... ... Exercise +.#
208 209 Exercise +.# Exercise +.#
209 210 ~ Why do DBMS include concurrency control? ~ Why do DBMS include concurrency control?
210 211
211
212 Exercise +.#
213 ~ Connect the dots:
214
215 |||
216 |-------:|:-------------:|---|
217 Row • | | • Attribute
218 Column header • | | • Tuple
219 Table • | | • Relation
220
221 <!-- Bogue, on ne peut avoir les tables inline. -->
222
223 Exercise +.#
224 ~ What do we call the number of attributes in a relation?
225
226
227 Exercise +.#
228 ~ At the logical level, does the order of the tuples in a relation matter?
229
230
231 Exercise +.#
232 ~ What should we put in an attribute if its value is unknown?
233
234
235 Exercise +.#
236 ~ What, if any, is the difference between a superkey, a key, and a primary key?
237
238
239 Exercise +.#
240 ~ Are we violating an integrity constraint if we try to set the value of a primary key to `NULL`? If yes, which one?
241
242
243 Exercise +.#
244 ~ Give three examples of operations.
245
246
247 Exercise +.#
248 ~ Define what is the domain constraint.
249
250 Exercise +.#
251 ~ Consider the following three relations:
252
253 AUTHOR(\underline{AuthorRef}, AuthorName, Address)
254 BOOK(\underline{ISSN}, AuthorRef, Title)
255 GAINED\_AWARD(\underline{AwardReference}, ISSN, Award\_Title)
256
257 For each relation, answer the following:
258
259 1. What is the primary key?
260 2. Are there, presumably, any foreign key?
261
262 Exercise +.#
263 ~ Consider the following three relations:
264
265 CAR(\underline{VIN}, Make, Model, Year)
266 DRIVER(\underline{State}, \underline{Licence\_Num}, Name, Address)
267 INSURANCE(\underline{Policy\_Number}, Insured\_Car, Insured\_Driver\_State, Insured\_Driver\_Num, Rate)
268
269 For each relation, answer the following:
270
271 1. What is the primary key?
272 2. Are there, presumably, any foreign key?
273
274 Exercise +.#
275 ~ Consider the following three relations
276
277 TRAIN(\underline{TrainRef}, Model, Year)
278 CONDUCTOR(\underline{CompanyID}, Name, ExperienceLevel)
279 ASSIGNED\_TO(\underline{TrainRef}, \underline{CompanyID}, Date)
280
281 1. What are the foreign keys in the ASSIGNED\_TO relation?
282 2. Assuming the database is empty, are the following instructions valid? If not, what integrity constraint are they violating?
283
284 1. Insert <'AM-356', 'Surfliner', 2012> into TRAIN
285 2. Insert <NULL, 'Graham Palmer', 'Senior'> into CONDUCTOR
286 3. Insert <'XB-124', 'GPalmer', '02/04/2018'> into ASSIGNED\_TO
287 4. Insert <'BTed, 'Bobby Ted', 'Senior'> and <'BTed', 'Bobby Ted Jr.', 'Junior'> into CONDUCTOR
288
289 212 ## Solution to Exercises ## Solution to Exercises
290 213
291 214
 
... ... Solution +.#
312 235 Solution +.# Solution +.#
313 236 ~ To ensure that several users trying to update the same data will do so in a controlled manner. ~ To ensure that several users trying to update the same data will do so in a controlled manner.
314 237
315 Solution +.#
316 ~ Row is Tuple, Column Header is Attribute, Table is Relation.
317
318
319 Solution +.#
320 ~ The degree, or arity, of the relation.
321
322
323 Solution +.#
324 ~ No.
325
326
327 Solution +.#
328 ~ `NULL`
329
330 Solution +.#
331 ~ A superkey is a subset of attributes such that no two tuples have the same combination of values for all their attributes.
332 A key is a minimal superkey, i.e., a superkey from which we cannot remove any attribute without losing the uniqueness constraint.
333 The primary key is one of the candidate key, i.e., the key that was chosen.
334
335
336 Solution +.#
337 ~ The entity integrity constraint.
338
339
340 Solution +.#
341 ~ Reading from the database, performing UPDATE, INSERT or DELETE operations.
342
343
344 Solution +.#
345 ~ The requirement that each attribute $A$ must be an atomic value from the domain dom($A$).
346
347
348 Solution +.#
349 ~ 1. \underline{AuthorRef} and \underline{ISSN}
350 2. AuthorRef for BOOK, ISSN for GAINED\_AWARD
351
352
353 Solution +.#
354 ~ 1. \underline{TrainRef} and \underline{CompanyID}.
355 2. 1. Yes,
356 2. no (it violates the entity integrity constraint),
357 3. no (it violates the referential integrity constraint),
358 4. no (it violates the key constraint)
359
360 238 ## Problems ## Problems
361 239
362 240 ### Campus Database ### Campus Database
 
... ... Question -.#
410 288 7. Can you list which professors are at the same floor? 7. Can you list which professors are at the same floor?
411 289 8. Can you tell which professor has the highest evaluations? 8. Can you tell which professor has the highest evaluations?
412 290
413 ### Setting Up MySQL {#installation}
414 291
415 In this problem, you will install the [MySQL](https://www.mysql.com/) DataBase Managment System and set it up.
416 On top of being open source and free, it is one of the most widespread and used DBMS, as well as one of the most well-documented.
417 Linux users will use its community-developed fork, \href{https://mariadb.org/}{MariaDB}, but that won't make a difference in this course.
292 ---
418 293
419 It is very important that you follow the steps below carefully.
420 Read the messages printed on your screen, make sure a step was correctly executed before moving to the next one.
421 And, remember:
422 294
423 1. Don't wait, set your system early.
424 2. I'm willing to help you, but there's nothing I can do with an email like "It doesn't work": if you look for help, be detailed and clear about what you think went wrong.
295 # The Relational Data Model and Relational Database Constraints
425 296
426 The following links could be useful:
297 **Ressources:**
427 298
428 - <https://dev.mysql.com/doc/refman/5.7/en/windows-installation.html>,
429 - <https://dev.mysql.com/doc/refman/5.7/en/linux-installation-native.html>,
430 - <https://dev.mysql.com/doc/refman/5.7/en/connecting-disconnecting.html> and
431 - <https://www.linode.com/docs/databases/mysql/how-to-install-mysql-on-debian-8>
299 - Textbook: Ch. 3
300 - <https://en.wikipedia.org/wiki/Relational_model>
432 301
433 302
434 #### Installation
303 **Last Time:**
304 Example (miniworld = University), to introduce vocabulary, utility of having multiple tables / files, describe possible interactions, highlight organization and how to conceive a DB (Specifications, Conceptual, Logical and Physical designs). Also to mention some of the features of DBMS (define / construct / manipulate / share), and characteristics of the DB approach.
435 305
436 Below are the instructions for Windows 10 and for Linux.
437 It is perfectly acceptable to install MySQL on a virtual machine for this class (remember that on <http://spots.augusta.edu/tschultz/resources/SWAvailable.html>, you can have access to VMware and Windows licences, but using [Virtual Box](https://www.virtualbox.org/wiki/Downloads) or Linux should also work fine).
438 Once this step is completed, or if MySQL is already installed on your computer, go to the next step.
439 306
440 - **For Windows 10**
441 1. Visit <https://dev.mysql.com/downloads/installer/>, click on "Download" next to "Windows (x86, 32-bit), MSI Installer 5.7.20 18.5M (mysql-installer-web-community-5.7.20.0.msi)". On the next page, click on the (somewhat hidden) "No thanks, just start my download." button.
442 2. Save the "mysql-installer-web-community-5.7.20.0.msi" file, and open it. If there is an updated version of the installer available, agree to download it. Accept the license term.
443 3. We will now install the various components needed for this class, leaving all the choices by defaults. This means that you need to do the following:
444 1. Leave the first option on "Developer Default" and click on "Next"
445 2. Click on "Next" even if you don't meet all the requirements
446 3. Click on "Execute". The system will download and install several softwares (this may take some time).
447 4. Click on "Next" twice, leave "Type and Networking" on "Standalone MySQL Server / Classic MySQL Replication" and click "Next", and leave the next options as they are (unless you know what you do and want to change the port, for instance) and click on "Next".
448 5. \label{choose-pswd} You now need to choose a password for the MySQL root account.
449 It can be anything, just make sure to memorize it.
450 Click on "Next".
451 6. On the "Windows Service" page, leave everything as it is and click on "Next".
452 7. On the "Plugins and Extensions" page, leave everything as it is and click on "Next".
453 8. Finally, click "Execute" on the "Apply Configuration" page, and then on "Finish".
454 9. Click on "Cancel" on the "Product Configuration" page and confirm that you don't want to add products: we only need to have MySQL Server 5.7.20 configured.
455 4. We now want to make sure that MySQL is running: launch Windows' "Control Panel", then click on "Administrative Tools", and on "Services". Look for "MySQL57", its status should be "Running". If it is not, right-click on it and click on "Start".
456 307
457 - **For Linux**
308 ## Concepts
458 309
459 1. Install, through your standard package management system (`apt` or `aptitude` for debian-based systems, `pacman` for Arch Linux, etc.), the packages `mysql-client` and `mysql-server` as well as their dependencies.
460 2. Open a terminal and type
310 ![Terminology](paper_screen/termimology.jpeg)
461 311
462 ```bash
463 /etc/init.d/mysql status
464 ```
465 to see if MySQL is running: if you read
312 Relational data model:
466 313
467 ```bash
468 Active: active (running)
469 ```
470 then you can move on to the next step, otherwise run (as root)
471
472 ```bash
473 service mysqld start
474 ```
314 - Mathematical model
315 - Multiple implementations ("engineering approximation")
475 316
476 3. As root, type in your terminal
317 ### Domains, Attributes, Tuples and Relations
477 318
478 ```bash
479 mysql_secure_installation
480 ```
481 You'll be asked to provide the current password for the root MySQL user: this password has not be defined yet, so just hit "Enter". You'll be asked if you want to set a new password (that you can freely chose, just make sure to memorize it). Then, answer "n" to the question "Remove anonymous users?", "Y" to "Disallow root login remotely?", "n" to "Remove test database and access to it?" and finally "Y" to "Reload privilege tables now?".
319 - **Domain** (or type) = set of atomic (as far as the relation is concerned) values. Can be given in the form of a data type, can be named and carry a logical definition (i.e., List_of_major as an enumerated data type, instead of just `String`).
320 - **Attribute** = Attribute name + attribute domain (but we'll just write the name).
321 - **Relation Schema** (or scheme) = description of a relation. RELATION_NAME(Attribute$_1$, ..., Attribute$_n$), where $n$ is the degre (arity) of the relation, and the domain of Attribute$_i$ is written dom(Attribute$_i$).
322 - **Tuple** t of the schema R(A$_1$, ..., A$_n$) is an ordered list of values <v$_1$, ..., v$_n$> where v$_i$ is in dom(A$_i$) or a special `NULL` value.
323 - **Relation** (or relation state) r of the schema R(A$_1$, ..., A_$n$), also written r(R), is the set of n-tuples {t$_1$, ..., t$_m$} where each t$_i$ is a tuple of the schema R(A$_1$, ..., A$_n$).
482 324
483
484 #### Creating an user
325 ### Characteristics of Relations
485 326
486 This step will create a non-root user and grant it some rights. Type the following three commands, one by one (that is, type the first one, hit "enter", type the second, hit "enter", etc. The colors are here to ease the reading, you can ignore them safely.):
327 - Order of tuples does not matter. Order *in* tuple **do** matter (alternate representation where this isn't true exist, cf. self-describing data).
328 - Value is atomic = "flat relational model", 1st normal form (not composite, not multi-valued).
329 - `NULL` is N/A, unknown, unavailable (or withheld).
330 - Relation Schema = assertion ("Every student has a name, a SSN, ...). Tuple = fact (Bob Taylor has SSN 12898, ...).
331 - Relations represents uniformly entities (STUDENT(...)) and relations (MAJORS(Student_number, Department_Code)).
487 332
488 ```sqlmysql
489 CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'password';
490 GRANT ALL PRIVILEGES ON `HW\_%` . * TO 'testuser'@'localhost';
491 EXIT;
492 ```
333 ### Notation
493 334
494 The message prompted after the two first commands should be
335 <!--
336 - Relation Schema: R(A$_1$, ..., A_$n$)
337 - Relation name : R, Q, S
338 - Relation states: r, q, s
339 - Tuples : t, u, v
340 -->
495 341
496 ```sqlmysql
497 Query OK, 0 rows affected (0.00 sec)
498 ```
342 - STUDENT = relation schema + current relation state
343 - STUDENT(Name, ..., Major) = relation schema only
344 - STUDENT.Name = Attribute Name in the relation STUDENT
345 - t[Name], t[Name, Major], t.Attribute
499 346
500 and the message after the last command should be
501
502 ```sqlmysql
503 Bye
504 ```
347 ---
505 348
506 Be careful: back-tics are surrounding
507
508 ```bat
509 HW\_%
510 ```
511
512 whereas single quotes are surrounding `testuser` and `localhost` (normally, copy-and-pasting from this document should work).
513
514 #### Log-in
515 349
516 We now log as the normal user called "testuser".
350 **Last Time:**
351 Relational model, vocabulary (domain, attribute, tuple, relation, relation scheme, atomic value
517 352
518 Linux users should type *as a normal user, i.e., not as root*, in their terminal the following, and Windows users should type in their command prompt the following (provided working directory is still
353 ## Constraints
519 354
520 ```bash
521 C:\Program Files\MySQL\MySQL Server 5.7\bin
522 ```
355 ### Types of Constraints
523 356
524 :
357 Those are constraints on the tuples (there are constraints on the scheme, for instance, "a relation can't have two attributes with the same name").
525 358
526 ```bash
527 mysql -u testuser -p
528 ```
359 #### Inherent model-based constraints (implicit)
529 360
530 Enter `password` as your password. If at some point you want to know if you are logged as root or testuser, simply enter
361 Those are part of the model.
531 362
532 ```sqlmysql
533 \s;
534 ```
363 - No duplicate tuple
364 - Arity must match
535 365
536 #### Creating our first database
366 #### Schema-based constraints (explicit)
537 367
538 Now, type the following commands one by one:
368 Those are parts of the schema
539 369
540 ```sqlmysql
541 CREATE DATABASE HW_1Q2;
542 USE HW_1Q2;
543 CREATE TABLE t(i integer, n integer);
544 INSERT INTO t VALUES (1,1),(2,2),(3,3);
545 SELECT * FROM t;
546 ```
370 - Value must match domain ("Domain constraint"), domain can be complex (not `NULL`)
371 - Entity integrity constraint (no primary key value can be `NULL`)
372 - Referential integrity constraint (referred values must exists)
547 373
548 After that last command, you should see
549
550 ```sqlmysql
551 +------+------+
552 | i | n |
553 +------+------+
554 | 1 | 1 |
555 | 2 | 2 |
556 | 3 | 3 |
557 +------+------+
558 ```
559
560 You're all set! All you have to do is to quit, using the command
561
562 ```sqlmysql
563 EXIT;
564 ```
565
566
567 **Add somewhere link to <https://dev.mysql.com/doc/mysql-windows-excerpt/5.7/en/mysql-installation-windows-path.html>**
568
569
570
571 ---
572
573
574 # The Relational Data Model and Relational Database Constraints
575
576 **Ressources:**
577
578 - Textbook: Ch. 3
579 - <https://en.wikipedia.org/wiki/Relational_model>
580
581
582 **Last Time:**
583 Example (miniworld = University), to introduce vocabulary, utility of having multiple tables / files, describe possible interactions, highlight organization and how to conceive a DB (Specifications, Conceptual, Logical and Physical designs). Also to mention some of the features of DBMS (define / construct / manipulate / share), and characteristics of the DB approach.
584
585
586
587 ## Concepts
588
589 ![Terminology](paper_screen/termimology.jpeg)
590
591 Relational data model:
592
593 - Mathematical model
594 - Multiple implementations ("engineering approximation")
595
596 ### Domains, Attributes, Tuples and Relations
597
598 - **Domain** (or type) = set of atomic (as far as the relation is concerned) values. Can be given in the form of a data type, can be named and carry a logical definition (i.e., List_of_major as an enumerated data type, instead of just `String`).
599 - **Attribute** = Attribute name + attribute domain (but we'll just write the name).
600 - **Relation Schema** (or scheme) = description of a relation. RELATION_NAME(Attribute$_1$, ..., Attribute$_n$), where $n$ is the degre (arity) of the relation, and the domain of Attribute$_i$ is written dom(Attribute$_i$).
601 - **Tuple** t of the schema R(A$_1$, ..., A$_n$) is an ordered list of values <v$_1$, ..., v$_n$> where v$_i$ is in dom(A$_i$) or a special `NULL` value.
602 - **Relation** (or relation state) r of the schema R(A$_1$, ..., A_$n$), also written r(R), is the set of n-tuples {t$_1$, ..., t$_m$} where each t$_i$ is a tuple of the schema R(A$_1$, ..., A$_n$).
603
604 ### Characteristics of Relations
605
606 - Order of tuples does not matter. Order *in* tuple **do** matter (alternate representation where this isn't true exist, cf. self-describing data).
607 - Value is atomic = "flat relational model", 1st normal form (not composite, not multi-valued).
608 - `NULL` is N/A, unknown, unavailable (or withheld).
609 - Relation Schema = assertion ("Every student has a name, a SSN, ...). Tuple = fact (Bob Taylor has SSN 12898, ...).
610 - Relations represents uniformly entities (STUDENT(...)) and relations (MAJORS(Student_number, Department_Code)).
611
612 ### Notation
613
614 <!--
615 - Relation Schema: R(A$_1$, ..., A_$n$)
616 - Relation name : R, Q, S
617 - Relation states: r, q, s
618 - Tuples : t, u, v
619 -->
620
621 - STUDENT = relation schema + current relation state
622 - STUDENT(Name, ..., Major) = relation schema only
623 - STUDENT.Name = Attribute Name in the relation STUDENT
624 - t[Name], t[Name, Major], t.Attribute
625
626 ---
627
628
629 **Last Time:**
630 Relational model, vocabulary (domain, attribute, tuple, relation, relation scheme, atomic value
631
632 ## Constraints
633
634 ### Types of Constraints
635
636 Those are constraints on the tuples (there are constraints on the scheme, for instance, "a relation can't have two attributes with the same name").
637
638 #### Inherent model-based constraints (implicit)
639
640 Those are part of the model.
641
642 - No duplicate tuple
643 - Arity must match
644
645 #### Schema-based constraints (explicit)
646
647 Those are parts of the schema
648
649 - Value must match domain ("Domain constraint"), domain can be complex (not `NULL`)
650 - Entity integrity constraint (no primary key value can be `NULL`)
651 - Referential integrity constraint (referred values must exists)
652
653 #### Application-based constraints (semantics)
374 #### Application-based constraints (semantics)
654 375
655 376 *Cannot* be expressed in the schema, and hence must be enforced by some other way. *Cannot* be expressed in the schema, and hence must be enforced by some other way.
656 377 Example: the date of birth of an employee must be greater than xxx. Example: the date of birth of an employee must be greater than xxx.
 
... ... c. Set default, or set `NULL`
764 485
765 486 Conclusion: The Relational Data Model and Relational Database Constraints: Vocabulary, Relations to model everything, difference between data and meta-data, constraints. Conclusion: The Relational Data Model and Relational Database Constraints: Vocabulary, Relations to model everything, difference between data and meta-data, constraints.
766 487
488 ## Exercises
489
490 Exercise +.#
491 ~ Connect the dots:
492
493 |||
494 |-------:|:-------------:|---|
495 Row • | | • Attribute
496 Column header • | | • Tuple
497 Table • | | • Relation
498
499 <!-- Bogue, on ne peut avoir les tables inline. -->
500
501 Exercise +.#
502 ~ What do we call the number of attributes in a relation?
503
504
505 Exercise +.#
506 ~ At the logical level, does the order of the tuples in a relation matter?
507
508
509 Exercise +.#
510 ~ What should we put in an attribute if its value is unknown?
511
512
513 Exercise +.#
514 ~ What, if any, is the difference between a superkey, a key, and a primary key?
515
516
517 Exercise +.#
518 ~ Are we violating an integrity constraint if we try to set the value of a primary key to `NULL`? If yes, which one?
519
520
521 Exercise +.#
522 ~ Give three examples of operations.
523
524
525 Exercise +.#
526 ~ Define what is the domain constraint.
527
528 Exercise +.#
529 ~ Consider the following three relations:
530
531 AUTHOR(\underline{AuthorRef}, AuthorName, Address)
532 BOOK(\underline{ISSN}, AuthorRef, Title)
533 GAINED\_AWARD(\underline{AwardReference}, ISSN, Award\_Title)
534
535 For each relation, answer the following:
536
537 1. What is the primary key?
538 2. Are there, presumably, any foreign key?
539
540 Exercise +.#
541 ~ Consider the following three relations:
542
543 CAR(\underline{VIN}, Make, Model, Year)
544 DRIVER(\underline{State}, \underline{Licence\_Num}, Name, Address)
545 INSURANCE(\underline{Policy\_Number}, Insured\_Car, Insured\_Driver\_State, Insured\_Driver\_Num, Rate)
546
547 For each relation, answer the following:
548
549 1. What is the primary key?
550 2. Are there, presumably, any foreign key?
551
552 Exercise +.#
553 ~ Consider the following three relations
554
555 TRAIN(\underline{TrainRef}, Model, Year)
556 CONDUCTOR(\underline{CompanyID}, Name, ExperienceLevel)
557 ASSIGNED\_TO(\underline{TrainRef}, \underline{CompanyID}, Date)
558
559 1. What are the foreign keys in the ASSIGNED\_TO relation?
560 2. Assuming the database is empty, are the following instructions valid? If not, what integrity constraint are they violating?
561
562 1. Insert <'AM-356', 'Surfliner', 2012> into TRAIN
563 2. Insert <NULL, 'Graham Palmer', 'Senior'> into CONDUCTOR
564 3. Insert <'XB-124', 'GPalmer', '02/04/2018'> into ASSIGNED\_TO
565 4. Insert <'BTed, 'Bobby Ted', 'Senior'> and <'BTed', 'Bobby Ted Jr.', 'Junior'> into CONDUCTOR
566
567 ## Solution to Exercises
568
569 Solution +.#
570 ~ Row is Tuple, Column Header is Attribute, Table is Relation.
571
572 Solution +.#
573 ~ The degree, or arity, of the relation.
574
575 Solution +.#
576 ~ No.
577
578
579 Solution +.#
580 ~ `NULL`
581
582 Solution +.#
583 ~ A superkey is a subset of attributes such that no two tuples have the same combination of values for all their attributes.
584 A key is a minimal superkey, i.e., a superkey from which we cannot remove any attribute without losing the uniqueness constraint.
585 The primary key is one of the candidate key, i.e., the key that was chosen.
586
587
588 Solution +.#
589 ~ The entity integrity constraint.
590
591
592 Solution +.#
593 ~ Reading from the database, performing UPDATE, INSERT or DELETE operations.
594
595
596 Solution +.#
597 ~ The requirement that each attribute $A$ must be an atomic value from the domain dom($A$).
598
599
600 Solution +.#
601 ~ 1. \underline{AuthorRef} and \underline{ISSN}
602 2. AuthorRef for BOOK, ISSN for GAINED\_AWARD
603
604
605 Solution +.#
606 ~ 1. \underline{TrainRef} and \underline{CompanyID}.
607 2. 1. Yes,
608 2. no (it violates the entity integrity constraint),
609 3. no (it violates the referential integrity constraint),
610 4. no (it violates the key constraint)
611
612
767 613
768 614 # SQL # SQL
769 615
 
... ... The three last sublanguages being dubbed "**D**ata **M**anipulation **L**anguage
829 675
830 676 ## First Commands ## First Commands
831 677
832 ```{.sql}
678 ~~~{.sql}
833 679 CREATE SCHEMA HW_FACULTY; CREATE SCHEMA HW_FACULTY;
834 680
835 681
 
... ... INSERT INTO PROF VALUES (
867 713 -- Note also the existence of DATETIME, with 'YYYY-MM-DD HH:MM:SS' -- Note also the existence of DATETIME, with 'YYYY-MM-DD HH:MM:SS'
868 714 , 'apple' , 'apple'
869 715 ); );
870 ```
716 ~~~
871 717
872 718 --- ---
873 719
 
... ... f. `CHECK`
890 736
891 737 We know a. and b. from the Relational Model, here comes new constraints that can't be describe in our relations. We know a. and b. from the Relational Model, here comes new constraints that can't be describe in our relations.
892 738
893 ```{.sql}
739 ~~~{.sql}
894 740 CREATE TABLE HURRICANE( CREATE TABLE HURRICANE(
895 741 Name VARCHAR(25) PRIMARY KEY, Name VARCHAR(25) PRIMARY KEY,
896 742 WindSpeed INT DEFAULT 76, WindSpeed INT DEFAULT 76,
 
... ... CREATE TABLE STATE(
902 748 Name VARCHAR(25) UNIQUE, Name VARCHAR(25) UNIQUE,
903 749 Postal_abbr CHAR(2) NOT NULL Postal_abbr CHAR(2) NOT NULL
904 750 ); );
905 ```
751 ~~~
906 752
907 753 - You can insert `NULL` in `UNIQUE` attributes. - You can insert `NULL` in `UNIQUE` attributes.
908 754 - `CHECK` constraints are parsed but don't do anything! - `CHECK` constraints are parsed but don't do anything!
909 755
910 ```{.sql}
756 ~~~{.sql}
911 757 -- Adding a primary key: -- Adding a primary key:
912 758 ALTER TABLE STATE ADD PRIMARY KEY (Name); ALTER TABLE STATE ADD PRIMARY KEY (Name);
913 759
 
... ... ALTER TABLE HURRICANE ALTER COLUMN WindSpeed SET DEFAULT 74;
925 771
926 772 --Adding a foreign key constraint --Adding a foreign key constraint
927 773 ALTER TABLE HURRICANE ADD FOREIGN KEY (Above) REFERENCES STATE(Name); ALTER TABLE HURRICANE ADD FOREIGN KEY (Above) REFERENCES STATE(Name);
928 ```
774 ~~~
929 775
930 776 - `NOT NULL` is to some extend part of the datatype. - `NOT NULL` is to some extend part of the datatype.
931 777 - Note the difference between adding and removing the `NOT NULL` constraint. - Note the difference between adding and removing the `NOT NULL` constraint.
 
... ... ALTER TABLE HURRICANE ADD FOREIGN KEY (Above) REFERENCES STATE(Name);
934 780
935 781 A bit of testing: A bit of testing:
936 782
937 ```{.sql}
783 ~~~{.sql}
938 784 INSERT INTO STATE VALUES('Georgia', 'GA'); INSERT INTO STATE VALUES('Georgia', 'GA');
939 785 INSERT INTO STATE VALUES('Texas', 'TX'); INSERT INTO STATE VALUES('Texas', 'TX');
940 786 INSERT INTO STATE VALUES('FLORIDA', 'FL'); INSERT INTO STATE VALUES('FLORIDA', 'FL');
 
... ... UPDATE HURRICANE SET Above = 'North Carolina' WHERE Name = 'Irma';
969 815 -- Let's patch it, by adding North Carolina to our STATE table. -- Let's patch it, by adding North Carolina to our STATE table.
970 816 INSERT INTO STATE VALUES('North Carolina', 'NC'); INSERT INTO STATE VALUES('North Carolina', 'NC');
971 817 UPDATE HURRICANE SET Above = 'North Carolina' WHERE Name = 'Irma'; UPDATE HURRICANE SET Above = 'North Carolina' WHERE Name = 'Irma';
972 ```
818 ~~~
973 819
974 820 ## Foreign Keys ## Foreign Keys
975 821
976 ```{.sql}
822 ~~~{.sql}
977 823 CREATE TABLE STORM( CREATE TABLE STORM(
978 824 Name VARCHAR(25) PRIMARY KEY, Name VARCHAR(25) PRIMARY KEY,
979 825 Kind ENUM('Tropical Storm', 'Hurricane'), Kind ENUM('Tropical Storm', 'Hurricane'),
 
... ... UPDATE STATE SET Affected_by = 'Harvey' WHERE Name = 'Georgia';
1011 857
1012 858 UPDATE STORM SET Name = 'Harley' WHERE Name = 'Harvey'; UPDATE STORM SET Name = 'Harley' WHERE Name = 'Harvey';
1013 859 DELETE FROM STORM WHERE Name = 'Harley'; DELETE FROM STORM WHERE Name = 'Harley';
1014 ```
860 ~~~
1015 861
1016 862 ## Foreign Keys Restrictions ## Foreign Keys Restrictions
1017 863
1018 ```{.sql}
864 ~~~{.sql}
1019 865 CREATE TABLE F_Key( CREATE TABLE F_Key(
1020 866 Attribute VARCHAR(25) PRIMARY KEY Attribute VARCHAR(25) PRIMARY KEY
1021 867 ); );
 
... ... DELETE FROM F_Key WHERE Attribute = 'First Test';
1077 923
1078 924 -- Let us drop this table, and try again. -- Let us drop this table, and try again.
1079 925 DROP TABLE Table_default; DROP TABLE Table_default;
1080 ```
926 ~~~
1081 927
1082 928 --- ---
1083 929
1084 ```{.sql}
930 ~~~{.sql}
1085 931 -- The following fails too, this time because of the Table_restrict table: -- The following fails too, this time because of the Table_restrict table:
1086 932 UPDATE F_Key SET Attribute = 'After Update' WHERE Attribute = 'First Test'; UPDATE F_Key SET Attribute = 'After Update' WHERE Attribute = 'First Test';
1087 933 DELETE FROM F_Key WHERE Attribute = 'First Test'; DELETE FROM F_Key WHERE Attribute = 'First Test';
 
... ... DELETE FROM F_Key WHERE Attribute = 'Second Test';
1124 970 -- And let's print the situation after this deletion: -- And let's print the situation after this deletion:
1125 971 SELECT * FROM Table_cascade; SELECT * FROM Table_cascade;
1126 972 SELECT * FROM Table_set_null; SELECT * FROM Table_set_null;
1127 ```
973 ~~~
1128 974
1129 975 --- ---
1130 976
 
... ... Note: Use `DESCRIBE <Table>;`, `SHOW TABLES;` and `SELECT * FROM <Table>;` inten
1138 984 - Remember, we start by creating a schema and tables inside of it. - Remember, we start by creating a schema and tables inside of it.
1139 985 - What if foreign keys are mutually dependent? - What if foreign keys are mutually dependent?
1140 986
1141 ```{.sql}
987 ~~~{.sql}
1142 988 CREATE TABLE PROF( CREATE TABLE PROF(
1143 989 Login VARCHAR(25) PRIMARY KEY, Login VARCHAR(25) PRIMARY KEY,
1144 990 Name VARCHAR(25), Name VARCHAR(25),
 
... ... CREATE TABLE DEPARTMENT(
1154 1000 ); );
1155 1001
1156 1002 ALTER TABLE PROF ADD FOREIGN KEY (Department) REFERENCES DEPARTMENT(Code); ALTER TABLE PROF ADD FOREIGN KEY (Department) REFERENCES DEPARTMENT(Code);
1157 ```
1003 ~~~
1158 1004
1159 1005 Note the structure of the `ALTER TABLE` command: Note the structure of the `ALTER TABLE` command:
1160 1006
 
... ... Note the structure of the `ALTER TABLE` command:
1162 1008 - ... `KEY (Department) REFERENCES (Code);`: error - ... `KEY (Department) REFERENCES (Code);`: error
1163 1009 - ... `KEY PROF(Department) REFERENCES DEPARTMENT(Code);`: ok - ... `KEY PROF(Department) REFERENCES DEPARTMENT(Code);`: ok
1164 1010
1165 ```{.sql}
1011 ~~~{.sql}
1166 1012 CREATE TABLE STUDENT( CREATE TABLE STUDENT(
1167 1013 Login VARCHAR(25) PRIMARY KEY, Login VARCHAR(25) PRIMARY KEY,
1168 1014 Name VARCHAR(25), Name VARCHAR(25),
 
... ... CREATE TABLE STUDENT(
1170 1016 Major CHAR(5), Major CHAR(5),
1171 1017 FOREIGN KEY (Major) REFERENCES DEPARTMENT(Code) FOREIGN KEY (Major) REFERENCES DEPARTMENT(Code)
1172 1018 ); );
1173 ```
1019 ~~~
1174 1020
1175 1021 #### Populating #### Populating
1176 1022
1177 1023 We can insert multiple values at once: We can insert multiple values at once:
1178 1024
1179 ```{.sql}
1025 ~~~{.sql}
1180 1026 INSERT INTO DEPARTMENT VALUES INSERT INTO DEPARTMENT VALUES
1181 1027 ('MATH', 'Mathematics', NULL), ('MATH', 'Mathematics', NULL),
1182 1028 ('CS', 'Computer Science', NULL); ('CS', 'Computer Science', NULL);
1183 ```
1029 ~~~
1184 1030
1185 1031 We can specify which attributes we are giving: We can specify which attributes we are giving:
1186 1032
1187 ```{.sql}
1033 ~~~{.sql}
1188 1034 INSERT INTO DEPARTMENT (Code, Name) VALUES INSERT INTO DEPARTMENT (Code, Name) VALUES
1189 1035 ('CYBR', 'Cyber Secturity'); ('CYBR', 'Cyber Secturity');
1190 ```
1036 ~~~
1191 1037
1192 1038 And we can even specify the order (even the trivial one): And we can even specify the order (even the trivial one):
1193 1039
1194 ```{.sql}
1040 ~~~{.sql}
1195 1041 INSERT INTO PROF (Login, Department, Name) VALUES INSERT INTO PROF (Login, Department, Name) VALUES
1196 1042 ('caubert', 'CS', 'Clément Aubert'); ('caubert', 'CS', 'Clément Aubert');
1197 1043
 
... ... INSERT INTO STUDENT (Login, Name, Registered, Major) VALUES
1206 1052 ('cjoella', 'Candice Joella', '20120212', 'CYBR'), ('cjoella', 'Candice Joella', '20120212', 'CYBR'),
1207 1053 ('aalyx', 'Ava Alyx', 20121011, 'CYBR'), ('aalyx', 'Ava Alyx', 20121011, 'CYBR'),
1208 1054 ('caubert', 'Clément Aubert', NULL, 'CYBR'); ('caubert', 'Clément Aubert', NULL, 'CYBR');
1209 ```
1055 ~~~
1210 1056
1211 1057 Note the date litterals. Note the date litterals.
1212 1058
 
... ... Note the date litterals.
1221 1067
1222 1068 Order of clause has no importance. Order of clause has no importance.
1223 1069
1224 ```{.sql}
1070 ~~~{.sql}
1225 1071 UPDATE <table> UPDATE <table>
1226 1072 SET <attribute1> = <value1>, <attribute2> = <value2>, ... SET <attribute1> = <value1>, <attribute2> = <value2>, ...
1227 1073 WHERE <condition>; WHERE <condition>;
 
... ... WHERE <condition>;
1229 1075 SELECT <attribute list, called projection attributes> SELECT <attribute list, called projection attributes>
1230 1076 FROM <table list> FROM <table list>
1231 1077 WHERE <condition>; WHERE <condition>;
1232 ```
1078 ~~~
1233 1079
1234 1080 Conditions can Conditions can
1235 1081
 
... ... Conditions can
1240 1086 - be trivial / empty - be trivial / empty
1241 1087 - use regular expressions (escape character is `\`.) - use regular expressions (escape character is `\`.)
1242 1088
1243
1244 ```{.sql}
1089 ~~~{.sql}
1245 1090 UPDATE Department SET Head = 'aturing' WHERE Code = 'MATH'; UPDATE Department SET Head = 'aturing' WHERE Code = 'MATH';
1246 1091
1247 1092 UPDATE Department SET Head = 'bgates' WHERE Code = 'CS' OR NOT Code = 'CYBR'; UPDATE Department SET Head = 'bgates' WHERE Code = 'CS' OR NOT Code = 'CYBR';
 
... ... SELECT Login FROM STUDENT;
1257 1102 SELECT Login FROM STUDENT WHERE Name LIKE 'Ava%'; SELECT Login FROM STUDENT WHERE Name LIKE 'Ava%';
1258 1103
1259 1104 SELECT Name FROM PROF WHENE Login LIKE '_aubert'; SELECT Name FROM PROF WHENE Login LIKE '_aubert';
1260 ```
1105 ~~~
1261 1106
1262 1107 --- ---
1263 1108
 
... ... SELECT Name FROM PROF WHENE Login LIKE '_aubert';
1285 1130
1286 1131 Note: SQL treats tables as multi-set, there can be repetitions in the tables. Note: SQL treats tables as multi-set, there can be repetitions in the tables.
1287 1132
1288 ```{.sql}
1133 ~~~{.sql}
1289 1134 SELECT DISTINCT Major FROM STUDENT; SELECT DISTINCT Major FROM STUDENT;
1290 ```
1135 ~~~
1291 1136
1292 1137 The default behaviour is `ALL`, but we can declare it explicitely. The default behaviour is `ALL`, but we can declare it explicitely.
1293 1138
1294 ```{.sql}
1139 ~~~{.sql}
1295 1140 (SELECT Login FROM STUDENT) UNION (SELECT Login FROM PROF); (SELECT Login FROM STUDENT) UNION (SELECT Login FROM PROF);
1296 ```
1141 ~~~
1297 1142
1298 1143 There is also `INTERSECT` and `EXCEPT` in the specification, but MariaDB and MySQL do not implement them. There is also `INTERSECT` and `EXCEPT` in the specification, but MariaDB and MySQL do not implement them.
1299 1144
 
... ... There is also `INTERSECT` and `EXCEPT` in the specification, but MariaDB and MyS
1302 1147
1303 1148 You can have `ORDER BY` specifications: You can have `ORDER BY` specifications:
1304 1149
1305 ```{.sql}
1150 ~~~{.sql}
1306 1151 SELECT Login FROM GRADE WHERE Grade > 3.0 ORDER BY Grade; SELECT Login FROM GRADE WHERE Grade > 3.0 ORDER BY Grade;
1307 1152
1308 1153 SELECT Login FROM GRADE WHERE Grade > 3.0 ORDER BY Grade DESC; SELECT Login FROM GRADE WHERE Grade > 3.0 ORDER BY Grade DESC;
1309 1154
1310 1155 SELECT Login, Major FROM STUDENT ORDER BY Major, Name; SELECT Login, Major FROM STUDENT ORDER BY Major, Name;
1311 ```
1156 ~~~
1312 1157
1313 1158 ### Aggregate Functions ### Aggregate Functions
1314 1159
1315 1160 You can use `MAX`, `SUM`, `MIN`, `AVG`, `COUNT`: You can use `MAX`, `SUM`, `MIN`, `AVG`, `COUNT`:
1316 1161
1317 ```{.sql}
1162 ~~~{.sql}
1318 1163 SELECT MAX(Registered) FROM STUDENT; SELECT MAX(Registered) FROM STUDENT;
1319 1164
1320 1165 SELECT COUNT(Name) FROM STUDENT; SELECT COUNT(Name) FROM STUDENT;
1321 1166
1322 1167 SELECT COUNT(DISTINCT Name) FROM STUDENT; SELECT COUNT(DISTINCT Name) FROM STUDENT;
1323 ```
1168 ~~~
1324 1169
1325 1170 ### Aliases for Columns ### Aliases for Columns
1326 1171
1327 ```{.sql}
1172 ~~~{.sql}
1328 1173 SELECT Login AS Username FROM PROF; SELECT Login AS Username FROM PROF;
1329 ```
1174 ~~~
1330 1175
1331 1176 ## Three-Valued Logic ## Three-Valued Logic
1332 1177
 
... ... You can test if a value is `NULL` with `IS NULL`.
1371 1216
1372 1217 ### Select-project-join (4.3.1) ### Select-project-join (4.3.1)
1373 1218
1374 ```{.sql}
1219 ~~~{.sql}
1375 1220 SELECT Login FROM PROF, DEPARTMENT WHERE DEPARTMENT.Name = 'Mathematics' AND Department = Code; SELECT Login FROM PROF, DEPARTMENT WHERE DEPARTMENT.Name = 'Mathematics' AND Department = Code;
1376 ```
1221 ~~~
1377 1222
1378 1223 - `Department.Name = 'Mathematics'` is the selection condition - `Department.Name = 'Mathematics'` is the selection condition
1379 1224 - `Department = Code` is the join condition, because it combines two tuples. - `Department = Code` is the join condition, because it combines two tuples.
1380 1225 - Why do we use the fully qualified Name attribute for `Name`? - Why do we use the fully qualified Name attribute for `Name`?
1381 1226 - We have to list all the tables we want to consult, even if we use fully qualified names. - We have to list all the tables we want to consult, even if we use fully qualified names.
1382 1227
1228 ~~~{.sql}
1229 SELECT Name FROM STUDENT, GRADE WHERE Grade > 3.0 AND STUDENT.Login = GRADE.Login;
1230 ~~~
1231
1232 - `Grade > 3.0` is the selection condition
1233 - `STUDENT.Login = GRADE.Login` is the join condition
1234
1235 We can have two join conditions!
1236
1237 ~~~{.sql}
1238 SELECT PROF.Name FROM PROF, DEPARTMENT, STUDENT WHERE STUDENT.Name = 'Ava Alyx' AND STUDENT.Major = DEPARTMENT.Code AND DEPARTMENT.Head = PROF.Login;
1239 ~~~
1240
1241 ### Aliasing Tuples
1242
1243 ~~~{.sql}
1244 SELECT A.Name FROM PROF AS A, DEPARTMENT, STUDENT AS B WHERE B.Name = 'Ava Alyx' AND B.Major = DEPARTMENT.Code AND DEPARTMENT.Head = A.Login;
1245 ~~~
1246
1247 ~~~{.sql}
1248 SELECT Others.Login FROM GRADE AS Mine, GRADE AS Others WHERE Mine.Login = 'aalyx' and Mine.Grade < Others.Grade;
1249 ~~~
1250
1251 ---
1252
1253 ~~~{.sql}
1254 SELECT Fellow.Name AS 'Fellow of Ava'
1255 FROM STUDENT AS Me, STUDENT AS Fellow
1256 WHERE Me.Name = 'Ava Alyx' AND Fellow.Major = Me.Major AND NOT Fellow.Name = 'Ava Alyx';
1257 ~~~
1258
1259 ### Nested Queries
1260
1261 ~~~{.sql}
1262 SELECT Login FROM GRADE WHERE Grade >
1263 (SELECT AVG(Grade) FROM GRADE);
1264 ~~~
1265
1266 Outer query, inner query.
1267 (Average of all non NULL values.)
1268
1269 ~~~{.sql}
1270 SELECT Login FROM GRADE WHERE Grade >= ALL (SELECT Grade FROM GRADE WHERE Grade IS NOT NULL);
1271
1272 SELECT Login
1273 FROM PROF
1274 WHERE DEPARTMENT IN ( SELECT Major
1275 FROM STUDENT
1276 WHERE Login LIKE '%a');
1277 ~~~
1278
1279 Answer to questions:
1280
1281 - Order of clause does not matter, not even for optimization purpose.
1282 - `SELECT COUNT(DISTINCT Name) FROM STUDENT;`
1283 - About Semantics / Explicit / Implicit Constraints, your textbook reads, pp. 67 - 69:
1284 1. Constraints that are inherent in the data model. We call these inherent model-based constraints or implicit constraints.
1285 2. Constraints that can be directly expressed in schemas of the data model, typically by specifying them in the DDL (data definition language, see Section 2.3.1). We call these schema-based constraints or explicit constraints.
1286 3. Constraints that cannot be directly expressed in the schemas of the data model, and hence must be expressed and enforced by the application programs. We call these application-based or semantic constraints or business rules.
1287
1288 Check is indeed explicit, in that respect, since it can be specified in the data model.
1289 But it's a terrible example, since Check does nothing, and has to be simulated with triggers or so (hence becoming a semantics constraints).
1290
1291 - You can `CREATE` views <https://dev.mysql.com/doc/refman/5.7/en/create-view.html>
1292
1293
1294
1295 3. More Select Queries
1296 a. Select-project-join (4.3.1)
1297 b. Aliases (4.3.2)
1298 c. Nested Queries (5.1.2)
1299
1300
1301
1302 ## More Select Queries
1303
1304 ### Select-project-join (4.3.1)
1305
1306 ~~~{.sql}
1307 SELECT Login FROM PROF, DEPARTMENT WHERE DEPARTMENT.Name = 'Mathematics' AND Department = Code;
1308 ~~~
1309
1310 - `Department.Name = 'Mathematics'` is the selection condition
1311 - `Department = Code` is the join condition, because it combines two tuples.
1312 - Why do we use the fully qualified Name attribute for `Name`?
1313
1314 ~~~{.sql}
1315 SELECT Name FROM STUDENT, GRADE WHERE Grade > 3.0 AND STUDENT.Login = GRADE.Login;
1316 ~~~
1317
1318 - `Grade > 3.0` is the selection condition
1319 - `STUDENT.Login = GRADE.Login` is the join condition
1320
1321 We can have two join conditions!
1322
1323 ~~~{.sql}
1324 SELECT PROF.Name FROM PROF, DEPARTMENT, STUDENT WHERE STUDENT.Name = 'Ava Alyx' AND STUDENT.Major = DEPARTMENT.Code AND DEPARTMENT.Head = PROF.Login;
1325 ~~~
1326
1327 ### Aliasing Tuples
1328
1329 ~~~{.sql}
1330 SELECT A.Name FROM PROF AS A, DEPARTMENT, STUDENT AS B WHERE B.Name = 'Ava Alyx' AND B.Major = DEPARTMENT.Code AND DEPARTMENT.Head = A.Login;
1331 ~~~
1332
1333 ~~~{.sql}
1334 SELECT Others.Login FROM GRADE AS Mine, GRADE as Others WHERE Mine.Login = 'aalyx' and Mine.Grade < Others.Grade;
1335 ~~~
1336
1337 ~~~{.sql}
1338 SELECT Fellow.Name AS 'Fellow of Ava'
1339 FROM STUDENT AS Me, STUDENT AS Fellow
1340 WHERE Me.Name = 'Ava Alyx' AND Fellow.Major = Me.Major AND NOT Fellow.Name = 'Ava Alyx';
1341 ~~~
1342
1343 ### Nested Queries
1344
1345 ~~~{.sql}
1346 SELECT Login FROM GRADE WHERE Grade >
1347 (SELECT AVG(Grade) FROM GRADE);
1348 ~~~
1349
1350 Outer query, inner query.
1351 (Average of all non NULL values.)
1352
1353 ~~~{.sql}
1354 SELECT Login FROM GRADE WHERE Grade >= ALL (SELECT Grade FROM GRADE WHERE Grade IS NOT NULL);
1355
1356 SELECT Login
1357 FROM PROF
1358 WHERE DEPARTMENT IN ( SELECT Major
1359 FROM STUDENT
1360 WHERE Login LIKE '%a');
1361 ~~~
1362
1363 Why can't we use `=`?
1364 Here, we can, because a student will have only 1 major: need to improve this example!
1365 Also, if `=` can be used, then a nested query isn't needed.
1366
1367 ## Exercises
1368
1369 Exercise +.#
1370 ~ What does it mean to say that `SQL` is at the same time a "data definition language" and a "data manipulation language"?
1371
1372 Exercise +.#
1373 ~ Name three kind of objects (for lack of a better word) a `CREATE` statement can create.
1374
1375 Exercise +.#
1376 ~ Write a `SQL` statement that adds a primary key constraint to an attribute named `Id` in an already existing table named `STAFF`.
1377
1378 Exercise +.#
1379 ~ Complete the following table wo different examples when asked for examples:
1380
1381 <!-- Color? -->
1382
1383 Data Type | Examples |
1384 --- | --- |
1385 **?** | $4$, $-32$
1386 Char(4) | **?**
1387 VarChar(10) | 'Train', 'Michelle'
1388 Bit(4) | **?**
1389 **?** | TRUE, UNKNOWN
1390
1391 Exercise +.#
1392 ~ Explain what the following `SQL` statement does
1393
1394 ~~~{.sqlmysql}
1395 CREATE SCHEMA Faculty;
1396 ~~~
1397
1398 Exercise +.#
1399 ~ If I want to enter January 21, 2016, as a value for an attribute with the `DATE` datatype, what value should I enter?
1400
1401 Exercise +.#
1402 ~ Write a statement that inserts the values "Thomas" and "$4$" into the table `TRAINS`.
1403
1404
1405 Exercise +.#
1406 ~ If `PkgName` is a primary key in the table `MYTABLE`, what can you tell about the number of rows returned by the following statement?
1407 ```{.sqlmysql}
1408 SELECT * FROM MYTABLE WHERE PkgName = 'MySQL';
1409 ```
1410
1411 Exercise +.#
1412 ~ What is the difference between an implicit, an explicit, and a semantic constraint?
1413
1414 Exercise +.#
1415 ~ If you want every tuple referencing the tuple you're about to delete to be deleted as well, what mechanism should you use?
1416
1417 Exercise +.#
1418 ~ If a database designer is using the `ON UPDATE SET NULL` for a foreign key, what mechanism is he implementing (i.e., describe how the database will react a certain operation)?
1419
1420 Exercise +.#
1421 ~ If the following is part of the design of a table:
1422
1423 ~~~{.sqlmysql}
1424 FOREIGN KEY (DptNumber) REFERENCES DEPARTMENT(DptNumber) ON DELETE SET DEFAULT ON UPDATE CASCADE
1425 ~~~
1426
1427 What happen to the row whose foreign key `DptNumber` is set to $3$ if
1428
1429 #. the row in the `DEPARTEMENT` table with primary key `DptNumber` set to \(3\) is deleted?
1430 #. the row in the `DEPARTEMENT` table with primary key `DptNumber` set to \(3\) as its value for `DptNumber` updated to \(5\)?
1431
1432 Exercise +.#
1433 ~ If the following is part of the design of a `WORKER` table:
1434
1435 ~~~{.sqlmysql}
1436 FOREIGN KEY WORKER(DptNumber) REFERENCES DEPARTMENT(DptNumber) ON UPDATE CASCADE
1437 ~~~
1438
1439 Admitting there is a row in the `WORKER` table whose foreign key `DptNumber` is set to $3$, what would happen if
1440
1441 #. We tried to delete the row in the `DEPARTEMENT` table with primary key `DptNumber` set to \(3\)?
1442 #. We tried to change the value of `DptNumber` of the row in the `DEPARTEMENT` table with primary key `DptNumber` set to \(3\)?
1443
1444 Exercise +.#
1445 ~ Given a relation `TOURIST(Name, EntryDate, Address)`, write a `SQL` statement printing the name and address of all the tourists who entered the territory after the 15 September, 2012.
1446
1447 Exercise +.#
1448 ~ What is the fully qualified name of an attribute? Give an example.
1449
1450 Exercise +.#
1451 ~ If `DEPARTMENT` is a database, what is `DEPARTMENT.*`?
1452
1453 Exercise +.#
1454 ~ What is a multi-set? What does it mean to say that SQL treats tables as multisets?
1455
1456 Exercise +.#
1457 ~ What is the difference between
1458
1459 ~~~{.sqlmysql}
1460 SELECT ALL * FROM MYTABLE;
1461 ~~~
1462
1463 and
1464
1465 ~~~{.sqlmysql}
1466 SELECT DISTINCT * FROM MYTABLE;
1467 ~~~
1468
1469 How are the results the same? How are they different?
1470
1471
1472 Exercise +.#
1473 ~ Describe what the star do in the statement `SELECT ALL * FROM MYTABLE;`.
1474
1475 Exercise +.#
1476 ~ What is wrong with the statement
1477
1478 ~~~{.sqlmysql}
1479 SELECT * WHERE Name = 'CS' FROM DEPARTMENT;
1480 ~~~
1481
1482 Exercise +.#
1483 ~ When is it useful to use a select-project-join query?
1484
1485 Exercise +.#
1486 ~ When is a tuple variable useful?
1487
1488 Exercise +.#
1489 ~ Write a query that changes the name of the professor whose login is 'caubert' to 'Hugo Pernot' in the table `PROF`.
1490
1491 Exercise +.#
1492 ~ Can an `UPDATE` statement have a `WHERE` condition using an attribute that isn't the primary key? If no, justify, if yes, tell what could happen.
1493
1494 Exercise +.#
1495 ~ What is a multi-set? What does it mean to say that `SQL` treats tables as multisets?
1496
1497
1498 Exercise +.#
1499 ~ What is the difference between those two queries?
1500
1501 ~~~{.sqlmysql}
1502 SELECT ALL * FROM MYTABLE;
1503 ~~~
1504
1505 and
1506
1507 ~~~{.sqlmysql}
1508 SELECT DISTINCT * FROM MYTABLE;
1509 ~~~
1510
1511 How are the results the same? How are they different?
1512
1513
1514 Exercise +.#
1515 ~ What are the possible meanings or interpretations for a `NULL` value?
1516
1517 Exercise +.#
1518 ~ What are the values of the following expressions (i.e., do they evaluate to `TRUE`, `FALSE`, or `UNKNOWN`)?
1519
1520 `TRUE AND FALSE`\hspace{2.2em}
1521 `TRUE AND UNKNOWN`\hspace{2.2em}
1522 `NOT UNKNOWN`\hspace{2.2em}
1523 `FALSE OR UNKNOWN`
1524
1525 Exercise +.#
1526 ~ What comparison expression should you use to test if a value is different from `NULL`?
1527
1528
1529 Exercise +.#
1530 ~ Explain this query:
1531
1532 ~~~{.sqlmysql}
1533 SELECT Login
1534 FROM PROF
1535 WHERE Department IN ( SELECT Major
1536 FROM STUDENT
1537 WHERE Login = 'jrakesh');
1538 ~~~
1539
1540 Exercise +.#
1541 ~ What is wrong with this query?
1542
1543 ~~~{.sqlmysql}
1544 SELECT Name
1545 FROM STUDENT
1546 WHERE Login IN ( SELECT Code
1547 FROM Department
1548 WHERE head = 'aturing');
1549 ~~~
1550
1551
1552 Exercise +.#
1553 ~ Write a query that returns the number of row (i.e., of entries, of tuples) in a table named `BOOK`.
1554
1555 Exercise +.#
1556 ~
1557 Consider the following `SQL` code:
1558
1559 ~~~{.sqlmysql}
1560 CREATE TABLE COMPUTER(
1561 Id VARCHAR(20) PRIMARY KEY,
1562 Model VARCHAR(20)
1563 );
1564
1565 CREATE TABLE PRINTER(
1566 Id VARCHAR(20) PRIMARY KEY,
1567 Model VARCHAR(20)
1568 );
1569
1570 CREATE TABLE CONNEXION(
1571 Computer VARCHAR(20),
1572 Printer VARCHAR(20),
1573 PRIMARY KEY(Computer, Printer),
1574 FOREIGN KEY (Computer) REFERENCES COMPUTER(Id),
1575 FOREIGN KEY (Printer) REFERENCES PRINTER(Id)
1576 );
1577
1578 INSERT INTO COMPUTER VALUES
1579 ('A', 'DELL A'),
1580 ('B', 'HP X'),
1581 ('C', 'ZEPTO D'),
1582 ('D', 'MAC Y');
1583
1584 INSERT INTO PRINTER VALUES
1585 ('12', 'HP-140'),
1586 ('13', 'HP-139'),
1587 ('14', 'HP-140'),
1588 ('15', 'HP-139');
1589
1590 INSERT INTO CONNEXION VALUES
1591 ('A', '12'),
1592 ('A', '13'),
1593 ('B', '13'),
1594 ('C', '14');
1595 ~~~
1596
1597 Write a query that returns … (in parenthesis, the values returned \emph{in this set-up}, but you have to be general)
1598
1599 #. … the number of computers connected to the printer whose id is '13' (i.e., \(2\) ).
1600 #. … the number of different models of printers (i.e., \(2\)).
1601 #. … the model(s) of the printer connected to the computer whose id is 'A' (i.e., 'HP-140' and 'HP-139').
1602 #. … the id of the computer(s) not connected to any printer (i.e., 'D').
1603
1604 Exercise +.#
1605 ~ Write a query that returns the sum of all the values stored in the `Pages` attribute of a `BOOK` table.
1606
1607 Exercise +.#
1608 ~ Write a query that adds a `Pages` attribute of type `INT` into a (already existing) `BOOK` table.
1609
1610 Exercise +.#
1611 ~ Write a query that removes the default value for a `Pages` attribute in a `BOOK` table.
1612
1613 ## Solution to Exercises
1614
1615 Solution +.#
1616 ~ It can specify the conceptual and internal schema, **and** it can manipulate the data.
1617
1618 Solution +.#
1619 ~ Database (schema), table, view, assertion, trigger, etc.
1620
1621 Solution +.#
1622 ~ ~~~{.sqlmysql}
1623 ALTER TABLE STAFF ADD PRIMARY KEY(Id);
1624 ~~~
1625
1626 <!-- Bogue -->
1627
1628 Solution +.#
1629
1630 <!-- Bogue table et solution, Color? -->
1631
1632 Data Type | Examples |
1633 Int | $4$, $-32$
1634 Char(4) | 'trai', 'plol'
1635 VarChar(10) | 'Train', 'Michelle'
1636 Bit(4) | B'1010', B'0101'
1637 Boolean | TRUE, UNKNOWN
1638
1639 Solution +.#
1640 ~ It creates a schema, i.e., a database, named "Faculty".
1641
1642 Solution +.#
1643 ~ `DATE`'2016-01-21'
1644
1645 Solution +.#
1646 ~
1647 ~~~{.sqlmysql}
1648 INSERT INTO TRAINS VALUES('Thomas', 4);
1649 ~~~
1650
1651 <!-- Bogue! -->
1652
1653 Solution +.#
1654 ~ Yes.
1655
1656 Solution +.#
1657 ~ The textbook reads, pp. 67 - 69:
1658
1659 #. Constraints that are inherent in the data model. We call these inherent model-based constraints or implicit constraints.
1660 #. Constraints that can be directly expressed in schemas of the data model, typically by specifying them in the DDL (data definition language, see Section 2.3.1). We call these schema-based constraints or explicit constraints.
1661 #. Constraints that cannot be directly expressed in the schemas of the data model, and hence must be expressed and enforced by the application programs. We call these application-based or semantic constraints or business rules.
1662
1663 Solution +.#
1664 ~ We should use a referential triggered action clause,
1665
1666 ~~~{.sqlmysql}
1667 ON DELETE CASCADE
1668 ~~~
1669
1670 Solution +.#
1671 ~ If the referenced tuple is updated, then the attribute of the referencing relation are set to NULL.
1672
1673 Solution +.#
1674 ~ The department number is set to the default value. The department number is updated accordingly.
1675
1676 Solution +.#
1677 ~ ~~~{.sqlmysql}
1678 SELECT Name, Address
1679 FROM TOURIST
1680 WHERE EntryDate > DATE'2012-09-15';
1681 ~~~
1682
1683 <!-- Bogue -->
1684
1685 Solution +.#
1686 ~ The name of the relation with the name of its schema and a period beforehand. myDB.MYTABLE, EMPLOYEE.name, etc.
1687
1688 Solution +.#
1689 ~ All the tables in that database.
1690
1691 Solution +.#
1692 ~ A set where the same value can occur twice. The same tuple can occur twice in a table.
1693
1694 Solution +.#
1695 ~ All will print the duplicate, distinct will eliminate them.
1696
1697
1698
1699 Solution +.#
1700 ~ It selects all the attributes.
1701
1702 Solution +.#
1703 ~ You can't have the `WHERE` before `FROM`.
1704
1705 Solution +.#
1706 ~ We use those query that projects on attributes using a selection and join conditions when we need to look for information gathered in multiple tables.
1707
1708 Solution +.#
1709 ~ It makes the distinction between two different copies of the same relation, it is useful when we want to select a tuple in a relation that is in a particular relation with a tuple in the same relation.
1710
1711 Cf. <https://stackoverflow.com/a/7698796/2657549>: They are useful for saving typing, but there are other reasons to use them:
1712
1713 - If you join a table to itself you must give it two different names otherwise referencing the table would be ambiguous.
1714 - It can be useful to give names to derived tables, and in some database systems it is required... even if you never refer to the name.
1715
1716 Solution +.#
1717 ~ ~~~{.sqlmysql}
1718 UPDATE PROF SET Name = 'Hugo Pernot' WHERE Login = 'caubert';
1719 ~~~
1720
1721 Solution +.#
1722 ~ Yes, we could update more than one tuple at a time.
1723
1724 Solution +.#
1725 ~ A set where the same value can occur twice.
1726 The same tuple can occur twice in a table.
1727
1728 Solution +.#
1729 ~ `ALL` will print the duplicate, `DISTINCT` will eliminate them.
1730
1731 Solution +.#
1732 ~ Unknown value, unavailable / withheld, N/A.
1733
1734 Solution +.#
1735 ~ `FALSE`, `UNKNOWN`, `UNKNOWN`, `FALSE`
1736
1737 Solution +.#
1738 ~ `IS NOT`
1739
1740 Solution +.#
1741 ~ It list the login of the professors teaching in the department where the student whose login is "jrakesh" is majoring.
1742
1743
1744 Solution +.#
1745 ~ It tries to find a `Login` in a `Code`!
1746
1747 Solution +.#
1748 ~ `SELECT COUNT(*) FROM BOOK;`
1749
1750 Solution +.#
1751 ~ This solution is missing
1752
1753
1754 Solution +.#
1755 ~ `SELECT SUM(Pages)FROM BOOK;`
1756
1757 Solution +.#
1758 ~ `ALTER TABLE BOOK ADD COLUMN Pages INT;`
1759
1760 Solution +.#
1761 ~ `ALTER TABLE BOOK ALTER COLUMN Pages DROP DEFAULT;`
1762
1763
1764 ## Problems
1765
1766 ### Setting Up MySQL
1767
1768 Problem -.+.#installation
1769
1770 In this problem, you will install the [MySQL](https://www.mysql.com/) DataBase Managment System and set it up.
1771 On top of being open source and free, it is one of the most widespread and used DBMS, as well as one of the most well-documented.
1772 Linux users will use its community-developed fork, \href{https://mariadb.org/}{MariaDB}, but that won't make a difference in this course.
1773
1774 It is very important that you follow the steps below carefully.
1775 Read the messages printed on your screen, make sure a step was correctly executed before moving to the next one.
1776 And, remember:
1777
1778 1. Don't wait, set your system early.
1779 2. I'm willing to help you, but there's nothing I can do with an email like "It doesn't work": if you look for help, be detailed and clear about what you think went wrong.
1780
1781 The following links could be useful:
1782
1783 - <https://dev.mysql.com/doc/refman/5.7/en/windows-installation.html>,
1784 - <https://dev.mysql.com/doc/refman/5.7/en/linux-installation-native.html>,
1785 - <https://dev.mysql.com/doc/refman/5.7/en/connecting-disconnecting.html> and
1786 - <https://www.linode.com/docs/databases/mysql/how-to-install-mysql-on-debian-8>
1787
1788
1789 #### Installation
1790
1791 Below are the instructions for Windows 10 and for Linux.
1792 It is perfectly acceptable to install MySQL on a virtual machine for this class (remember that on <http://spots.augusta.edu/tschultz/resources/SWAvailable.html>, you can have access to VMware and Windows licences, but using [Virtual Box](https://www.virtualbox.org/wiki/Downloads) or Linux should also work fine).
1793 Once this step is completed, or if MySQL is already installed on your computer, go to the next step.
1794
1795 - **For Windows 10**
1796 1. Visit <https://dev.mysql.com/downloads/installer/>, click on "Download" next to "Windows (x86, 32-bit), MSI Installer 5.7.20 18.5M (mysql-installer-web-community-5.7.20.0.msi)". On the next page, click on the (somewhat hidden) "No thanks, just start my download." button.
1797 2. Save the "mysql-installer-web-community-5.7.20.0.msi" file, and open it. If there is an updated version of the installer available, agree to download it. Accept the license term.
1798 3. We will now install the various components needed for this class, leaving all the choices by defaults. This means that you need to do the following:
1799 1. Leave the first option on "Developer Default" and click on "Next"
1800 2. Click on "Next" even if you don't meet all the requirements
1801 3. Click on "Execute". The system will download and install several softwares (this may take some time).
1802 4. Click on "Next" twice, leave "Type and Networking" on "Standalone MySQL Server / Classic MySQL Replication" and click "Next", and leave the next options as they are (unless you know what you do and want to change the port, for instance) and click on "Next".
1803 5. \label{choose-pswd} You now need to choose a password for the MySQL root account.
1804 It can be anything, just make sure to memorize it.
1805 Click on "Next".
1806 6. On the "Windows Service" page, leave everything as it is and click on "Next".
1807 7. On the "Plugins and Extensions" page, leave everything as it is and click on "Next".
1808 8. Finally, click "Execute" on the "Apply Configuration" page, and then on "Finish".
1809 9. Click on "Cancel" on the "Product Configuration" page and confirm that you don't want to add products: we only need to have MySQL Server 5.7.20 configured.
1810 4. We now want to make sure that MySQL is running: launch Windows' "Control Panel", then click on "Administrative Tools", and on "Services". Look for "MySQL57", its status should be "Running". If it is not, right-click on it and click on "Start".
1811
1812 - **For Linux**
1813
1814 1. Install, through your standard package management system (`apt` or `aptitude` for debian-based systems, `pacman` for Arch Linux, etc.), the packages `mysql-client` and `mysql-server` as well as their dependencies.
1815 2. Open a terminal and type
1816
1817 ~~~{.bash}
1818 /etc/init.d/mysql status
1819 ~~~
1820
1821 to see if MySQL is running: if you read
1822
1823 ~~~{.bash}
1824 Active: active (running)
1825 ~~~
1826
1827 then you can move on to the next step, otherwise run (as root)
1828
1829 ~~~{.bash}
1830 service mysqld start
1831 ~~~
1832
1833 3. As root, type in your terminal
1834
1835 ~~~{.bash}
1836 mysql_secure_installation
1837 ~~~
1838
1839 You'll be asked to provide the current password for the root MySQL user: this password has not be defined yet, so just hit "Enter". You'll be asked if you want to set a new password (that you can freely chose, just make sure to memorize it). Then, answer "n" to the question "Remove anonymous users?", "Y" to "Disallow root login remotely?", "n" to "Remove test database and access to it?" and finally "Y" to "Reload privilege tables now?".
1840
1841 #### Creating an user
1842
1843 This step will create a non-root user and grant it some rights. Type the following three commands, one by one (that is, type the first one, hit "enter", type the second, hit "enter", etc. The colors are here to ease the reading, you can ignore them safely.):
1844
1845 ~~~{.sqlmysql}
1846 CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'password';
1847
1848 GRANT ALL PRIVILEGES ON `HW\_%` . * TO
1849 'testuser'@'localhost';
1850
1851 EXIT;
1852 ~~~
1853
1854 The message prompted after the two first commands should be
1855
1856 ~~~{.sqlmysql}
1857 Query OK, 0 rows affected (0.00 sec)
1858 ~~~
1859
1860 and the message after the last command should be
1861
1862
1863 ~~~{.sqlmysql}
1864 Bye
1865 ~~~
1866
1867 Be careful: back-tics are surrounding
1868
1869 ~~~bat
1870 HW\_%
1871 ~~~
1872
1873
1874 whereas single quotes are surrounding `testuser` and `localhost` (normally, copy-and-pasting from this document should work).
1875
1876 #### Log-in
1877
1878 We now log as the normal user called "testuser".
1879
1880 Linux users should type *as a normal user, i.e., not as root*, in their terminal the following, and Windows users should type in their command prompt the following (provided working directory is still
1881
1882 ~~~{.bash}
1883 C:\Program Files\MySQL\MySQL Server 5.7\bin
1884 ~~~
1885
1886 :
1887
1888 ~~~{.bash}
1889 mysql -u testuser -p
1890 ~~~
1891
1892 Enter `password` as your password. If at some point you want to know if you are logged as root or testuser, simply enter
1893
1894 ~~~{.sqlmysql}
1895 \s;
1896 ~~~
1897
1898 #### Creating our first database
1899
1900 Now, type the following commands one by one:
1901
1902 ~~~{.sqlmysql}
1903 CREATE DATABASE HW_1Q2;
1904 USE HW_1Q2;
1905 CREATE TABLE t(i integer, n integer);
1906 INSERT INTO t VALUES (1,1),(2,2),(3,3);
1907 SELECT * FROM t;
1908 ~~~
1909
1910 After that last command, you should see
1911
1912 ~~~{.sqlmysql}
1913 +------+------+
1914 | i | n |
1915 +------+------+
1916 | 1 | 1 |
1917 | 2 | 2 |
1918 | 3 | 3 |
1919 +------+------+
1920 ~~~
1921
1922 You're all set! All you have to do is to quit, using the command
1923
1924 ~~~{.sqlmysql}
1925 EXIT;
1926 ~~~
1927
1928 **Add somewhere link to <https://dev.mysql.com/doc/mysql-windows-excerpt/5.7/en/mysql-installation-windows-path.html>**
1929
1930 ### Creating, Listind and Dropping Databases
1931
1932 Problem-.+.#creatingSchema
1933
1934 *This exercise assume you successfully completed @installation.*
1935
1936 #. Connect to your MySQL DBMS as `testuser`:
1937 - **In windows**, open a command prompt (search for "cmd") and type
1938
1939 ~~~{.bash}
1940 cd "C:\Program Files\MySQL\MySQL Server 5.7\bin"
1941 ~~~
1942
1943 - **In Linux**, open a shell (as a normal user)
1944
1945 Then, in both cases, type
1946
1947 ~~~{.text}
1948 mysql -u testuser -p
1949 ~~~
1950
1951 and enter the password `password`.
1952 If you are prompted with a message
1953
1954 ~~~{.bash}
1955 ERROR 1045 (28000): Access denied for user 'testuser'@'localhost' (using password: YES)
1956 ~~~
1957
1958 then you probably typed the wrong password.
1959 Otherwise, you should see a welcoming message from MySQL / MariaDB and a prompt.
1960
1961 #. Create a new database called `HW_2Q1`
1962
1963 ~~~{.sqlmysql}
1964 CREATE DATABASE HW_2Q1;
1965 ~~~
1966
1967 #. List the databases
1968
1969 ~~~{.sqlmysql}
1970 SHOW DATABASES;
1971 ~~~
1972
1973 Make sure `HW_2Q1` is a part of it.
1974
1975 4. Remove ("drop") the database, using
1976
1977 ~~~{.sqlmysql}
1978 DROP DATABASE HW_2Q1;
1979 ~~~
1980
1981 In the future, we will refer to the commands 1 and 2 as "log-in as `testuser` and create a database `HW_2Q1`".
1982
1983 ### Reading the Documentation
1984
1985 The goal of this problem is to learn where to find the documentation of your DBMS, and to have a first look at the syntax of SQL commands.
1986
1987 You can consult your textbook, Table~ 5.2, p. 140 (6th edition) or Table~ 7.2, p. 235 (7th edition), for a very quick summary of the most common commands.
1988 Make sure you are familiar with the Backus–Naur form (BNF) notation commonly used:
1989
1990 - non-terminal symbols (i.e., variables, parameters) are enclosed in angled brackets,
1991
1992 ~~~{.text}
1993 <...>
1994 ~~~
1995
1996 - optional parts are shown in square brackets,
1997
1998 ~~~{.text}
1999 [...]
2000 ~~~
2001
2002 - repetitons are shown in braces
2003
2004 ~~~{.text}
2005 {...}
2006 ~~~
2007
2008 - alternatives are shown in parenthesis and separated by vertical bars,
2009
2010 ~~~{.text}
2011 (...|...|...)
2012 ~~~
2013
2014 The most complete lists of commands are probably at
2015
2016 - <https://mariadb.com/kb/en/library/sql-statements/> and
2017 - <https://dev.mysql.com/doc/refman/5.7/en/sql-syntax.html>
2018
2019 Those are the commands implemented in the DBMS you are actually using.
2020 Since there are small variations from one implementation to the other, it's better to take one of this link as a reference in the future.
2021
2022 ### Creating and Using a Table
2023
2024 *This exercise, and the following ones, assume you successfully completed @installation.*
2025
2026 Log in as `testuser` and create a database `HW_2Q3`.
2027
2028 #### Setting Up the Meta-Data
2029
2030 We will first set-up our meta-data (i.e., the schema, the structure where our tables will be, and the tables themselves).
2031
2032 Let us first tell MySQL that we want to use that database
2033
2034 ~~~{.sqlmysql}
2035 USE HW_2Q3;
2036 ~~~
2037
2038 and ask what it contains
2039
2040 ~~~{.sqlmysql}
2041 SHOW TABLES;
2042 ~~~
2043
2044 Now, create a first table named `NAME`
2045
2046 ~~~{.sqlmysql}
2047 CREATE TABLE NAME(
2048 FName VARCHAR(15),
2049 LName VARCHAR(15),
2050 Id INT,
2051 PRIMARY KEY(Id)
2052 );
2053 ~~~
2054
2055 Note that the `SQL` syntax and your DBMS are completely fine with your statement spreading over multiple lines.
2056 Let us create a second table, named `ADDRESS`
2057
2058 ~~~{.sqlmysql}
2059 CREATE TABLE ADDRESS(
2060 StreetName VARCHAR(15),
2061 Number INT,
2062 Habitants INT,
2063 PRIMARY KEY(StreetName, Number)
2064 );
2065 ~~~
2066
2067 To make sure those two tables were actually created, we can use
2068
2069 ~~~{.sqlmysql}
2070 SHOW TABLES;
2071 ~~~
2072
2073 But how to make sure that you entered the attributes correctly?
2074 One way to make sure is to enter the command
2075
2076 ~~~{.sqlmysql}
2077 SHOW CREATE TABLE NAME;
2078 ~~~
2079
2080 or
2081
2082 ~~~{.sqlmysql}
2083 DESC ADDRESS;
2084 ~~~
2085
2086 and to examine carefully the message printed. You should read
2087
2088 ~~~{.plain}
2089 +------------+-------------+------+-----+---------+-------+
2090 | Field | Type| Null | Key | Default | Extra |
2091 +------------+-------------+------+-----+---------+-------+
2092 | StreetName | varchar(15) | NO | PRI | NULL| |
2093 | Number | int(11) | NO | PRI | NULL| |
2094 | Habitants | int(11) | YES | | NULL| |
2095 +------------+-------------+------+-----+---------+-------+
2096 ~~~
2097
2098 If you believe there is a mistake, you can erase ("drop") the \emph{table} (not the whole database, as we did in @creatingSchema) using
2099
2100 ~~~{.sqlmysql}
2101 DROP TABLE ADDRESS;
2102 ~~~
2103
2104 And then re-create it. Of course, you can do the same for the `NAME` table.
2105
2106 Now, let us add a foreign key to the `ADDRESS` table:
2107
2108 ~~~{.sqlmysql}
2109 ALTER TABLE ADDRESS
2110 ADD FOREIGN KEY (Habitants)
2111 REFERENCES NAME(Id);
2112 ~~~
2113
2114 And observe the modification:
2115
2116 ~~~{.sqlmysql}
2117 DESC ADDRESS;
2118 ~~~
2119
2120 #### Inserting Data
2121
2122 This second part is about data, i.e., filling our tables with actual information.
2123
2124 We begin by adding some data in the `NAME` table:
2125
2126 ~~~{.sqlmysql}
2127 INSERT INTO NAME VALUES ('Barbara', 'Liskov', 003);
2128 INSERT INTO NAME VALUES ('Tuong Lu', 'Kim', 004);
2129 INSERT INTO NAME VALUES ('Samantha', NULL, 080);
2130 ~~~
2131
2132 To display the data we just inserted, we can use:
2133
2134 ~~~{.sqlmysql}
2135 SELECT * FROM NAME;
2136 ~~~
2137
2138 Do you notice anything regarding the values we entered for the `Id` attribute?
2139
2140 We can add some data into the `ADDRESS` table (using a different syntax):
2141
2142 ~~~{.sqlmysql}
2143 INSERT INTO ADDRESS (StreetName, Number, Habitants)
2144 VALUES
2145 ('Armstrong Drive', 10019, 003),
2146 ('North Broad St.', 23, 004),
2147 ('Robert Lane', 120, NULL);
2148 ~~~
2149
2150 And let's use our first update command:
2151
2152 ~~~{.sqlmysql}
2153 UPDATE ADDRESS SET Habitants = 3 WHERE Number = 120;
2154 ~~~
2155
2156 #### Exercises
2157
2158 Now, anser the following:
2159
2160 Question -.#
2161 ~ Have a look at the formal definition of the
2162
2163 ~~~{.sqlmysql}
2164 ALTER
2165 ~~~
2166
2167 command, at <https://dev.mysql.com/doc/refman/5.7/en/alter-table.html> or <https://mariadb.com/kb/en/library/alter-table/>.
2168
2169 Question -.#
2170 ~ Draw the relations corresponding to that database, including the domains and primary, as well as foreign, keys.
2171
2172 Question -.#
2173 ~ Write a
2174
2175 ~~~{.sqlmysql}
2176 SELECT
2177 ~~~
2178
2179 statement that returns the
2180
2181 ~~~{.sqlmysql}
2182 Id
2183 ~~~
2184
2185 number of the person whose first name is "Samantha".
2186
2187 Question -.#
2188 ~ Write a statement that violate the entity integrity constraint. What is the error message returned?
2189
2190 Question -.#
2191 ~ Execute an `UPDATE` statement that violate the referential integrity constraint. What is the error message returned?
2192
2193 Question -.#
2194 ~ Write a statement that violate another kind of constraint. Explain what constraint you are violating, and explain the error message.
2195
2196 Solutions in comment.
2197
2198 <!--
2199 SELECT Id FROM NAME WHERE FName = 'Samantha';
2200 % ERROR 1062 (23000): Duplicate entry '80' for key 'PRIMARY'
2201 % ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`HW_2Q3`.`ADDRESS`, CONSTRAINT `fk_id` FOREIGN KEY (`Habitants`) REFERENCES `name` (`Id`))
2202 % ERROR 1136 (21S01): Column count doesn't match value count at row 1
2203 -->
2204
2205 ### Repetiting Tuples in MySQL {#repetition}
2206
2207 Log in as `testuser` and create a database `HW_2Q4`. Tell MySQL that you want to use that database, and create a table (I will assume you named it `EXAMPLE` in the following, but you are free to name it the way you want) with at least two attributes that have different data types. Don't declare a primary key yet. Answer the following:
2208
2209 #. Add a tuple to your table using
2210
2211 ~~~{.sqlmysql}
2212 INSERT INTO EXAMPLE VALUES(X, Y);
2213 ~~~
2214
2215 where "X" and "Y" are values with the right type.
2216 Try to add this tuple again. What do you observe? (You can use
2217
2218 ~~~{.sqlmysql}
2219 SELECT * FROM EXAMPLE;
2220 ~~~
1383 2221
1384 ```{.sql}
1385 SELECT Name FROM STUDENT, GRADE WHERE Grade > 3.0 AND STUDENT.Login = GRADE.Login;
1386 ```
2222 to observe what is stored in this table.)
1387 2223
1388 - `Grade > 3.0` is the selection condition
1389 - `STUDENT.Login = GRADE.Login` is the join condition
2224 #. Alter your table to add a primary key, using
1390 2225
1391 We can have two join conditions!
2226 ~~~{.sqlmysql}
2227 ALTER TABLE EXAMPLE ADD PRIMARY KEY (Attribute);
2228 ~~~
1392 2229
1393 ```{.sql}
1394 SELECT PROF.Name FROM PROF, DEPARTMENT, STUDENT WHERE STUDENT.Name = 'Ava Alyx' AND STUDENT.Major = DEPARTMENT.Code AND DEPARTMENT.Head = PROF.Login;
1395 ```
2230 where `Attribute` is the name of the attribute you want to be a primary key. What do you observe?
1396 2231
1397 ### Aliasing Tuples
2232 #. Empty your table using
1398 2233
1399 ```{.sql}
1400 SELECT A.Name FROM PROF AS A, DEPARTMENT, STUDENT AS B WHERE B.Name = 'Ava Alyx' AND B.Major = DEPARTMENT.Code AND DEPARTMENT.Head = A.Login;
1401 ```
2234 ~~~{.sqlmysql}
2235 DELETE FROM EXAMPLE;
2236 ~~~
2237
2238 and alter your table to add a primary key, using the command we gave at the previous step. What do you observe?
1402 2239
1403 ```{.sql}
1404 SELECT Others.Login FROM GRADE AS Mine, GRADE AS Others WHERE Mine.Login = 'aalyx' and Mine.Grade < Others.Grade;
1405 ```
2240 #. Try to add the same tuple twice. What do you observe?
1406 2241
1407 ---
1408 2242
1409 ```{.sql}
1410 SELECT Fellow.Name AS 'Fellow of Ava'
1411 FROM STUDENT AS Me, STUDENT AS Fellow
1412 WHERE Me.Name = 'Ava Alyx' AND Fellow.Major = Me.Major AND NOT Fellow.Name = 'Ava Alyx';
1413 ```
1414 ### Nested Queries
1415 2243
1416 ```{.sql}
1417 SELECT Login FROM GRADE WHERE Grade >
1418 (SELECT AVG(Grade) FROM GRADE);
1419 ```
2244 ### Prof Revisited
1420 2245
1421 Outer query, inner query.
1422 (Average of all non NULL values.)
2246 Create the `PROF`, `STUDENT`, `DEPARTMENT` and `GRADE` tables as during the lecture.
2247 Populate them with some data.
1423 2248
1424 ```{.sql}
1425 SELECT Login FROM GRADE WHERE Grade >= ALL (SELECT Grade FROM GRADE WHERE Grade IS NOT NULL);
2249 #. Create a `LECTURE` table as follows:
1426 2250
1427 SELECT Login
1428 FROM PROF
1429 WHERE DEPARTMENT IN ( SELECT Major
1430 FROM STUDENT
1431 WHERE Login LIKE '%a');
1432 ```
2251 - It should have four attributes, `Name`, `Instructor`, `Code`, and `Year`, of type `VARCHAR(25)` for the two first, `YEAR(4)`, and `CHAR(5)`.
2252 - The `Year` and `Code` attributes should be the primary key (yes, have *two* attributes be the primary key).
2253 - The `Instructor` attribute should be a foreign key referencing the `Login` attribute in `PROF`.
1433 2254
1434 Answer to questions:
2255 #. Populate the `LECTURE` table with some made-up data.
1435 2256
1436 - Order of clause does not matter, not even for optimization purpose.
1437 - `SELECT COUNT(DISTINCT Name) FROM STUDENT;`
1438 - About Semantics / Explicit / Implicit Constraints, your textbook reads, pp. 67 - 69:
1439 1. Constraints that are inherent in the data model. We call these inherent model-based constraints or implicit constraints.
1440 2. Constraints that can be directly expressed in schemas of the data model, typically by specifying them in the DDL (data definition language, see Section 2.3.1). We call these schema-based constraints or explicit constraints.
1441 3. Constraints that cannot be directly expressed in the schemas of the data model, and hence must be expressed and enforced by the application programs. We call these application-based or semantic constraints or business rules.
2257 #. Add two columns to the `GRADE` table, using
1442 2258
1443 Check is indeed explicit, in that respect, since it can be specified in the data model.
1444 But it's a terrible example, since Check does nothing, and has to be simulated with triggers or so (hence becoming a semantics constraints).
2259 ~~~{.sqlmysql}
2260 ALTER TABLE GRADE
2261 ADD COLUMN LectureCode CHAR(5),
2262 ADD COLUMN LectureYear YEAR(4);
2263 ~~~
1445 2264
1446 - You can `CREATE` views <https://dev.mysql.com/doc/refman/5.7/en/create-view.html>
2265 #. Use `DESCRIBE` and `SELECT` to observe the schema of the `GRADE` table and its rows (i.e., tuples). Is that what you would have expected?
1447 2266
2267 #. Add a foreign key in `GRADE`, using
1448 2268
2269 ~~~{.sqlmysql}
2270 ALTER TABLE GRADE
2271 ADD FOREIGN KEY (LectureYear, LectureCode)
2272 REFERENCES LECTURE(Year, Code);
2273 ~~~
1449 2274
1450 3. More Select Queries
1451 a. Select-project-join (4.3.1)
1452 b. Aliases (4.3.2)
1453 c. Nested Queries (5.1.2)
2275 #. Update the tuples in `GRADE` with some made-up data: now, every row should contain, on top of a login and a grade, a lecture year and a lecture code.
2276 #. Write `SELECT` statements answering the following questions (where XXX and YY should be relevant values considering your data):
1454 2277
2278 #. "I taught class XXX in YYYY, could you give me the logins and grades of the students who took it?"
2279 #. "Could you list the instructors who taught in YYYY?" (and, please, avoid duplicates)
2280 #. "Could your list the name and grade of all the student who took class XXX (no matter the year)?"
2281 #. "Could you tell me which years was the class XXX taught?"
2282 #. "Could you list the classes taught the same year as class XXX?"
2283 #. "Could you print the name of the students who registered after Ava Alyx?"
2284 #. "How many departments' heads are teaching this year?"
2285
2286 ## Solution to Selected Problems
1455 2287
2288 ###
2289 Solution for @#repetition
2290 ~
1456 2291
1457 ## More Select Queries
2292 ~~~{.sqlmysql}
2293 CREATE TABLE EXAMPLE(
2294 X VARCHAR(15),
2295 Y INT);
2296 ~~~
1458 2297
1459 ### Select-project-join (4.3.1)
2298 ~~~{.sqlmysql}
2299 INSERT INTO EXAMPLE VALUES('Train', 4);
2300 ~~~
1460 2301
1461 ```{.sql}
1462 SELECT Login FROM PROF, DEPARTMENT WHERE DEPARTMENT.Name = 'Mathematics' AND Department = Code;
1463 ```
2302 OK to insert same tuple twice.
1464 2303
1465 - `Department.Name = 'Mathematics'` is the selection condition
1466 - `Department = Code` is the join condition, because it combines two tuples.
1467 - Why do we use the fully qualified Name attribute for `Name`?
2304 ~~~{.sqlmysql}
2305 ALTER TABLE EXAMPLE ADD PRIMARY KEY (X);
2306 ERROR 1062 (23000): Duplicate entry 'Train' for key 'PRIMARY'
2307 ~~~
1468 2308
1469 ```{.sql}
1470 SELECT Name FROM STUDENT, GRADE WHERE Grade > 3.0 AND STUDENT.Login = GRADE.Login;
1471 ```
2309 ### Solution For Prof Revisited
1472 2310
1473 - `Grade > 3.0` is the selection condition
1474 - `STUDENT.Login = GRADE.Login` is the join condition
2311 %Solution +.#
1475 2312
1476 We can have two join conditions!
2313 ~~~{.sqlmysql}
2314 CREATE TABLE LECTURE(
2315 Name VARCHAR(25),
2316 Instructor VARCHAR(25),
2317 Year YEAR(4),
2318 Code CHAR(5),
2319 PRIMARY KEY(Year, Code),
2320 FOREIGN KEY (Instructor) REFERENCES PROF(Login)
2321 );
1477 2322
1478 ```{.sql}
1479 SELECT PROF.Name FROM PROF, DEPARTMENT, STUDENT WHERE STUDENT.Name = 'Ava Alyx' AND STUDENT.Major = DEPARTMENT.Code AND DEPARTMENT.Head = PROF.Login;
1480 ```
2323 INSERT INTO LECTURE VALUES
2324 ('Intro to CS', 'caubert', 2017, '1304'),
2325 ('Intro to Algebra', 'perdos', 2017, '1405'),
2326 ('Intro to Cyber', 'aturing', 2017, '1234');
1481 2327
1482 ### Aliasing Tuples
2328 ALTER TABLE GRADE ADD COLUMN LectureCode CHAR(5),
2329 ADD COLUMN LectureYear YEAR(4);
1483 2330
1484 ```{.sql}
1485 SELECT A.Name FROM PROF AS A, DEPARTMENT, STUDENT AS B WHERE B.Name = 'Ava Alyx' AND B.Major = DEPARTMENT.Code AND DEPARTMENT.Head = A.Login;
1486 ```
2331 DESCRIBE GRADE;
1487 2332
1488 ```{.sql}
1489 SELECT Others.Login FROM GRADE AS Mine, GRADE as Others WHERE Mine.Login = 'aalyx' and Mine.Grade < Others.Grade;
1490 ```
2333 SELECT * FROM GRADE;
1491 2334
1492 ```{.sql}
1493 SELECT Fellow.Name AS 'Fellow of Ava'
1494 FROM STUDENT AS Me, STUDENT AS Fellow
1495 WHERE Me.Name = 'Ava Alyx' AND Fellow.Major = Me.Major AND NOT Fellow.Name = 'Ava Alyx';
1496 ```
1497 ### Nested Queries
2335 ALTER TABLE GRADE ADD FOREIGN KEY (LectureYear, LectureCode) REFERENCES LECTURE(Year, Code);
1498 2336
1499 ```{.sql}
1500 SELECT Login FROM GRADE WHERE Grade >
1501 (SELECT AVG(Grade) FROM GRADE);
1502 ```
2337 UPDATE GRADE SET LectureCode = '1304', LectureYear = 2017 WHERE Login = 'jrakesh' AND Grade = '2.85';
2338 UPDATE GRADE SET LectureCode = '1405', LectureYear = 2017 WHERE Login = 'svlatka' OR (Login = 'jrakesh' AND Grade = '3.85');
2339 UPDATE GRADE SET LectureCode = '1234', LectureYear = 2017 WHERE Login = 'aalyx' OR Login = 'cjoella';
1503 2340
1504 Outer query, inner query.
1505 (Average of all non NULL values.)
2341 SELECT Login, Grade FROM Grade WHERE Lecturecode='1304' and LectureYear = '2017';
1506 2342
1507 ```{.sql}
1508 SELECT Login FROM GRADE WHERE Grade >= ALL (SELECT Grade FROM GRADE WHERE Grade IS NOT NULL);
2343 SELECT DISTINCT Instructor FROM LECTURE WHERE year = 2017;
1509 2344
1510 SELECT Login
1511 FROM PROF
1512 WHERE DEPARTMENT IN ( SELECT Major
1513 FROM STUDENT
1514 WHERE Login LIKE '%a');
1515 ```
2345 SELECT Name, Grade FROM STUDENT, GRADE WHERE GRADE.LectureCode = 1405 AND STUDENT.Login = GRADE.Login;
1516 2346
1517 Why can't we use `=`?
1518 Here, we can, because a student will have only 1 major: need to improve this example!
1519 Also, if `=` can be used, then a nested query isn't needed.
2347 SELECT Year FROM Lecture WHERE Code = '1234';
2348
2349 SELECT Name FROM LECTURE WHERE Year IN (SELECT Year FROM LECTURE WHERE CODE = '1234');
2350
2351 SELECT B.name FROM STUDENT AS A, STUDENT AS B WHERE A.Name = 'Ava Alyx' AND A.Registered > B.Registered;
1520 2352
2353 SELECT COUNT(DISTINCT PROF.Name) AS 'Head Teaching This Year' FROM LECTURE, DEPARTMENT, PROF WHERE Year = 2017 AND Instructor = Head AND Head = PROF.Login;
2354 ~~~
1521 2355
1522 2356 # Review Session # Review Session
1523 2357
 
... ... Loosing information inadvertently
1869 2703 Updated have to be consistent. Updated have to be consistent.
1870 2704
1871 2705 Example: Example:
1872 ```
2706 ~~~
2707
1873 2708 ---------- (Login, Name, AdvisoryName, AdvisorOffice, Major, MajorHead) ---------- (Login, Name, AdvisoryName, AdvisorOffice, Major, MajorHead)
1874 2709
1875 2710 -----------(Office, PhoneNumber, Building) -----------(Office, PhoneNumber, Building)
1876 ```
2711 ~~~
1877 2712
1878 2713 1. Advisor without student 1. Advisor without student
1879 2714 2. Delete last student of advisor 2. Delete last student of advisor
 
... ... Example:
1885 2720
1886 2721 Example: Example:
1887 2722
1888 ```
2723 ~~~
2724
1889 2725 STUDENT(Login, ..., siblingEnrolled) STUDENT(Login, ..., siblingEnrolled)
1890 ```
2726 ~~~
1891 2727
1892 2728 Transform into "Emergency Contact in University" relation (bonus: allow multiple contacts). Transform into "Emergency Contact in University" relation (bonus: allow multiple contacts).
1893 2729
 
... ... Check: 1) Clear Semantics, 2) Absence of Anomalies, 3) Rarity of NULL, 4) Identi
1903 2739
1904 2740 Goals: To avoid redundant work, loss of info., difficulties to select / join, redundancy. Goals: To avoid redundant work, loss of info., difficulties to select / join, redundancy.
1905 2741
1906 ```
2742 ~~~
2743
1907 2744 MARKER(Owner, Color, OwnerOffice, Brand, BrandEmail) MARKER(Owner, Color, OwnerOffice, Brand, BrandEmail)
1908 2745
1909 2746 TEACHER(Office, Name, Phone) TEACHER(Office, Name, Phone)
1910 ```
2747 ~~~
1911 2748
1912 2749 Corrected to: Corrected to:
1913 2750
1914 ```
2751 ~~~
2752
1915 2753 MARKER(Owner, Color, Brand) MARKER(Owner, Color, Brand)
1916 2754
1917 2755 TEACHER(Office, Name, Phone) TEACHER(Office, Name, Phone)
1918 2756
1919 2757 BRAND(Name, Email) BRAND(Name, Email)
1920 ```
2758 ~~~
1921 2759
1922 2760 Brand, Name and Name being the ID. Brand, Name and Name being the ID.
1923 2761
 
... ... Formal tool to assess how "good" a database is, a property of the relation schem
1931 2769
1932 2770 Let us list all the attributes of our previous example: Let us list all the attributes of our previous example:
1933 2771
1934 ```
2772 ~~~
2773
1935 2774 MARKER.Owner, MARKER.Color, MAKER.Brand, TEACHER.Office, TEACHER.Name, TEACHER.Phone, BRAND.Name, BRAND.Email MARKER.Owner, MARKER.Color, MAKER.Brand, TEACHER.Office, TEACHER.Name, TEACHER.Phone, BRAND.Name, BRAND.Email
1936 ```
2775 ~~~
1937 2776
1938 2777 Think about their dependencies, and list them: Think about their dependencies, and list them:
1939 2778
 
... ... Sources:
2213 3052 **Example: cf. review session.** **Example: cf. review session.**
2214 3053
2215 3054
3055 ## Exercises
3056
3057 Exercise +.#
3058 ~ What could be the decomposition of an attribute used to store an email address? When could that be useful?
3059
3060 Exercise +.#
3061 ~ Draw the ER diagram for a "COMPUTER" entity that has one multivalued attribute "Operating\_System", a composite attribute "Devices" (decomposed into "Keyboard" and "Mouse") and an "Id" key attribute.
3062
3063 Exercise +.#
3064 ~ Draw the ER diagram for a "CELLPHONE" entity that has a composite attribute "Plan" (decomposed into "Carrier" and "Price"), a "Mobile\_identification\_number" key attribute, and a multi-valued "App\_Installed" attribute.
3065
3066 Exercise +.#
3067 ~ Name one difference between a primary key in the relational model, and a key attribute in the ER model.
3068
3069 Exercise +.#
3070 ~ What is the difference between an entity type and a weak entity type?
3071
3072 Exercise +.#
3073 ~ What is the degree of a relationship type?
3074
3075 Exercise +.#
3076 ~ What is a self-referencing, or recursive, relationship type? Give two examples.
3077
3078 Exercise +.#
3079 ~ What does it mean for a binary relationship type "Owner" between entity types "Person" and "Computer" to have a cardinality ration $M:N$?
3080
3081 Exercise +.#
3082 ~ What are the two possible structural constraints on a relationship type?
3083
3084 Exercise +.#
3085 ~ Under what condition(s) can an attribute of a binary relationship type be migrated to become an attribute of one of the participating entity type?
3086
3087 Exercise +.#
3088 ~ What is a partial key?
3089
3090 Exercise +.#
3091 ~ For the following binary relationships, suggest cardinality ratios based on the common-sense meaning of the entity types.
3092
3093 **Entity 1** | **Cardinality Ratio** | **Entity 2** |
3094 | --- | :---: | --- |
3095 STUDENT | | MAJOR
3096 CAR | | TAG
3097 INSTRUCTOR | | LECTURE
3098 INSTRUCTOR | | OFFICE
3099 COMPUTER | | OPERATING\_SYSTEM
3100
3101 Exercise +.#
3102 ~ Give an example of a binary relationship type of cardinality $1 : N$.
3103
3104 Exercise +.#
3105 ~ Give an example of a binary relationship type of cardinality $N:1$, and draw the corresponding diagram (you don't have to include details on the participating entity types).
3106
3107 Exercise +.#
3108 ~ Draw an ER diagram with a single entity type, with two stored attributes and one derived attribute. In your answer, it should be clear that the value for the derived attribute will always be obtained from the value(s) for the other attribute(s).
3109
3110 Exercise +.#
3111 ~ Draw an ER diagram expressing the total participation of an entity type "BURGER" in a binary relation "CONTAINS" between "BURGER" and "INGREDIENT".
3112 What would be the ratio of such a relation?
3113
3114 Exercise +.#
3115 ~ Convert the following ER diagram into a relational model:
3116
3117 \begin{tikzpicture}[node distance=7em]
3118 \node[relationship] (contains){STAYS\_AT};
3119 \node[entity] (person) [above = 1cm of contains] {PERSON} edge node[right] {$N$} (contains);;
3120 \node[attribute] (ssn) [left of=person] {\key{SSN}} edge (person);
3121 \node[attribute] (dob) [above = .5cm of person] {Date\_Of\_Birth} edge (person);
3122 \node[entity] (burger) [below of= contains] {PLACE} edge node[right] {$1$} (contains);
3123 \node[attribute] (dob) [below = .5cm of burger] {\key{Address}} edge (burger);
3124 \node[attribute] (ssn) [left of=burger] {Rooms} edge (burger);
3125 \end{tikzpicture}
3126
3127 Exercise +.#
3128 ~ Why do weak entity type have a total participation constraint?
3129
3130 Exercise +.#
3131 ~ What is insertion anomaly? Give an example.
3132
3133 Exercise +.#
3134 ~ Why should we avoid attributes whose value will often be `NULL`? Can the usage of `NULL` be completely avoided?
3135
3136 Exercise +.#
3137 ~ Consider the following relation:
3138
3139 PROF(\underline{SSN}, Name, Department, Bike\_brand)
3140
3141 Why is it a poor design to have a "Bike\_brand" attribute in such a relation?
3142 How should we store this information?
3143
3144
3145 Exercise +.#
3146 ~ Consider the following relation:
3147
3148 STUDENT(\underline{SSN}, Name, \(…\), Sibling\_On\_Campus)
3149
3150 Why is it a poor design to have a "Sibling\_On\_Campus" attribute in such a relation?
3151 How should we store this information?
3152
3153 Exercise +.#
3154 ~ Consider the following relational database schema:
3155
3156 STUDENT(\underline{Login}, Name, \(…\), Major, Major\_Head)
3157 DEPARTMENT(\underline{Code}, Name, Major\_Head)
3158
3159 Assuming that "Major" is a foreign key referencing "DEPARTMENT.Code", what is the problem with that schema? How could you address it?
3160
3161
3162 Exercise +.#
3163 ~ Consider the relation \(R(A , B, C, D, E, F)\) and the following functional dependencies:
3164
3165 #. \(F \to \{D, C\}, D \to \{B, E\}, \{B, E\} \to A\)
3166 #. \(\{A, B\} \to \{C, D\}, \{B, E\} \to F\)
3167 #. \(A \to \{C, D\}, E \to F, D \to B\)
3168
3169 For each set of functional dependency, give a key for \(R\). We want a key, so it has to be minimal.
3170
3171 Exercise +.#
3172 ~ Consider the relation \(R(A, B, C, D, E, F)\) and the following functional dependencies:
3173 \[ A \to \{D, E\}, D \to \{B, F\}, \{B, E\} \to A, \{A,C\} \to \{B, D, F\}, A \to F\]
3174 Answer the following:
3175
3176 #. How many candidate keys is there? List them.
3177 #. How many transitive dependencies can you find? Give them and justify them.
3178
3179 Exercise +.#
3180 ~ Consider the relation \(R(A, B, C, D)\) and answer the following:
3181
3182 #. If \(\{A, B\}\) is the only key, is \(\{A, B\} \to \{C,D\}, \{B, C\} \to D\) a 2NF? List the nonprime attributes and justify.
3183 #. If \(\{A, B, C\}\) is the only key, is \(A \to \{B, D\}, \{A, B, C\} \to D\) a 2NF? List the nonprime attributes and justify.
3184
3185
3186 Exercise +.#
3187 ~ Consider the relation \(R(A, B, C, D, E, F)\) with candidate keys \(\{A, B\}\) and \(C\). Answer the following:
3188
3189 #. What are the prime attributes in \(R\)?
3190 #. Is \(\{C,D\} \to E\) a fully functional dependency?
3191 #. Write a set of functional dependencies containing at least one transitive depency, and justify your answer.
3192
3193
3194 Exercise +.#
3195 ~ Consider the relation \(R(A , B, C, D, E)\) and the following functional dependencies:
3196
3197 #. \(C \to D, \{C, B\} \to A, A \to \{B, C, D\}, B \to E\)
3198 #. \(\ A \to \{C, D\}, C \to B, D \to E, \{E, C\} \to A\)
3199 #. \(\{A, B\} \to D, D \to \{B, C\}, E \to C\)
3200
3201 For each one, give one candidate key for \(R\).
3202
3203 Exercise +.#
3204 ~ Consider the relation \(R(A, B, C, D, E)\) and answer the following:
3205
3206 #. If \(\{A, B\}\) is the primary key, is \(B \to E, C \to D\) a 2NF?% List the nonprime attributes and justify.
3207 #. If \(\{A\}\) is the primary key, is \(B \to C, B \to D\) a 2NF?% List the nonprime attributes and justify.
3208
3209
3210 Exercise +.#
3211 ~ Consider the relation \(R(A, B, C, D, E, F)\), and let \(\{B, D\}\) be the primary key, and have additionnaly the functional dependencies \(\{A, D\} \to E, C \to F\).
3212 This relation is not in 3NF, can you tell why?
3213
3214
3215 Exercise +.#
3216 ~ Consider the relation \(R(A, B, C, D)\) and answer the following:
3217
3218 #. If \(A\) is the only key, is \(A \to \{B,C,D\}, \{A, B\} \to C, \{B, C\} \to D\) a 3NF? List the nonprime attributes and justify.
3219 #. If \(B\) is the only key, is \(B \to \{A, C, D\}, A \to \{C, D\}, \{A, C\} \to D\) a 3NF? List the nonprime attributes and justify.
3220
3221
3222 ## Solution to Exercises
3223
3224 Solution +.#
3225 ~ Name / extension.
3226 To have statistics about the extensions, to sort the username by length, etc.
3227
3228 Solution +.#
3229 ~ \begin{tikzpicture}[node distance=7em]
3230 \node[entity] (computer) {COMPUTER};
3231 \node[attribute] (pid) [left of=computer] {\key{Id}} edge (computer);
3232 \node[multi attribute] (os) [above of=computer] {Operating\_System} edge (computer);
3233 \node[attribute] (devices) [right of=computer] {Devices} edge (computer);
3234 \node[attribute] (mouse) [above right of=devices] {Mouse} edge (devices);
3235 \node[attribute] (keyboard) [right of=devices] {Keyboard} edge (devices);
3236 \end{tikzpicture}
3237
3238 Solution +.#
3239 ~ \begin{tikzpicture}[node distance=7em]
3240 \node[entity] (cellphone) {CELLPHONE};
3241 \node[attribute] (mid) [left of=cellphone] {\key{MIN}} edge (cellphone);
3242 \node[multi attribute] (app) [above of=cellphone] {App\_Installed} edge (cellphone);
3243 \node[attribute] (plan) [right of=cellphone] {Plan} edge (cellphone);
3244 \node[attribute] (carrier) [above right of=plan] {Carrier} edge (plan);
3245 \node[attribute] (price) [right of=plan] {Price} edge (plan);
3246 \end{tikzpicture}
3247
3248 Solution +.#
3249 ~ There can be more than one key in the ER model.
3250
3251 Solution +.#
3252 ~ The weak entity type doesn't have a primary key.
3253
3254 Solution +.#
3255 ~ The number of participating entity types.
3256
3257 Solution +.#
3258 ~ A relationship type where the same entity type participates more than once.
3259 On rooms, "is to the left of", on persons, "is married to".
3260
3261 Solution +.#
3262 ~ That a person can own multiple computers, and that a computer can have multiple owners.
3263
3264 Solution +.#
3265 ~ Cardinality ration and participation constraints.
3266
3267 Solution +.#
3268 ~ When the cardinality is $1 : N$, $1 : 1$ or $N : 1$.
3269
3270 Solution +.#
3271 ~ For a weak entity attribute, it is the attribute that can uniquely identify weak entites that are related to the same owner entity.
3272
3273 Solution +.#
3274
3275 **Entity 1** | **Cardinality Ratio** | **Entity 2** | **Explanation** |
3276 | --- | :---: | --- | --------|
3277 STUDENT | N:1 | MAJOR | "A student has one major, but multiple students can have the same major"
3278 CAR | 1:1 | TAG | "A car has exactly one tag, a tag belongs to one particular car."
3279 INSTRUCTOR | 1:N | LECTURE | "An instructor can teach multiple lecture, but a lecture is taught by only one person."
3280 INSTRUCTOR | 1:N | OFFICE | "An instructor can have multiple office, but an office belongs to only one instructor"
3281 COMPUTER | M:N | OS| "A computer can have multiple operating system, the same operating system can be installed on more than one computer."
3282
3283 Some of those choices, of course, are is arguable (typically, almost any combination seems reasonnable for the INSTRUCTOR : OFFICE relation).
3284
3285 Solution +.#
3286 ~ SUPERVISION, a recursive relationship on EMPLOYEE.
3287
3288 Solution +.#
3289 ~ \begin{tikzpicture}[node distance=7em]
3290 \node[relationship] (contains){BELONGS};
3291 \node[entity] (burger) [left = 1cm of contains] {HAND} edge node[above] {$N$} (contains);
3292 \node[entity] (ingredient) [right = 1cm of contains] {PERSON} edge node[above]{$1$} (contains);
3293 \end{tikzpicture}
3294
3295 Solution +.#
3296 ~
3297 \begin{tikzpicture}[node distance=7em]
3298 \node[entity] (person) {PERSON};
3299 \node[attribute] (ssn) [left of=person] {\key{SSN}} edge (person);
3300 \node[attribute] (dob) [above of=person] {Date\_Of\_Birth} edge (person);
3301 \node[derived attribute] (age) [right of=person] {Age} edge (person);
3302 \end{tikzpicture}
3303
3304 Solution +.#
3305 ~ \begin{tikzpicture}[node distance=7em]
3306 \node[relationship] (contains){CONTAINS};
3307 \node[entity] (burger) [left = 1cm of contains] {BURGER} edge[total] node[above] {$N$} (contains);
3308 \node[entity] (ingredient) [right = 1cm of contains] {INGREDIENT} edge node[above]{$M$} (contains);
3309 \end{tikzpicture}
3310
3311 Solution +.#
3312 ~ \begin{tikzpicture}[node distance=7em]
3313 \node[relationship] (contains){CONTAINS};
3314 \node[entity] (burger) [left = 1cm of contains] {BURGER} edge[total] node[above] {$N$} (contains);
3315 \node[entity] (ingredient) [right = 1cm of contains] {INGREDIENT} edge node[above]{$M$} (contains);
3316 \end{tikzpicture}
3317
3318 Solution +.#
3319 ~ Otherwise, we couldn't identify entities in it without owner entity.
3320
3321 Solution +.#
3322 ~
3323 When you have to invent a primary key or add a lot of `NULL` value to be able to add a tuple.
3324 I want to add a room in my DB, but the only place where rooms are listed are as an attribute on a Instructor table, so I have to "fake" an instructor to add a room.
3325
3326 Solution +.#
3327 ~ Because they waste space, and because they are ambiguous (N/A, or unknown, or not communicated?).
3328 No, it is necessary sometimes.
3329
3330 Solution +.#
3331 ~ Because it will be `NULL` most of the time.
3332 In a separate table.
3333
3334 Solution +.#
3335 ~ Because it will be `NULL` most of the time, and because students could have more than one sibling on campus.
3336 In a separate table.
3337
3338 Solution +.#
3339 ~ Major\_Head will give update anomalies.
3340 By putting the Head of the department in the DEPARTMENT relation only, i.e., removing it from STUDENT.
3341
3342 Solution +.#
3343 ~ #. \(F\)
3344 #. \(\{A, B, E\}\)
3345 #. \(\{A, E\}\)
3346
3347 Solution +.#
3348 ~ #. \(\{A, C\}\),
3349 #. \(A \to F\) by \(A \to D, D\to F\).
3350
3351 Solution +.#
3352 ~ #. Yes. \(C\) and \(D\) are non prime, and they fully depend on \(\{A,B\}\).
3353
3354 #. No. \(D\) is the only non prime, and it depends only on \(A\).
3355
3356 Solution +.#
3357 ~ #. \(A,B,C\)
3358 #. No, because we can remove \(D\),
3359 #. \(A \to D\), \(D \to E\) and \(A \to E\)
3360
3361 Solution +.#
3362 ~ #. \(\{B, C\}\), \(A\)
3363 #. \(A\), \(\{C,E\}\),
3364 #. \(\{A, D, E\}\), \(\{A, B, E\}\)
3365
3366 Solution +.#
3367 ~ 1. No. \(C, D, E\), and \(E\) has a partial relation to \(B\)
3368
3369 2. Yes. Since the primary key is a singleton, it is obvious.
3370
3371 Solution +.#
3372 ~ \(\{B, D\} \to C \to F\) breaks the 3NF.
3373
3374 Solution +.#
3375 ~ 1. No. \(B\), \(C\) and \(D\) are non prime, \(A \to \{B,C\} \to D\) breaks the 3NF.
3376
3377 2. No. \(A\), \(B\) and \(D\) are non prime, \(B \to \{A,C\} \to D\) breaks the 3NF.
3378
3379
3380 ## Problems
3381
3382 Problem +.#Movie
3383
3384 Consider the ER schema for the MOVIES database:
3385
3386 \begin{tikzpicture}
3387 \node (a) at (0,0) {\includegraphics[page=1,width=1\textwidth]{img/te.pdf}};
3388 \fill[white] (-8.3, 6.5) rectangle (-3.5, 4);
3389 \end{tikzpicture}
3390
3391 Assume that MOVIES is a populated database.
3392 ACTOR is used as a gender-netral term.
3393 Given the constraints shown in the ER schema, respond to the following statements with \emph{True} or \emph{False}.
3394 Justify each answer.
3395
3396 #. There are no actors in this database that have been in no movies.
3397 #. There might be actors who have acted in more than ten movies.
3398 #. Some actors could have done a lead role in multiple movies.
3399 #. A movie can have only a maximum of two lead actors.
3400 #. Every director have to have been an actor in some movie.
3401 #. No producer has ever been an actor.
3402 #. A producer cannot be an actor in some other movie.
3403 #. There could be movies with more than a dozen actors.
3404 #. Producers can be directors as well.
3405 #. A movie can have one director and one producer.
3406 #. A movie can have one director and several producers.
3407 #. There could be some actors who have done a lead role, directed a movie, and produced some movie.
3408 #. It is impossible for a director to play in the movie (s)he directed.
3409
3410
3411 Problem +.#
3412
3413 Draw the ER diagram for the following situation:
3414 A car-insurance company wants to have a database of accidents.
3415 An accident involves cars, drivers, and it has several aspects: the moment and place where it took place, the amount of damages, and a (unique) report number.
3416 A car has a license, a model, a year, and an owner.
3417 A driver has an id, an age, a name, and an address.
3418
3419 One of the interesting choice is: should "accident" be an entity type or a relationship type?
3420
3421 Solution +.#
3422 ~ \includegraphics[page=1,width=1\textwidth]{img/p.pdf}
3423
3424 OR
3425
3426 \begin{tikzpicture}[node distance=7em]
3427 \node[entity] (person) {Person};
3428 \node[attribute] (pid) [left of=person] {\key{id}} edge (person);
3429 \node[attribute] (name) [above left of=person] {Name} edge (person);
3430 \node[attribute] (address) [below left of=person] {address} edge (person);
3431
3432 \node[relationship] (owns) [above right of=person] {Owns} edge node[above, sloped]{$M$} (person);
3433 \node[entity] (car) [above right of=owns] {Car} edge node[above, sloped]{$N$} (owns);
3434 \node[attribute] (licence) [above left of=car] {\key{licence}} edge (car);
3435 \node[attribute] (model) [above of =car] {model} edge (car);
3436 \node[attribute] (year) [above right of =car] {year} edge (car);
3437
3438 \node[relationship] (accident) [right = 5cm of person] {Accident} edge[total] node[above, sloped]{$M$} (person);
3439 \node[attribute] (report_number) [below of = accident] {\key{Report Number}} edge (accident);
3440 \node[attribute] (time) [right of = accident] {Time} edge (accident);
3441 \node[attribute] (place) [below right of = accident] {Place} edge (accident);
3442 \node[attribute] (damage_amount) [above right of = accident] {Damage\_Amount} edge (accident);
3443
3444 \draw (car) edge[total] node[above, sloped]{$N$} (accident);
3445 \end{tikzpicture}
3446
3447 Problem +.#
3448
3449 Apply the ER-to-Relation mapping to your ER diagram from the previous problem.
3450
3451 Problem +.#CarSale
3452
3453 Consider the following relation, and its functional dependencies:
3454
3455 CAR\_SALE(\underline{Car\_no}, Date\_sold, \underline{Salesman\_no}, Commission, Discount\_amt)
3456
3457 | | |
3458 ---: | :---: | ---
3459 \{Car\_no, Salesman\_no\} | →| \{Date\_sold, Commission, Discount\_amt\}
3460 Date\_sold | →| Discount\_amt
3461 Salesman\_no | →| Commission
3462
3463 Based on the given primary key, is this relation in 1NF, 2NF, or 3NF? Why or why not? Normalize it completely. Then draw an ER diagram for the resulting schema.
3464
3465
3466
3467 Problem +.#Bike
3468
3469 This problem asks you to convert business statements into dependencies.
3470 Consider the following relation:
3471
3472 BIKE(Serial\_no, Manufacturer, Model, Batch, Wheel\_size, Retailer)
3473
3474 Each tuple in the relation BIKE contains information about a bike with a serial number, made by a manufacturer, with a particular model number, released in a certain batch, which has a certain wheel size, and is sold by a certain retailer.
3475
3476 - Write each of the following dependencies as a functional dependency (I give you the first one as an example):
3477
3478 #. A retailer can't have two bikes of the same model from different batches.
3479
3480 \emph{solution:} \{Retailer, Model\} → Batch
3481
3482 #. The manufacturer and serial number uniquely identifies the bike and where it is sold.
3483 #. A model number is registered by a manufacturer and therefore can't be used by another manufacturer.
3484 #. All bikes in a particular batch are of the same model.
3485 #. All bikes of a certain model have the same wheel size.
3486
3487 - Based on those statements, what could be a key for this relation?
3488 - Assuming all those functional dependencies hold, and taking the primary key you identified at the previous step, what is the degree of normality of this relation? Justify your answer.
3489
3490 Problem +.#
3491
3492 Consider the relations \(R\) and \(T\) below, and their functional dependencies (on top of the one induced by the primary keys):
3493
3494 \begin{tabular}{l}
3495 R(\underline{EventId}, \underline{Email}, Time, Date, Location, Status)\\
3496 T(\underline{Invno}, Subtotal, Tax, Total, Email, Lname, Fname, Phone)
3497 \end{tabular}
3498
3499
3500 | | |
3501 ---: | :---: | --- |
3502 \{EventId, Email\} | → | Status
3503 EventId | → | \{Time, Date, Location\}
3504 Invno | → | \{Subtotal, Tax, Total, Email\}
3505 Email | → | \{Fname, Lname, Phone\}
3506
3507 Normalize the relations to 2NF and 3NF. Show all relations at each stage (2NF and 3NF) of the normalization process.
3508
3509
3510 Problem +.#Book
3511
3512 Consider the following relation for published books:
3513
3514 BOOK (Book\_title, Book\_type, Author\_name, List\_price, Author\_affil, Publisher)
3515
3516 Suppose we have the following dependencies:
3517
3518 | | |
3519 ---: | :---: | --- |
3520 Book\_title | → | \{ Publisher, Book\_type \}
3521 Book\_type | → | List\_price
3522 Author\_name | → | Author\_affil
3523
3524 - What would be a suitable key for this relation?
3525 - How could this relation not be in first normal form? Explain your answer.
3526 - This relation is not in second normal form: explain why and normalize it.
3527 - Is the relations you obtained at the previous step in third normal form? Explain why, and normalize them if needed.
3528
3529 ## Solution to Selected Problems
3530
3531 ### Solution to the @Movie
3532
3533 #. true
3534 #. true
3535 #. true
3536 #. true
3537 #. false
3538 #. false
3539 #. false
3540 #. true
3541 #. true
3542 #. true
3543 #. true
3544 #. true
3545 #. false
3546
3547 ### Solution to @CarSale
3548
3549 This relation satisfies 1NF but not 2NF (Car\_no → Date\_sold and Salesman\_no → Commission so these two attributes are not fully functional dependent on the primary key) and not 3NF.
3550
3551 To normalize,
3552
3553 2NF:
3554 \begin{tabular}{l}
3555 Car\_Sale1(Car\_no, Date\_sold, Discount\_amt)\\
3556 Car\_Sale2(Car\_no, Salesman\_no)\\
3557 Car\_Sale3(Salesman\_no,Commission)
3558 \end{tabular}
3559 3NF:
3560 \begin{tabular}{c}
3561 Car\_Sale1-1(Car\_no, Date\_sold)\\
3562 Car\_Sale1-2(Date\_sold, Discount\_amt)\\
3563 Car\_Sale2(Car\_no, Salesman\_no)\\
3564 Car\_Sale3(Salesman\_no,Commission)
3565 \end{tabular}
3566
3567 ### Solution to @Bike
3568
3569 -
3570 #. \{ Manufacturer, Serial\_no \} → \{ Model, Batch, Wheel\_size, Retailer\}
3571 #. Model → Manufacturer
3572 #. Batch → Model
3573 #. \{Model, Manufacturer\} → Wheel\_size
3574
3575 - \{Manufacturer, Serial\_no \}
3576 - If every attribute is atomic, it is in second nf. \{ Manufacturer, Serial\_no \} → Batch →Model breaks the 3NF.
3577
3578 ### Solution to @Book
3579
3580 - \{Book Title, Author Name\}
3581 - If an attribute is composite or multi-valued.
3582 - Because of \{ Book\_title \} → \{ Publisher, Book\_type \}.
3583 We can normalize it as
3584 (Book Title, Publisher, Book Type, List Price), (Author Name, Author Affiliation), (Author Name, Book Title).
3585 - Because of \{Book title\} → \{ Book\_type\} → \{ List\_price\}\\
3586 (Book Title, Publisher, Book Type) and (Book Type, List Price), (Author Name, Author Affiliation), (Author Name, Book Title).
2216 3587
2217 3588 # Databases Applications # Databases Applications
2218 3589
 
... ... For a quick introduction to Java, cf. <http://spots.augusta.edu/caubert/teaching
2275 3646
2276 3647 ### The Java Code ### The Java Code
2277 3648
2278 ```{.java .numberLines}
3649 ~~~{.java .numberLines}
2279 3650 import java.sql.*; import java.sql.*;
2280 3651
2281 3652 public class FirstProg { public class FirstProg {
 
... ... public class FirstProg {
2310 3681 } }
2311 3682 } }
2312 3683 } }
2313 ```
3684 ~~~
2314 3685
2315 3686 A couple of comments: A couple of comments:
2316 3687
 
... ... A couple of comments:
2323 3694
2324 3695 ### The Database ### The Database
2325 3696
2326 ```{.plain}
3697 ~~~{.plain}
2327 3698 MariaDB [HW_ebookshop]> SELECT * FROM books; MariaDB [HW_ebookshop]> SELECT * FROM books;
2328 3699 +------+----------------------------+--------------+-------+------+ +------+----------------------------+--------------+-------+------+
2329 3700 | id | title | author | price | qty | | id | title | author | price | qty |
 
... ... MariaDB [HW_ebookshop]> SELECT * FROM books;
2335 3706 | 1005 | A Teaspoon of Java | Kevin Jones | 55.55 | 55 | | 1005 | A Teaspoon of Java | Kevin Jones | 55.55 | 55 |
2336 3707 +------+----------------------------+--------------+-------+------+ +------+----------------------------+--------------+-------+------+
2337 3708 5 rows in set (0.00 sec) 5 rows in set (0.00 sec)
2338 ```
3709 ~~~
2339 3710
2340 3711 ### The Result ### The Result
2341 3712
2342 3713 If you store the program in `FirstProg.java`, compile it, with If you store the program in `FirstProg.java`, compile it, with
2343 3714
2344 ```{.bash}
3715 ~~~{.bash}
2345 3716 javac FirstProg.java javac FirstProg.java
2346 ```
3717 ~~~
2347 3718
2348 3719 and then execute it, with and then execute it, with
2349 3720
2350 ```{.bash}
3721 ~~~{.bash}
2351 3722 java -cp .:mysql-connector-java-5.1.44/mysql-connector-java-5.1.44-bin.jar FirstProg java -cp .:mysql-connector-java-5.1.44/mysql-connector-java-5.1.44-bin.jar FirstProg
2352 ```
3723 ~~~
2353 3724
2354 3725 then you would obtain: then you would obtain:
2355 3726
2356 ```{.plain .numberLines}
3727 ~~~{.plain .numberLines}
2357 3728 The SQL query is: select title, price, qty from books where qty > 40 The SQL query is: select title, price, qty from books where qty > 40
2358 3729 The records selected are: The records selected are:
2359 3730 A Cup of Java, 44.44, 44 A Cup of Java, 44.44, 44
2360 3731 A Teaspoon of Java, 55.55, 55 A Teaspoon of Java, 55.55, 55
2361 3732 Total number of records = 2 Total number of records = 2
2362 ```
3733 ~~~
2363 3734
2364 3735 ### A Variation ### A Variation
2365 3736
2366 3737 If you were to replace the body of `try` in the previous program with If you were to replace the body of `try` in the previous program with
2367 3738
2368 ```{.java .numberLines}
3739 ~~~{.java .numberLines}
2369 3740 String strSelect = "SELECT * FROM books"; String strSelect = "SELECT * FROM books";
2370 3741 ResultSet rset = stmt.executeQuery(strSelect); ResultSet rset = stmt.executeQuery(strSelect);
2371 3742
 
... ... while (rset.next()) {
2383 3754 System.out.println(); System.out.println();
2384 3755 } }
2385 3756 conn.close(); conn.close();
2386 ```
3757 ~~~
2387 3758
2388 3759 You would obtain: You would obtain:
2389 3760
2390 ```{.plain}
3761 ~~~{.plain}
2391 3762 The records selected are: The records selected are:
2392 3763 1001 id, Java for dummies title, Tan Ah Teck author, 11.11 price, 11 qty 1001 id, Java for dummies title, Tan Ah Teck author, 11.11 price, 11 qty
2393 3764 1002 id, More Java for dummies title, Tan Ah Teck author, 22.22 price, 22 qty 1002 id, More Java for dummies title, Tan Ah Teck author, 22.22 price, 22 qty
2394 3765 1003 id, More Java for more dummies title, Mohammad Ali author, 33.33 price, 33 qty 1003 id, More Java for more dummies title, Mohammad Ali author, 33.33 price, 33 qty
2395 3766 1004 id, A Cup of Java title, Kumar author, 44.44 price, 44 qty 1004 id, A Cup of Java title, Kumar author, 44.44 price, 44 qty
2396 3767 1005 id, A Teaspoon of Java title, Kevin Jones author, 55.55 price, 55 qty 1005 id, A Teaspoon of Java title, Kevin Jones author, 55.55 price, 55 qty
2397 ```
3768 ~~~
2398 3769
2399 3770 ## Mapping Datatypes ## Mapping Datatypes
2400 3771
 
... ... For more details, consult <https://docs.oracle.com/javase/7/docs/api/java/sql/St
2433 3804
2434 3805 We can pass options when connecting to the database: We can pass options when connecting to the database:
2435 3806
2436 ```{.java}
3807 ~~~{.java}
2437 3808 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/HW_DBPROG" Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/HW_DBPROG"
2438 3809 + "?user=testuser" + "?user=testuser"
2439 3810 + "&password=password" + "&password=password"
2440 3811 + "&allowMultiQueries=true" + "&allowMultiQueries=true"
2441 3812 + "&createDatabaseIfNotExist=true" + "&createDatabaseIfNotExist=true"
2442 3813 + "&useSSL=true"); + "&useSSL=true");
2443 ```
3814 ~~~
2444 3815
2445 3816 `createDatabaseIfNotExist` is about schema, actually. `createDatabaseIfNotExist` is about schema, actually.
2446 3817
 
... ... You can use the `getMetaData()` of the `DatabaseMetaData` to obtain information
2454 3825 Use `stmt.executeUpdate` (multiple insertion possible if `allowMultiQueries` was set to true). Use `stmt.executeUpdate` (multiple insertion possible if `allowMultiQueries` was set to true).
2455 3826 Another way of batch processing statements: Another way of batch processing statements:
2456 3827
2457 ```{.java}
3828 ~~~{.java}
2458 3829 stmt.addBatch(insert3); stmt.addBatch(insert3);
2459 3830 stmt.addBatch(insert4); stmt.addBatch(insert4);
2460 3831 stmt.executeBatch(); stmt.executeBatch();
2461 ```
3832 ~~~
2462 3833
2463 3834 ### Prepared Statements ### Prepared Statements
2464 3835
 
... ... Attacks: buffer overflow, denial of service, weak authentication, privilege esca
2514 3885
2515 3886 Example with `ASP`, Active Server Pages, a server-side scripting language: Example with `ASP`, Active Server Pages, a server-side scripting language:
2516 3887
2517 ```{.asp}
3888 ~~~{.asp}
2518 3889 txtUserId = getRequestString("UserId"); txtUserId = getRequestString("UserId");
2519 3890 txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId; txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
2520 ```
3891 ~~~
2521 3892
2522 3893 a. `105; DROP TABLE Suppliers;` Execute remote command a. `105; DROP TABLE Suppliers;` Execute remote command
2523 3894 b. `105 or 1 = 1` Exploit, bypass login screen b. `105 or 1 = 1` Exploit, bypass login screen
 
... ... A lot of enthusiasm, also because it "frees the data" (and, actually, the metada
2614 3985 Some of it will last for sure: polyglot persistency, the possibility of being schema-less, being "distributed first", the possibility of sacrifying consistency for greater good, etc. Some of it will last for sure: polyglot persistency, the possibility of being schema-less, being "distributed first", the possibility of sacrifying consistency for greater good, etc.
2615 3986 Doesn't mean SQL ("OldSQL") and relational database are over: still useful in many scenario, and the powerfull query language is great (writing your own every time is a nightmare…). Doesn't mean SQL ("OldSQL") and relational database are over: still useful in many scenario, and the powerfull query language is great (writing your own every time is a nightmare…).
2616 3987
2617 Starting ~2010, one reaction was to develop "NewSQL", which would combine aspects of both approaches.
3988 Starting ~ 2010, one reaction was to develop "NewSQL", which would combine aspects of both approaches.
2618 3989 MongoDB announced that it would have more and more of the ACID properties! <https://www.mongodb.com/blog/post/multi-document-transactions-in-mongodb> MongoDB announced that it would have more and more of the ACID properties! <https://www.mongodb.com/blog/post/multi-document-transactions-in-mongodb>
2619 3990
2620 3991 Also, a really great use of NoSQL is to adopt it at an early stage of the development, when it isn't clear what the schemas should be. Also, a really great use of NoSQL is to adopt it at an early stage of the development, when it isn't clear what the schemas should be.
 
... ... Pro:
2727 4098
2728 4099 Document: Document:
2729 4100
2730 - Implementations differs on the details of the definition, but always the central notion. MongoDB has its own implementation, but there are ~45 others. MongoDB is the most popular one (next: Amazon DynamoDB, Couchbase, CouchDB)
4101 - Implementations differs on the details of the definition, but always the central notion. MongoDB has its own implementation, but there are ~ 45 others. MongoDB is the most popular one (next: Amazon DynamoDB, Couchbase, CouchDB)
2731 4102 - Documents encapsulate and encode data (Self-Describing Data) - Documents encapsulate and encode data (Self-Describing Data)
2732 4103 - Do not need to adhere a standard schema. - Do not need to adhere a standard schema.
2733 4104 - One program can have many different types of objects, and those objects often have many optional fields - One program can have many different types of objects, and those objects often have many optional fields
 
... ... Think of BSON as a binary representation of JSON (JavaScript Object Notation) do
2738 4109
2739 4110 An example of XML (Extensible Markup Languag) document (you can actually convert from XML to JSON): An example of XML (Extensible Markup Languag) document (you can actually convert from XML to JSON):
2740 4111
2741 ```{.xml}
4112 ~~~{.xml}
2742 4113 <shiporder orderid="889923"> <shiporder orderid="889923">
2743 4114 <orderperson>John Smith</orderperson> <orderperson>John Smith</orderperson>
2744 4115 <shipto> <shipto>
 
... ... An example of XML (Extensible Markup Languag) document (you can actually convert
2759 4130 <price>9.90</price> <price>9.90</price>
2760 4131 </item> </item>
2761 4132 </shiporder> </shiporder>
2762 ```
4133 ~~~
2763 4134
2764 4135 - Invalid document exists! - Invalid document exists!
2765 4136 - Human and computer-readable - Human and computer-readable
 
... ... Each MongoDB instance has multiple databases, each database can have multiple co
2779 4150
2780 4151 Two documents (delimited by `[`…`]`, used to delimit an arry of document). Two documents (delimited by `[`…`]`, used to delimit an arry of document).
2781 4152
2782 ```{.json}
4153 ~~~{.json}
2783 4154 [ [
2784 4155 { {
2785 4156 "firstname": "Martin", "firstname": "Martin",
 
... ... Two documents (delimited by `[`…`]`, used to delimit an arry of document).
2802 4173 "lastcity": "Chicago" "lastcity": "Chicago"
2803 4174 } }
2804 4175 ] ]
2805 ```
4176 ~~~
2806 4177
2807 4178 **Use the same example all along!** **Use the same example all along!**
2808 4179
 
... ... Cf. "MongoDB Driver Quick Start" <https://mongodb.github.io/mongo-java-driver/3.
2863 4234
2864 4235 Compile and execute with Compile and execute with
2865 4236
2866 ```{.bash}
4237 ~~~{.bash}
2867 4238 javac -cp .:mongo-java-driver-3.7.0-rc0.jar MongoTest2.java javac -cp .:mongo-java-driver-3.7.0-rc0.jar MongoTest2.java
2868 4239 java -cp .:mongo-java-driver-3.7.0-rc0.jar MongoTest2 java -cp .:mongo-java-driver-3.7.0-rc0.jar MongoTest2
2869 ```
4240 ~~~
2870 4241
2871 4242 After various import statement, and the usual header: After various import statement, and the usual header:
2872 4243
2873 ```{.java}
4244 ~~~{.java}
2874 4245 MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017"); MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
2875 4246 MongoClient mongoClient = new MongoClient(connectionString); MongoClient mongoClient = new MongoClient(connectionString);
2876 ```
4247 ~~~
2877 4248
2878 4249 Or, more compact: Or, more compact:
2879 4250
2880 ```{.java}
4251 ~~~{.java}
2881 4252 MongoClient mongoClient = new MongoClient(); MongoClient mongoClient = new MongoClient();
2882 ```
4253 ~~~
2883 4254
2884 4255 Get a collection: Get a collection:
2885 4256
2886 ```{.java}
4257 ~~~{.java}
2887 4258 MongoDatabase database = mongoClient.getDatabase("mydb"); MongoDatabase database = mongoClient.getDatabase("mydb");
2888 4259 MongoCollection<Document> collection = database.getCollection("test"); MongoCollection<Document> collection = database.getCollection("test");
2889 ```
4260 ~~~
2890 4261
2891 4262 Assume we want to create the following document: Assume we want to create the following document:
2892 4263
2893 ```{.json}
4264 ~~~{.json}
2894 4265 { {
2895 4266 "name" : "MongoDB", "name" : "MongoDB",
2896 4267 "type" : "database", "type" : "database",
 
... ... Assume we want to create the following document:
2898 4269 "versions": [ "v3.2", "v3.0", "v2.6" ], "versions": [ "v3.2", "v3.0", "v2.6" ],
2899 4270 "info" : { "level" : "easy", "used" : "yes" } "info" : { "level" : "easy", "used" : "yes" }
2900 4271 } }
2901 ```
4272 ~~~
2902 4273
2903 4274 (Remember: order does not matter!) (Remember: order does not matter!)
2904 4275
2905 4276 Then we can use the `Document` class, and then insert it: Then we can use the `Document` class, and then insert it:
2906 4277
2907 ```{.java}
4278 ~~~{.java}
2908 4279 Document doc = new Document("name", "MongoDB"); Document doc = new Document("name", "MongoDB");
2909 4280 doc.append("type", "database"); doc.append("type", "database");
2910 4281 doc.append("count", 1); doc.append("count", 1);
2911 4282 doc.append("versions", Arrays.asList("v3.2", "v3.0", "v2.6")); doc.append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"));
2912 4283 doc.append("info", new Document("level", "easy").append("used", "yes")); doc.append("info", new Document("level", "easy").append("used", "yes"));
2913 ```
4284 ~~~
2914 4285
2915 4286 We can "chain" the `append`: `doc.append("type", "database").append("count", 1);` We can "chain" the `append`: `doc.append("type", "database").append("count", 1);`
2916 4287
2917 4288 And then insert: And then insert:
2918 4289
2919 ```{.java}
4290 ~~~{.java}
2920 4291 collection.insertOne(doc); collection.insertOne(doc);
2921 ```
4292 ~~~
2922 4293
2923 4294 Only at this point would the database and collection being created. Only at this point would the database and collection being created.
2924 4295 To make sure everything went right: To make sure everything went right:
2925 4296
2926 ```{.bash}
4297 ~~~{.bash}
2927 4298 mongo mongo
2928 4299 show dbs show dbs
2929 4300 use mydb use mydb
2930 4301 show collections show collections
2931 4302 db.collection.find() db.collection.find()
2932 4303 { "_id" : ObjectId("5ae08a7252cbeb2717712b9f"), "name" : "MongoDB" … } { "_id" : ObjectId("5ae08a7252cbeb2717712b9f"), "name" : "MongoDB" … }
2933 ```
4304 ~~~
2934 4305
2935 4306 We can construct lists of documents and insert them: We can construct lists of documents and insert them:
2936 4307
2937 ```{.java}
4308 ~~~{.java}
2938 4309 List<Document> documents = new ArrayList<Document>(); List<Document> documents = new ArrayList<Document>();
2939 4310 for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
2940 4311 documents.add(new Document("i", i)); documents.add(new Document("i", i));
2941 4312 } }
2942 4313
2943 4314 collection.insertMany(documents); collection.insertMany(documents);
2944 ```
4315 ~~~
2945 4316
2946 4317 ## Principles ## Principles
2947 4318
File notes/Makefile changed (mode: 100644) (index cd3b56c..5a09ed4)
1 1 all: all:
2 pandoc 00_sum.md --pdf-engine=xelatex --toc --filter pandoc-citeproc --filter pandoc-numbering --top-level-division=chapter -M date="`date "+%B %e, %Y"`" -o 00_sum.pdf
2 pandoc 00_sum.md --pdf-engine=xelatex --toc --filter pandoc-numbering --filter pandoc-citeproc --top-level-division=chapter -M date="`date "+%B %e, %Y"`" -o 00_sum.pdf
3 3 # pandoc \ # pandoc \
4 4 # --standalone \ # --standalone \
5 5 # --email-obfuscation=references \ # --email-obfuscation=references \
Hints:
Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://rocketgit.com/user/caubert/CSCI_3410

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@ssh.rocketgit.com/user/caubert/CSCI_3410

Clone this repository using git:
git clone git://git.rocketgit.com/user/caubert/CSCI_3410

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a merge request:
... clone the repository ...
... make some changes and some commits ...
git push origin main