chapter 5 introduction to sql. structured query language = the “programming language” for...

28
Chapter 5 Introduction to SQL

Upload: prudence-baker

Post on 26-Dec-2015

233 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

Chapter 5

Introduction to SQL

Page 2: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• Structured Query Language • = the “programming language” for relational

databases• SQL is a nonprocedural language = the user

specifies what must be done (ex. create a table), but not how it is to be done.

• Several SQL dialects exist, in different RDBMSs; minor differences among them.

SQL

2

Page 3: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• Use CREATE TABLE command for each db table, basic syntax:CREATE TABLE tablename (

column_1 data_type [constraints] ,column_2 data_type [constraints],…column_k data_type [constraints] ,PRIMARY KEY (column_i [, column_j …]) ]

);

• Notes:– End each SQL command with a semicolon to execute it;– A comma separates all table element (column, PK) definitions;

SQL – Creating DB Tables

3

Page 4: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

sql.sql

CREATE DATABASE sitename;

USE sitename;CREATE TABLE users (…First_name VARCHAR(20) NOT NULL,…};

Page 5: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

VARCHAR

• Variable length string– Size varies from record to record.

Page 6: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

create_myusers.sql

• CSC301\create_myusers.sql• How would you create the table in db_frank?

J:\>mysql -h cscdb.nku.edu -u frank -D db_frank -p < CSC301\create_myusers.sqlEnter password: ******

Page 7: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

insert_myusers.sql

• CSC301\insert_myusers.sql• How would you upload this to

db_fall15_frank?

J:\>mysql -h csweb.hh.nku.edu -u frank -D db_fall15_frank -p < CSC301\insert_myusers.sqlEnter password: ******

Page 8: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• After you create the tables in your database, you can view:– All tables in the currently used database

with:

show tables;

– The structure of any of the tables in the

current database with:

describe table_name;

MySQL - SHOW and DESCRIBE

8

Page 9: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

myusers

J:\>mysql -h csweb.hh.nku.edu -u frank -pEnter password: ******mysql> use db_fall15_frank;mysql> show tables;mysql> describe myusers;

Page 10: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• Use DROP TABLE command for each db table you want to delete; basic syntax:

DROP TABLE tablename;

• Note:– This command deletes all the rows in the table tablename and the

table tablename itself!

SQL – Deleting DB Tables

10

Page 11: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• SQL requires the use of the INSERT command to enter data into a table.

• INSERT command’s basic syntax:

INSERT INTO tablename

VALUES (value_1, value_2, … , value_n);

– This version of INSERT: • adds one table row (tuple) at a time• requires a value to be specified for every column of the table;

values are specified in the same order columns were defined in

DML – Adding Table Rows

11

Page 12: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

sql.sql

• INSERT INTO users …

• SHA1('mypass') – 160 bit hash digest of password

• NOW() – function return the current system date and time

Page 13: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• Example:insert into customers values (1, "Julie Smith", "25 Oak Street", "Airport West");insert into orders values (NULL, 1, 49.99, "2007-04-15");

• Notes:–The row contents are delimited by parentheses–Attribute entries are separated by commas–String and date values must be quoted (‘ or “)–Numerical entries are not enclosed in any special characters

INSERT

13

Page 14: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

myusers

INSERT INTO myusers VALUES (NULL, ‘Charles', ‘Frank', ‘[email protected]', SHA1(‘secret'), NOW());

Page 15: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• SELECT command is used to list the contents of a table (or more tables).

• The simplest form (syntax) of a SELECT query is:

SELECT column_listFROM tablename;

– Column_list represents one or more attributes from tablename, separated by commas

SELECT

15

Page 16: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• Example:SELECT name, city FROM customers; the result contains all the rows and only the two specified columns of table customers.

SELECT

16

Page 17: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

sql.sql

SELECT * FROM forums;

Asterisk (*) can be used as a wildcard character to list all attributes for the selected rows (when column_list is *)

