10 - SQL
10 - SQL
Relational Data
SQL
Tom Blount
[email protected]
Today
• SQL
• For data definition
• For data manipulation
• SQLite
• Useful SQL tools
Prerequisites
• To take part in today’s session you must have made
a planet
• https://ofb-interactive.soton.ac.uk/space/planet
• Note: Different DB systems use different types, so make sure you are
familiar with the system you are using
• No BOOLEAN!
• No DATE!
Adding Types
CREATE TABLE planets (
name TEXT,
description TEXT,
ruler_id INTEGER,
race_id INTEGER,
quadrant TEXT,
sector_x INTEGER,
sector_y INTEGER
);
Adding Keys
CREATE TABLE planets (
name TEXT,
Here we have specified the
description TEXT, primary key of the table
ruler_id INTEGER,
race_id INTEGER, If an operation is attempted
later that will invalidate this, the
quadrant TEXT, key will be enforced and the
sector_x INTEGER, insertion/edit will be rejected
sector_y INTEGER,
PRIMARY KEY
(quadrant,sector_x,sector_y)
)
Adding Properties
We can specify whether
columns can take null
CREATE TABLE planets ( values or not
name TEXT NOT NULL,
description TEXT NULL,
ruler_id INTEGER NOT NULL,
race_id INTEGER NOT NULL,
quadrant TEXT NOT NULL,
sector_x INTEGER NOT NULL,
sector_y INTEGER NOT NULL,
PRIMARY KEY
(quadrant,sector_x,sector_y)
)
Rename a Table
ALTER TABLE OldName
RENAME TO NewName
Remove a Table
• If you want to make changes to a table, there are
some limited operations you can do with ALTER
TABLE
• However, it is usually easiest to remove the table
and recreate it as you want it
• To do this, use
• DROP TABLE <Table Name>
• Getting started:
https://www.jetbrains.com/help/datagrip/sqlite.html
Datagrip
You will need to set up and install the driver and then open your SQLite File
Datagrip
But for these exercises…
• We’ve set up an SQL environment you can use from
the comfort of your web browser ☺
Manipulation
SELECT
• The SELECT statement allows us to retrieve information the
database
• We specify what data we want and where we want it from
• We can place further constraints on the conditions, grouping,
ordering and amount of data that is returned
SELECT expression
FROM tables
WHERE conditions
All of these parts are optional!
GROUP BY expression
ORDER BY expression
LIMIT expression
SELECT Examples
• SELECT * FROM Table
• * Means all columns
• SELECT Column,Column2… FROM Table
• Specify specific columns
• SELECT Columns FROM Table WHERE Conditions
• Specify conditions on results returned
• SELECT Columns FROM Table LIMIT Number
• Limit the number of results
• SELECT * FROM Table ORDER BY Column ASC/DESC
• Specify an ordering
• You can combine them but they must be in the right
order
Using WHERE
• WHERE column=number
• If the column is a number
• Example: WHERE id=3
• WHERE column=‘string’
• If the column contains text
• Example: WHERE name=‘Oli'
• WHERE column=anotherColumn
• If you want to compare values between two columns
• Example: WHERE sector_x=sector_y
A simple example
Activity 2: Our First Query Together
• Go to https://ofb-interactive.soton.ac.uk/game/
• If this doesn’t work for you, create a planet and let me know to spawn your ship!
• Your ship awaits, but hasn’t been fully programmed yet. It is currently docked at
Earth in the Ship Yard and linked to GalNet which provides data about the
quadrant
• We are going to be using the Ship Computer to query the GalNet database
• Click the GREEN computer screen to access the Ship Computer
• First, type ‘DOWNLOAD’ to update the Ship Computer with the GALNET
database
• Next, get the list of all the planets in the quadrant
• You will want to use the SELECT command
• The table is called planets
• Can you get them in alphabetical order?
• Can you get just the name, quadrant and sectors?
• How many planets are there in the alpha quadrant?
Activity 2: Example
We restricted to just the name, quadrant, sector_x and sector_y columns here
More Complex Querying
• We can join conditions
together with AND, OR and
NOT
• SELECT * FROM table WHERE
id=1 OR id=2
Reference table
• IN or NOT IN
• SELECT * FROM table WHERE id
NOT IN (1,3,5)
Activity 3: More Complex Queries
• Go to https://ofb-interactive.soton.ac.uk/game/
Joins JOIN
Non-sweetcorn pizza
45
Joining in SQL
SELECT Table1.*, Table2.*
FROM Table1
LEFT JOIN Table2
ON Table1.Column=Table2.Column
• Go to https://ofb-interactive.soton.ac.uk/game/
• Go to https://ofb-interactive.soton.ac.uk/game/
• Go to https://ofb-interactive.soton.ac.uk/game/
We are going to make a quick lookup table that has the resource name and planet details
We bring in the results from our select query, matching the number of columns to our table
UPDATE Table
SET column=value,column=value…
WHERE column=value AND column=value…
Update
Update all with
conditions
Deleting
Deleting works in the same way!
National Space Centre,
Leicester
We now can’t have a note on a planet that doesn’t exist (once foreign_keys is on)
This ensures that regardless of what our application does, the database cannot end up inconsistent
Maintaining Referential Integrity
• We can tailor this behaviour using ON DELETE and FOREIGN KEY (planet_id)
ON UPDATE REFERENCES planets
• ON DELETE ON DELETE <Action>
• When the parent record is deleted ON UPDATE <Action>
• ON UPDATE
• When the parent key is updated
• Not overly useful when it’s an automatically generated
key
• Potential actions:
• CASCADE the deletion/updates to the referring
tables
• May not be appropriate
• Delete a booking, you don’t want to delete the member!
• Delete a member when they’ve left, you don’t want to
delete they had a booking
• RESTRICT: Prevent the parent being updated/deleted
• SET DEFAULT: Set the key value to the default
• SET NULL: Set the key value to NULL
Back to the Example
We will set our table to cascade updates and deletes
When planet 1 was deleted, the note corresponding to planet 1 was deleted (rather than
prevented, as it was before)
When planet 2 had it’s key changed, the key was also updated in planet_notes
Indexes
• Data structures associated with a table to support
queries
• Logically ordered by the values of a key
• Usually created for columns you’ll be accessing regularly
• Greatly improves database performance
• Instead of having to load all records (O(n) linear complexity)
where you have to examine each and check if a clause holds
• Can quickly lookup and access associated rows based on the
value of the index
• For example, ID columns, boolean properties etc.
• But adds cost to INSERT/UPDATE/DELETE
• Also have to update the indexes
• Efficiently querying large relations would be impossible
without them!
Index Mechanics
• Chosen attribute becomes an index key
• Sorted, searchable - Logarithmic time, rather than linear time
• Don’t have to scan the whole table
• Typically implemented as balanced binary trees
• Before, Between and After values to follow (can be used for
comparisons and quality)
• Can also be implemented as hash indexes
• Only for equality (= or != operations)
• The database system will use the indexes to plan the best
possible way to execute your query
Creating Indexes
• CREATE INDEX <index_name>
ON <table_name>(<column_name>)
• DROP INDEX <index_name>