Reaves.dev

v0.1.0

built using

Phoenix v1.7.12

SQL

Stephen M. Reaves

::

2023-06-17

Notes about Lesson 8 of CS-6400

Summary

History

SQL is lingua franca of dbs.

Originally known as SEQUEL: Strucuted English QUEry Language

Based on relational tuple calculus and some algebra

ANSI & ISO Standars:

SQL is supported by a lot of DBs:

Operations

INSERT INTO UserInterests (Email, Interest, SinceAge)
VALUES ('[email protected]', 'Reading', 5);
DELETE FROM UserInterests
Where Interest = 'Swimming';
UPDATE UserInterests
SET Interest = 'Rock Music'
WHERE Email = '[email protected]'
  AND Interest = 'Music';

Queries

SELECT column1, column2, ..., columnn
FROM table1, table2, ..., tablem
WHERE condition;

is equivalent to

πcolumn 1, , column n(σcondition(table1××tablem))\pi _\text{column 1, \dots, column n} (\sigma _\text{condition} (table_1 \times \dots \times table_m))

If there is no WHERE clause, the query defaults to a cartesian product.

SELECT *
FROM RegularUser
WHERE HomeTown    = 'Atlanta'
   OR CurrentCity = HomeTown;

Joins

Natual Inner Join

Regular User

EmailBirthYearSex
[email protected]1985M
[email protected]1988M

YearSalary

BirthYearSalary
198527,000
SELECT Email, RegularUser.BirthYear, Salary
FROM RegularUser, YearSalary
WHERE RegularUser.BirthYear = YearSalary.BirthYear;

or

SELECT Email, RegularUser.BirthYear, Salary
FROM RegularUser NATURAL JOIN YearSalary;

or

SELECT Email, R.BirthYear, Salary
FROM RegularUser AS R, YearSalary AS Y
WHERE R.BirthYear = Y.BirthYear;

Result

EmailBirthYearSalary
[email protected]198527,000

If there are no same-named attributes, the NATURAL JOIN defaults to cartesian product.

Left Outer Join

Return everything from the left-hand side, include right-hand side data if available.

SELECT EMAIL, R.BirthYear, Salary
FROM RegularUser AS R
LEFT OUTER JOIN YearSalary AS Y;

String Matching

Use LIKE and the % wildcard to match text.

SELECT *
FROM RegularUser
WHERE CurrentCity LIKE 'San%';

% matches any string, including empty string.

_ matches any single character.

Sorting

SELECT *
FROM RegularUser
WHERE Sex = 'M'
ORDER BY CurrentCity ASC;

Set Operations

Union

Set union projection. Useful for combining multiple columns into one.

RegularUser
EmailCurrentCityHomeTown
[email protected]SeattleAtlanta
[email protected]AustinAustin
[email protected]San DiegoPortland
[email protected]San FranciscoAtlanta
[email protected]San DiegoAtlanta
SELECT CurrentCity
FROM RegularUser
UNION
SELECT HomeTown
FROM RegularUser;
Result
Seattle
San Diego
San Francisco
Portland
Atlanta
Austin

Running UNION ALL instead of just UNION will return all instances of the values, not just the distinct.

Intersection

Set intersectoin projection.

RegularUser
EmailCurrentCityHomeTown
[email protected]SeattleAtlanta
[email protected]AustinAustin
[email protected]San DiegoPortland
[email protected]San FranciscoAtlanta
[email protected]College ParkAtlanta
[email protected]College ParkAustin
[email protected]AustinSan Francisco
SELECT CurrentCity
FROM RegularUser
INTERSECT
SELECT HomeTown
FROM RegularUser;
Result
San Francisco
Austin

Running INTERSECT ALL instead of just INTERSECT will return all instances of the values, not just the distinct.

Except

Set intersectoin projection.

RegularUser
EmailCurrentCityHomeTown
[email protected]SeattleAtlanta
[email protected]Las VegasAustin
[email protected]San DiegoPortland
[email protected]San FranciscoSan Diego
[email protected]San DiegoAtlanta
[email protected]Las VegasAtlanta
SELECT CurrentCity
FROM RegularUser
EXCEPT
SELECT HomeTown
FROM RegularUser;
Result
Seattle
Las Vegas
San Francisco