SELECT user_id, username FROM users;

Page 18: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• Can limit data selected by placing conditional restrictions on the rows to be included in the output → with the WHERE clause of the SELECT statement.

• Syntax:SELECT column_listFROM tablename[ WHERE condition_list ] ;

Will retrieve all the rows that match the conditions specified in the optional WHERE clause

If no rows match the specified criteria result = an empty set of tuples (not an error!) 18

Listing Table Rows

condition_list = one or more conditional expressions connected by logical operators

Page 19: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• WHERE clause example:SELECT title FROM books WHERE price > 40;

• Conditional restrictions in the condition_list :column_name comparison_operator valueexpression comparison_operator expressionexpression – with columns and values (constants) as operands;

– Comparisons include the usual “suspects”• =, !=, <, etc.• Also can use BETWEEN value1 AND value2

– If a data field is empty, can test with IS NULL operator• SELECT name FROM customers WHERE address IS NULL;

Finds records with no address specified19

Listing Table Rows (cont)

Page 20: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• Can match patterns with LIKE– Pattern can be simple characters up to RE– % matches any number of characters, _ matches 1

character• Can match multiple conditions using AND and OR• Can negate a condition using NOT

• Example:SELECT title

FROM books WHERE price > 40 AND author like “Thomas%”;20

Listing Table Rows (cont)

Page 21: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• Can sort results of query with ORDER BY:SELECT column_listFROM tablename[ORDER BY column1 [ASC | DESC], column2 [ASC | DESC] …];

• Notes:–Although ORDER BY produces a sorted output, the actual table contents

are unaffected by the ORDER BY clause!–ORDER BY clause must be listed last in SELECT (except for LIMIT)

• Example:–SELECT title, price, author FROM books ORDER BY price, author; all books info sorted by price and, for same price, ordered by the author21

Listing Table Rows

default

Page 22: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

myusers

mysql> select * from myusers;

mysql> select email from myusers where last_name='Frank';

mysql> select * from myusers where email like '%edu';

Page 23: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• Use the UPDATE command to modify data in a table.• UPDATE command’s syntax:

UPDATE tablenameSET column_1 = expression_1 [, column_2 = expression_2 …][WHERE condition_list];

–expression = a simple value (76 or ‘Florida’), or a formula (price – 10)–condition_list = one or more conditional expressions connected by logical operators (and, or, not)

• If more than one attribute is to be updated per tuple, separate modifications with commas

Updating Table Rows

23

Page 24: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• Examples:UPDATE booksSET price = price * 1.1;– increase all the book prices by 10%

UPDATE customersSET address = ‘250 Olsens Road’WHERE customer_id = 4;• update a certain customer’s address – PK used to identify the customer

• Notes:– The WHERE clause is optional– If a WHERE clause is not specified, all rows from the specified table

will be modified.

Updating Table Rows (cont)

24

Page 25: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

myusers

mysql> select * from myusers;

mysql> UPDATE myusers SET email='[email protected]' WHERE user_id = 18;

mysql> select * from myusers where user_id='18';

Page 26: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• Use the DELETE command to delete data from a table.

• DELETE command’s syntax:

DELETE FROM tablename[WHERE condition_list ];

• Notes:– WHERE clause is optional– If a WHERE clause is not specified, all rows from the

specified table will be deleted

DML – Deleting Table Rows

26

Page 27: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

• Examples:

DELETE FROM customersWHERE customer_id = 4; – delete data about a customer who didn’t place orders for a long

time

DELETE FROM books WHERE price < 4;

• delete all cheap books (none, one, or more tuples can satisfy the condition)

DELETE FROM books;• delete all books; table is not deleted, but remains empty

Deleting Table Rows (cont)

27

Page 28: Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user

myusers

mysql> DELETE FROM myusers WHERE user_id = 8 LIMIT 1;

mysql> select * from users limit 10;