Revision Exercises
Revision Exercises
Exercise: SQL
Given the following schema:
Students(sid, name, degree, ...)
// e.g. Students(3322111, 'John Smith', 'MEngSc', ...)
Courses(cid, code, term, title, ...)
// e.g. Courses(1732, 'COMP9311', '12s1', 'Databases', ...)
Enrolments(sid, cid, mark, grade)
// e.g. Enrolments(3322111, 1732, 50, 'PS')
Write an SQL query to solve the problem
- find all students who enrolled COMP9315 in 18s2
- for each student, give (student ID, name, mark)
Solution:
select s.sid, s.name, e.mark
from Students s join Enrolments e on s.sid = e.sid
join Courses c on e.cid = c.cid
where c.code = "COMP9315" and c.term = '18s2'
Exercise: Unix File I/O
Write a C program that reads a file, block-by-block.
Command-line parameters:
- block size in bytes
- name of input file Use low-level C operations: open, read. Count and display how many blocks/bytes read.
Solution:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void giveUp(char *);
int main(int argc, char **argv) {
char *buf;
int inf;
int bufsize;
ssize_t nread;
int nblocks = 0, nbytes = 0;
// process command line args
if (argc < 3) giveUp("Insufficient args");
bufsize = atoi(argv[1]);
if (bufsize < 100) giveUp("Invalid buffer size");
buf = malloc(bufsize * sizeof(char));
if (buf == NULL) giveUp("Can't create buffer");
// open file
if ((inf = open(argv[2], O_RDONLY)) < 0) {
giveUp("Can't read file");
}
// read file and count blocks/bytes
while ((nread = read(inf, buf, bufsize)) != 0) {
nblocks ++;
nbytes += nread;
printf("%ld bytes read in current block\n", nread);
}
// display results
printf("Read %d blocks and %ld bytes\n", nblocks, nbytes);
exit(EXIT_SUCCESS);
}
void giveUp(char *msg) {
fprinf(stderr, "Error: %s\n", msg);
fprinf(stderr, "Usage: ./blocks Blocksize InputFile\n");
exit(EXIT_FAILURE);
}
Exercise: Relational Algebra
Assume a schema: R(a,b,c), S(x,y) Translate each of the following SQL statements to RA
- select * from R
- select a,b from R
- select * from R where a > 5
- select * from R join S on R.a = S.y
Indicate: the fields $and #tuples in result
Solution:
- R
- fields: a, b, c
#tuples = R
- $\pi_{a,b}(R)$ or Proj[a,b]R
- fields: a, b
#tuples = R
- $\sigma_{a>5}(R)$ or Sel[a>5]R
- fields: a,b,c
#tuples $\leq R $
- $R \bowtie_{R.a = S.y} S$ or R Join[a=y] S
- fields: a,b,c,x,y
#tuples $\leq R \times S $
