Introduction to SQL

by K. Yue

1. Introduction

2. Exercises and Examples of Basic SQL

We will use MySQL. Either download your own version of MySQL or connect to the MySQL server at dcm.uhcl.edu (port 3306).

DDL:

Examples:

-- Drop tables before creating them again.
-- Note that Supply needs to be dropped first.
-- Otherwise referential integrity may be violated.
DROP TABLE SUPPLY;
DROP TABLE PART;
DROP TABLE SUPPLIER;

-- Create tables
CREATE TABLE SUPPLIER (
  SNUM varchar(9),
  SNAME varchar(15),
  SCITY varchar(15),
  STATUS integer(3),
  primary key (SNUM)
);

CREATE TABLE PART (
  PNUM varchar(9),
  PNAME varchar(15),
  COLOR varchar(12),
  WEIGHT integer(5),
  primary key (PNUM)
);

CREATE TABLE SUPPLY (
  SNUM varchar(9),
  PNUM varchar(9),
  QUANTITY integer(6),
  primary key (SNUM, PNUM),
  foreign key (SNUM) references SUPPLIER(SNUM),
  foreign key (PNUM) references PART(PNUM)
);

Examples:

CREATE VIEW Houston_Supplier AS
SELECT *
FROM SUPPLIER
WHERE SCity = 'Houston';


mysql> SELECT *
-> from Houston_Supplier;
+------+-------+---------+--------+
| SNUM | SNAME | SCITY | STATUS |
+------+-------+---------+--------+
| S2     | DEF    | Houston  | 20      |
| S3     | Go go | Houston  | 12       |
+------+-------+---------+--------+
2 rows in set (0.01 sec)

DML

The Select Statement

SELECT <columns>
FROM <relations>
WHERE <condition>;

Example:

-- All suppliers with Status between 5 to 15.
SELECT *
FROM Supplier
WHERE Status BETWEEN 5 AND 15;

-- All suppliers with status of 1, 5, 10 or 20.
-- Order by status.
SELECT *
FROM Supplier
WHERE Status IN (1, 5, 10, 20)
ORDER BY Status;

-- All suppliers with the character 'o' in the City.
SELECT *
FROM Supplier
WHERE SCity LIKE '%o%';

Group by and having:

Example:

-- Average status of suppliers grouped by city.
select SCITY, 'Number of suppliers =', COUNT(*) ,
'Average Status = ', AVG(STATUS)
from Supplier
group by SCity;

-- Average weight of parts, grouped by color, counting only parts with weight more than 3
-- and showing only results of color with average weidht more than 5.
select Color, COUNT(*) as 'count',
AVG(Weight) as 'Average Weight'
from Part
and weight > 3
group by Color
having Avg(Weight) > 5;