structured query language sql ist359 m005 yang wang [email protected] 342 hinds

24
Structured Query Language SQL IST359 M005 Yang Wang [email protected] 342 Hinds http://blackboard.sy r.edu

Upload: augustine-powers

Post on 23-Dec-2015

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

Structured Query LanguageSQL

IST359 M005

Yang [email protected] Hindshttp://blackboard.syr.edu

Page 2: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

Acknowledgements and caveat

These slides draw liberally, with permission, from the following sources:

• IST359 materials by Prof. Michael Fudge Jr.• Slides from Murach’s SQL Server 2008 book

Caveat (beware): At best, PowerPoint slides are only a pale limitation of the entirety of a class meeting. In IST359 in particular, the lectures will cover topics beyond what appears in these slides. Don’t rely on them as a substitute for attending class.

Page 3: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

Learning Objectives

• Describe and use basic SQL commands• Explain how and why SQL is used, and

why it’s important• Compare and contrast DML and DDL• Use SQL commands to create metadata

structures and perform CRUD operations.

Page 4: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

WHAT IS SQL?

A computer programming language designed for managing data and structures (metadata) in relational database management systems.

Page 5: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

Brief History of SQL

• 1970– E. Codd develops relational database concept

• 1974-1979–System R with Sequel (later SQL) created at IBM Research Lab

• 1979–Oracle markets first relational DB with SQL

• 1986–ANSI SQL standard released• 1989, 1992, 1999, 2003, 2007–Major ANSI

standard updates• Current–SQL is supported by most major

database vendors at 1999, 2003 and 2007

Page 6: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

The SQL Server Environment

Server

Instance

Instance

Catalog (db) Catalog (db)

Schema Schema

Objects

Catalog (db) Catalog (db)

Schema Schema

ObjectsIn this class we use:• SQL Server ist-s-students.syr.edu• Instance . (default)• Catalog ist359yournetid#• Schema dbo (default)

Page 7: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

SQL Server 2008 R2: ist-s-students

• Other Information:– SQL Dialect: T-SQL / Transact-SQL– Case Sensitive Collation?: Yes– System tables used to represent meta data.– Client / Server over TCP/IP Connect to database using:

• host/IP, port number, logon, password• Client software used to manage data/meta data on server

– Everything can be expressed in SQL!• Naming Rules for Objects in SQL Server:

– Up to 128 characters long– Must begin with a letter or _, @, # (cannot be a digit)– Can contain digits, letters, _, .– Spaces can be used but should be avoided.

Page 8: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

My Naming ConventionsWhat Mike’s Convention Rationale for use

All object names Use all lower case letters. Disambiguation: eg. Employee vs. employee for example

All object names Use underscore in place of SPACE

Avoid the need to place brackets around identifiers. employee_phone_number vs. [employee phone number]

Tables Pluralize Should be employees table, since it contains more than one employee

Tables Qualify with logical schema Disambiguation of objects within the same database: eg. kmart_employees vs. netflix_employees

Column names Qualify with table name Helps define scope of object. Eg. employee_zipcode .vs vendor_zipcode

Constraints pk= primary keyfk=foreign keyu=uniqueck=checki=index

Disambiguation of constraints, for example: ck_vendor_zipcode .vs. fk_vendor_zipcode

Page 9: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

SQL: Language BreakdownDomain SQL Commands Objects

Metadata(DDL)

CREATEALTERDROP

Tables, functions, views, procedures, etc

DATA(DML)

C - INSERTR - SELECTU - UPDATED - DELETE

Tables (as a target)

Security(DCL)

GRANTREVOKE

Tables, functions, views, procedures, etc.

Transactions(DTL)

BEGIN TRANSCOMMITROLLBACK

Controls DML statements

Page 10: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

Workflow in SQL Mgmt Studio

1. Type in SQL2. Highlight it3. Check it

(For syntax errors)4. Wreck it

(Execute on Server)5. Once you execute “the program has run and

the damage is done.” There is no undo, only redo, meaning if you delete something to get it back you must start over again.

Page 11: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

DDL 1

• Create students table w/Defaults• ID• Name• Email• GPA• Year

(Fr, So, Jr, Sr)• Are they iSchool?• DOB?

Page 12: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

Murach’s SQL Server 2008, C10 © 2008, Mike Murach & Associates, Inc.

Page 13: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

Common column attributes

Attribute Description NULL|NOT NULL Indicates whether or not the column

can accept null values. NULL is the default unless PRIMARY KEY is specified.

PRIMARY KEY|UNIQUE Identifies the primary key or a unique key for the table. If PRIMARY KEY is specified, the NULL attribute isn’t allowed.

IDENTITY Identifies an identity column. Only one identity column can be created per table.

DEFAULT default_value Specifies a default value for the column.

SPARSE Optimizes storage of null values for the column. This attribute was introduced with SQL Server 2008.

Murach’s SQL Server 2008, C10 © 2008, Mike Murach & Associates, Inc.

Page 14: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

DDL2

• Students tableadd constraints

• Primary Key• Unique emails• Valid GPA’s

Page 15: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

Column and table constraints

Constraint At the column level At the table levelNOT NULL Prevents null values

from being stored inthe column.

n/a

