Querying Relational Databases with SQL Flashcards
Add a tuple in the Student table/ insert rows
INSERT
INTO Student (mn, name, email, age)
VALUES (‘s1253477’, ‘Jenny’, ‘jenny@sms.ed.ac.uk’, 23)
• The above statement adds a tuple in the Student table.
• We could omit the list of column names and simply list
the values in the appropriate order, but it is good
practice to include column names.
Deleting rows
DELETE
FROM Student
WHERE name = ‘Alan’
Updating rows
We can update the column values in an existing row using the UPDATE command UPDATE Student SET name = ‘Alan’ WHERE mn = ‘s1428571’
What questions can we ask to the database?
Which students are older than 19?
What are the names of all students taking the
Medical Informatics course?
What is the average age of all students born in
Europe who are taking the Medical Informatics
course but not the Advanced Databases course?
How to query returns all students older than
19.
• The following query returns all students older than
19.
SELECT *
FROM Student
WHERE age > 19
• The * means that the table returned has the same
schema as Students.
What is SQL query syntax?
SELECT [DISTINCT] field-list
FROM table-list
[ WHERE qualification ]
• Anything in [square brackets] is optional.
• SELECT: the columns to be retained in the result
• FROM: the tables from which to take the data
• WHERE: conditions that should hold for the records
to be picked out
What can we use instead of *
Instead of using *, we can explicitly specify the
list of fields to be returned. These could be in
a different order than in the original table
SELECT mn, name, email, age
FROM Student
WHERE age > 19
How can we specify which tables the fields are from
We can specify which tables the fields are from. • This is particularly useful when the FROM clause includes several tables. SELECT Student.mn, Student.name, Student.email, Student.age FROM Student WHERE Student.age > 19 Locally abbreviating names= Student S
How to select only a subset of the
fields of each selected tuple
SELECT S.name FROM Student S WHERE S.age > 19 • In this case, the table returned has a different schema to that in Student
How not to specify a condition through
the WHERE-part of the query
SELECT age
FROM Student
How to remove any duplicates from
the returned records
By using DISTINCT, we remove any duplicates from
the returned records.
SELECT DISTINCT age
FROM Student
How to query returns the email
addresses of all students taking Medical
Informatics
SELECT S.email FROM Student S, Takes T, Course C WHERE S.mn = T.mn AND T.cid = C.cid AND C.title = ‘Medical Informatics’
How to query evaluation
- Take all rows from the tables.
- Keep only the row combinations that satisfy the
qualification conditions. - Return the specified columns.
The three set-operation constructs
that extend the basic form of a query:
UNION: A or B
INTERSECT: A and B
EXCEPT: A but not B
Example of union
Find the email addresses of all students taking
Medical Informatics or Advanced Databases