Running EXCEPT ALL instead of just EXCEPT will return all instances of the values, not just the distinct.

Built-in Functions

count, sum, avg, min, max

Group by

If you group by fields, then any field you select needs to be grouped by or an aggregate function.

HAVING is similar to WHERE, but only applies to groups.

Nested Queries

YearSalary
BirthYearSalary
198527,000
196943,000
196745,000
196844,000
198824,000
198626,000
197438,000

and

RegularUser
EmailCurrentCityHomeTown
[email protected]SeattleAtlanta
[email protected]AustinAustin
[email protected]San DiegoPortland
[email protected]San DiegoAtlanta
[email protected]College ParkAtlanta
[email protected]College ParkAustin
SELECT CurrentCity
FROM RegularUser R, YearSalary Y
WHERE R.BirthYear = Y.BirthYear
  AND Y.Salary > ALL
  (SELECT Salary
   FROM RegularUser R, YearSalary Y
   WHERE R.BirthYear = Y.BirthYear
     AND R.HomeTown = 'Austin');
Result
CurrentCity
San Diego
College Park

Equivalent statement

SELECT CurrentCity
FROM RegularUser R, YearSalary Y
WHERE R.BirthYear = Y.BirthYear
  AND Y.Salary > 
  (SELECT max(Salary)
   FROM RegularUser R, YearSalary Y
   WHERE R.BirthYear = Y.BirthYear
     AND R.HomeTown = 'Austin');

Correlated Query

SELECT R.Email, BirthYear
FROM RegularUser R
WHERE NOT EXIST
  (SELECT *
   FROM UserInterest U
   WHERE U.Email = R.Email);

Views

PDF Notes

Definition

A view is a virtual table.

The definition is stored in the catalog.

CREATE VIEW AtlantaUserInterests AS
SELECT U.Email, Interest, SinceAge
FROM UserInterests I, RegularUser U
WHERE I.Email = U.Email
  AND HomeTown = 'Atlanta';

Columns in a view:

Since a view is a virtal table, “updates” to a view can only be done by the DBMS by updating the base tables from which the view is defined.

Updatable Rules

A view is updatable if and only if:

Updatable means INSERT, DELETE, and UPDATE are ok.

Not Updatable Examples

-- Not Unique
CREATE VIEW SexHomeTown AS
SELECT Sex, HomeTown
FROM RegularUser
WHERE BirthYear >= 1969;

-- Computed Attribute
CREATE VIEW AvgUserInterestSinceAge AS
SELECT Email, AVG(SinceAge)
FROM UserInterests
GROUP BY Email;

-- Join
CREATE VIEW AtlantaUserInterests AS
SELECT U.Email, Interest, SinceAge
FROM UserInterests I, RegularUser U
WHERE I.Email = U.Email AND HomeTown=‘Atlanta’;

Updatable Examples

CREATE VIEW UserInterestsSinceTeen AS
SELECT *
FROM UserInterests
WHERE SinceAge >= 13;

-- Moves row(s) outside the view
UPDATE UserInterestsSinceTeen
SET SinceAge = 12
WHERE Interest = ‘DIY’;

-- Creates row outside the view
INSERT INTO UserInterestsSinceTeen
VALUES (‘[email protected]’, ‘Soccer’, 8);

CREATE VIEW UserInterestsSinceTeen AS
SELECT *
FROM UserInterests
WHERE SinceAge >= 13
WITH CHECK OPTION; -- Prevents updates outside the view

Materialized Views

To create a materialized view, we use the following syntax:

CREATE MATERIALIZED VIEW ViewName
[REFRESH [FAST|COMPLETE|FORCE] [ON DEMAND|ON COMMIT]] [BUILD IMMEDIATE|BUILD DEFERRED]
AS Select Query;

Options includes:

Source

Remember that the syntax and semantics may vary in different commercial DBMSs.