Lec03 SQL Basics
Lec03 SQL Basics
1
Multi-column Keys
• This makes name a key:
2
Multi-column Keys
• Syntax change if a primary key has multiple columns:
goes away
CREATE TABLE Company(
name VARCHAR(20) PRIMARY KEY,
country VARCHAR(20),
employees INT,
added
for_profit BOOLEAN,
PRIMARY KEY (name, country));
3
Multi-column Keys (2)
• Likewise for secondary keys:
goes away
CREATE TABLE Company( name VARCHAR(20)
UNIQUE,
country VARCHAR(20),
employees INT,
added
for_profit BOOLEAN,
UNIQUE (name, country));
4
Multi-column Keys (3)
• This makes manufacturer a foreign key:
5
Multi-column Keys (3)
• Similar syntax for foreign keys:
6
One Way to Input Data
• Write a program that outputs SQL statements:
for (int a = 1; a <= 50; a++)
for (int b = 1; b <= 50; b++)
System.out.format(
“INSERT INTO T VALUES (%d,%d);\n“,
a, b);
• Feed those into SQLite:
sqlite3 foo.db < inputs.sql
7
Demo: MakeTriples.java
8
Warning
• Be very careful when doing this with strings:
System.out.format(
”INSERT INTO T2 VALUES (%d, ‘%s’);”,
3, ”O’Shaughnessy”);
Becomes:
INSERT INTO T2 VALUES (3, ‘O’Shaughnessy’);
which is a syntax error in this case
9
https://xkcd.com/327/
10
Warning (cont)
• Be very careful when doing this with strings:
System.out.format(
”INSERT INTO T VALUES (%d, ‘%s’);”,
3, ”O’Shaughnessy”);
• This allows a SQL injection attack!
– Must check for quotes and escape (or disallow) them.
– We’ll see safer ways to do this using JDBC
12
Demo: websql.html in Chrome
(Note: this HTML/JS code is out of class scope)
13
Physical Data Independence
• SQL doesn’t specify how data is stored on disk
• Examples in lec03-sql-basics.sql
16
Joins
• Can use data from multiple tables:
SELECT pname, price
FROM Product, Company
WHERE manufacturer = cname AND
country = ‘Japan’ AND
price < 150;
17
Interpreting Joins
• A JOIN B produces one row for every pair of rows
– one row from A and one row from B
18
Interpreting Joins
• A JOIN B produces one row for every pair of rows
– one row from A and one row from B
19
Interpreting Joins
• A JOIN B produces one row for every pair of rows
– one row from A and one row from B
20
Interpreting Joins
• A JOIN B produces one row for every pair of rows
– one row from A and one row from B
21
Interpreting Joins
• A JOIN B produces one row for every pair of rows
– one row from A and one row from B
22
Interpreting Joins
• A JOIN B produces one row for every pair of rows
– one row from A and one row from B
23
Interpreting Joins
• A JOIN B produces one row for every pair of rows
– one row from A and one row from B
Cname Country Pname Price Manufacturer
Canon Japan SingleTouch 149.99 Canon
26
Join Examples
• See lec03-sql-basics.sql…
27