PRIMARY KEY Requires that each rowin the table have aunique value in thecolumn. Null valuesare not allowed.

Requires that each rowin the table have aunique set of valuesover one or morecolumns. Null valuesare not allowed.

UNIQUE Requires that each rowin the table have aunique value in thecolumn.

Requires that each rowin the table have aunique set of valuesover one or morecolumns.

Murach’s SQL Server 2008, C10 © 2008, Mike Murach & Associates, Inc.

Page 16: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

Column and table constraints (continued)

Constraint At the column level At the table levelCHECK Limits the values for a

column.Limits the values forone or more columns.

[FOREIGN KEY]REFERENCES

Enforces referentialintegrity between acolumn in the newtable and a column in arelated table.

Enforces referentialintegrity between oneor more columns in thenew table and one ormore columns in therelated table.

Murach’s SQL Server 2008, C10 © 2008, Mike Murach & Associates, Inc.

Page 17: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

DML

• Add students• List students• Find one student• Update students• Update one student

Page 18: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

The syntax of the INSERT statement INSERT [INTO] table_name [(column_list)] [DEFAULT] VALUES (expression_1 [, expression_2]...) [, (expression_1 [, expression_2]...) ...]

How to insert a single row into a table You use the INSERT statement to add a new row to a table.

In the INSERT clause, you specify the name of the table that you want to add a row to, along with an optional column list.

You specify the values to be inserted in the VALUES clause. The values you specify depend on whether you include a column list.

If you don’t include a column list: You must code a value for every column, in the same order as they appear in the table. The only exception is an identity column, which must be omitted.

Murach’s SQL Server 2008, C10 © 2008, Mike Murach & Associates, Inc.

Page 19: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

The basic syntax of the SELECT statementSELECT select_listFROM table_source[WHERE search_condition][ORDER BY order_by_list]

The four clauses of the SELECT statement

Clause Description

SELECT Describes the columns that will be included in theresult set.

FROM Names the table from which the query will retrievethe data.

WHERE Specifies the conditions that must be met for a row tobe included in the result set. This clause is optional.

ORDER BY Specifies how the rows in the result set will be sorted.This clause is optional.

Murach’s SQL Server 2008, C10 © 2008, Mike Murach & Associates, Inc.

Page 20: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

The syntax of the UPDATE statement UPDATE table_name SET column_name_1 = expression_1 [, column_name_2 = expression_2]... [FROM table_source [[AS] table_alias] [WHERE search_condition]

How to perform a basic update operation You use the UPDATE statement to modify one or more rows in

the table named in the UPDATE clause.

You name the columns to be modified and the value to be assigned to each column in the SET clause.

You can specify the value for a column by using a literal, an expression, or the DEFAULT or NULL keyword when appropriate.

Warning: If you omit the WHERE clause, all the rows in the table will be updated.

Murach’s SQL Server 2008, C10 © 2008, Mike Murach & Associates, Inc.

Page 21: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

The syntax of the DELETE statement DELETE [FROM] table_name [FROM table_source] [WHERE search_condition]

How to perform a basic delete operation You can use the DELETE statement to delete one or more rows

from the table you name in the DELETE clause.

You specify the conditions that must be met for a row to be deleted in the WHERE clause.

You can specify additional criteria for the delete operation in the FROM clause.

Warning: If you omit the WHERE clause, all the rows in the table will be deleted.

Murach’s SQL Server 2008, C10 © 2008, Mike Murach & Associates, Inc.

Page 22: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

Lookup table

• Create table student_years• Add pk to table• Add data to student_years • Alter students add FK

Page 23: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

The basic syntax of the ALTER TABLE statementALTER TABLE table_name [WITH CHECK|WITH NOCHECK]{ADD new_column_name data_type [column_attributes] | DROP COLUMN column_name | ALTER COLUMN column_name new_data_type [NULL|NOT NULL] | ADD [CONSTRAINT] new_constraint_definition | DROP [CONSTRAINT] constraint_name}

How to alter a table The ALTER TABLE statement to modifies an existing table. You can use this statement to add columns or constraints, drop

columns or constraints, or change the definition of an existingcolumn, including changing the column’s data type.

Before SQL Server changes the data type of a column, it checks tobe sure that no data will be lost. If it will, the operation isn’t done.

You can modify a column to allow null values as long as thecolumn isn’t defined as the primary key.

Murach’s SQL Server 2008, C10 © 2008, Mike Murach & Associates, Inc.

Page 24: Structured Query Language SQL IST359 M005 Yang Wang ywang@syr.edu 342 Hinds

The syntax of a column-level foreign keyconstraint

[FOREIGN KEY] REFERENCES ref_table_name (ref_column_name) [ON DELETE {CASCADE|NO ACTION}] [ON UPDATE {CASCADE|NO ACTION}]

The syntax of a table-level foreign key constraintFOREIGN KEY (column_name_1 [, column_name_2]...) REFERENCES ref_table_name (ref_column_name_1 [, ref_column_name_2]...) [ON DELETE {CASCADE|NO ACTION}] [ON UPDATE {CASCADE|NO ACTION}]

Murach’s SQL Server 2008, C10 © 2008, Mike Murach & Associates, Inc.