Databases

Querying Databases with SQL

Lecture 3: MySQL DML Operations

INSERT, SELECT, UPDATE, DELETE, JOIN

Relational databases : Querying


Relational databases : Inserting with "INSERT"


Relational databases : Updating with "UPDATE"

Relational databases : deleting with "DELETE"


Relational databases : Querying


SQL Queries : practising with MySQL

Select with WHERE clauses : practising

JOIN operators

Different types of JOIN

Exercise : practising Select with joins


Exercise : Going further with SQL Queries


Integrating with Programming languages


Integrating with Programming languages (2)


Integrating with Programming languages(3)


Exercise: Practice Basic Queries

Using the facilities/bookings database, write queries for:

  1. List all facilities with monthly maintenance cost greater than $100
  2. List all members who joined after January 1st, 2012
  3. Count how many bookings were made by member ID 1
  4. Find the total number of slots booked per facility
  5. List facilities that have never been booked
-- Example solution for #1:
SELECT * FROM facilities 
WHERE monthlymaintenance > 100;
    

Exercise: Practice JOINs

Write queries that combine multiple tables:

  1. List all bookings with member names (not IDs)
  2. Show facility names with their total booking revenue
  3. Find members who have never made a booking
  4. List the top 5 most popular facilities by number of bookings
-- Example solution for #1:
SELECT b.*, m.firstname, m.surname 
FROM bookings b
INNER JOIN members m ON b.memid = m.memid;
    

MySQL String Functions

Function Description Example
CONCAT() Concatenate strings CONCAT(firstname, ' ', lastname)
UPPER() / LOWER() Convert case UPPER(name)
SUBSTRING() Extract substring SUBSTRING(text, 1, 10)
LENGTH() String length LENGTH(description)

MySQL Date Functions

Function Description Example
NOW() Current date and time SELECT NOW()
CURDATE() Current date SELECT CURDATE()
DATE_ADD() Add interval to date DATE_ADD(NOW(), INTERVAL 7 DAY)
DATEDIFF() Difference between dates DATEDIFF(date1, date2)
YEAR() / MONTH() / DAY() Extract date parts YEAR(order_date)

Slide Overview