sql 101 for web developers 14 november 2012. what is a database and why have one? tables,...

Post on 01-Jan-2016

216 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

SQL 101for Web Developers

14 November 2012

• What is a database and why have one?• Tables, relationships, normalization• SQL– What SQL is and isn’t– CRUD: four basic operations– Select queries step by step– Using JOINs in SELECT queries

• Next steps and resources

What is a database and why?

• A database can be as simple as a single, excel-like table

• For your website, a database brings you the power of dynamic data

• Different technologies are used (e.g., MySQL, SQL Server, Access, Oracle, Sybase, DB2, SQLite) but most website-connected dbs are relational databases

Student records – one table

A database is a whole spreadsheet file.A table is a tab/sheet in the spreadsheet, with

each one being given a name.A column is a column in both.A row is a row in both.

name phone course term grade

Tom Rees 111-2222 ENG 101 Spring 2009 3.5

Beth Hardy 333-4444 EEB 102 Fall 2009 3.0

Tom Rees 111-2222 EEB 102 Fall 2010 3.5

Student records – one tablename phone course term grade

Tom Rees 111-2222 ENG 101 Spring 2009 3.5

Beth Hardy 333-4444 EEB 102 Fall 2009 3.0

Tom Rees 111-2222 EEB 102 Fall 2010 3.5

fname lname phone course_prefix

course_num

term year grade

Tom Rees 111-2222 ENG 101 Spring 2009 3.5

Beth Hardy 333-4444 EEB 102 Fall 2009 3.0

Tom Rees 111-2222 EEB 102 Fall 2010 3.5

Normalized Data

Normalized Data

Table relationships

• Primary keys – unique identifier for each record in one table

• Primary keys – also used to build relationships among tables– one-to-one (studentID to email address)– one-to-many (one student – many enrollment

records)– many-to-many (many students to many sections)

Table relationshipsMany to many: books and authorsAuthor table: authorID nameBook table: bookID, title, ISBNBook_Author table:

Book_AuthorID bookID authorID

1 3 6

2 3 9

3 4 7

4 5 9

SQL statements

• SQL is a standard language for accessing databases.

• It is not a programming language or a scripting language.

• Four basic types of queries: “CRUD” stands for– create– read– update– delete

SQL statements

• Four basic types: “CRUD” stands for– (create)

CREATE (table) INSERT INTO (table) VALUES– (read) SELECT column_names FROM table_name– (update) UPDATE– (delete) DELETE rows, DROP tables

SELECT * FROM student_records; (will get entire contents of table)

SELECT fname FROM student_records;+---------+| fname |+---------+| Tom || Beth || Tom |+---------+

fname lname phone course_prefix

course_num

term year grade

Tom Rees 111-2222 ENG 101 Spring 2009 3.5

Beth Hardy 333-4444 EEB 102 Fall 2009 3.0

Tom Rees 111-2222 EEB 102 Fall 2010 3.5

SELECT grade FROM student_records WHERE lname = 'Rees';

+---------+| grade |+---------+| 3.5 || 3.5 |+---------+

• The WHERE statement lets you filter records• Lots of operators in addition to =

fname lname phone course_prefix

course_num

term year grade

Tom Rees 111-2222 ENG 101 Spring 2009 3.5

Beth Hardy 333-4444 EEB 102 Fall 2009 3.0

Tom Rees 111-2222 EEB 102 Fall 2010 3.5

• SELECT * FROM student_records WHERE lname = 'Rees' AND term = 'Fall';

• SELECT * FROM student_records WHERE lname = 'Rees' AND (term = 'Fall' OR term = 'Spring');

• SELECT * FROM student_records WHERE lname LIKE 'R%';

• SELECT * FROM student_records WHERE lname IN ('Rees', 'Hardy');

SELECT fname, lname FROM student_records ORDER BY lname;

+---------+---------+| fname | lname |+---------+---------+| Tom | Rees || Tom | Rees || Beth | Hardy |+---------+---------+

SELECT DISTINCT lname FROM student_records;

+---------+| lname |+---------+| Rees || Hardy |+---------+

Why you must be familiar with your data:

When you get results back from a query, how do you know you got the right results?

Joins

Joins• JOIN (Inner Join): Return rows when there is at least

one match in both tables

• LEFT (Outer) JOIN: Return all rows from the left table, even if there are no matches in the right table

• RIGHT (Outer) JOIN: Return all rows from the right table, even if there are no matches in the left table

• FULL (Outer) JOIN: Return rows when there is a match in one of the tables

Joins

• The syntax used determines which table will be fully represented.

• A row of NULL values is substituted when a matching row is not present.

table “Author” contains names of authors, with the primary key “Author_ID”

table “Book_Author” contains ISBN numbers, keyed with the primary key “Book_Author_ID” and linked to the Author table by the foreign key “Author_ID.”

SELECT First_Name, Last_Name, ISBN FROM Author INNER JOIN Book_Author ON Author.Author_ID = Book_Author.Author_ID;

+------------+-----------+------------+| First_Name | Last_Name | ISBN |+------------+-----------+------------+| Chad | Russell | 1590593324 || Jon | Stephens | 1590593324 |+------------+-----------+------------+

This INNER JOIN only gets rows where there is a match. If an author doesn’t have a book, and a book doesn’t have an author, neither type of record shows up.

When we need at least one row in the result set for every row in a given table, regardless of matching rows, we use an OUTER JOIN query.

SELECT First_Name, Last_Name, ISBN FROM Author LEFT OUTER JOIN Book_Author ON Author.Author_ID = Book_Author.Author_ID;

+------------+-----------+------------+

| First_Name | Last_Name | ISBN |

+------------+-----------+------------+

| Chad | Russell | 1590593324 |

| Jon | Stephens | 1590593324 |

| Mike | Hillyer | NULL |

+------------+-----------+------------+

This query will NOT return rows for books that don’t have an author – just authors that don’t have a book.

SELECT s.first_name,

s.last_name, c.course_prefix,

c.course_number

FROM students s,

courses c, enrollment e,

sections sc

WHERE s.student_id

= e.student_id

AND e.section_id

= sc.section_id

AND c.course_id

= sc.course_id;

Although not explicitly named as such, this is an INNER JOIN.

How do you grab the data output from a query?

Depends on your database type and your programming or scripting language

(for example, you can use PHP functions to read the result set one row at a time and put the results into an array.)

What didn’t we cover?

• Database optimization and performance• Security issues like sql injection• Data integrity and constraints• Data types• Views• Triggers• Transactions• PDOs

What else didn’t we cover?

• Logic• Math expressions• String manipulation• Parameterized queries• Database design• Different database technologies

Why do I need to know any SQL when my CMS does it all for me?

• It helps to know your data• Sometimes the fastest way to fix a problem is with a straight

database query• You can check up on the queries written by your CMS• You can’t always use a CMS – sometimes you need to write a

custom web app.• You might need to migrate data from your department’s

Access database into another db.

• What is a database and why have one?• Tables, relationships, normalization• SQL– What SQL is and isn’t– CRUD: four basic operations– Select queries step by step– Using JOINs in SELECT queries

• Next steps and resources: depends on the technologies you are using. There are a lot of good online tutorials, and of course books.

I like “Learn SQL the hard way”http://sql.learncodethehardway.org/book/

(coaches you through creating a SQLite db on your local computer, entering data into it, and then running queries on it)

Why is it “the hard way”? Enforces precision, attention to detail, and persistence by requiring you to type each exercise (no copy-paste!) and make it run.

top related