Industry standard for interacting with relational databases Statements to Enter, Retrieve, Modify,...

35

Transcript of Industry standard for interacting with relational databases Statements to Enter, Retrieve, Modify,...

Industry standard for interacting with relational databases

Statements to Enter, Retrieve, Modify, Remove & Display data stored in database tables◦ Pose Ad-Hoc Queries◦ Create Various Objects◦ Perform Database Maintenance

Works with SQL-Server and almost all other data management sytems

Query Statements Data Definition Language Statements Data Manipulation Language Statements Transaction Control Statements Data Control Language Statements

Retrieve rows from one or more tables◦ Select Statement

SELECT FROM WHERE GROUP BY HAVING ORDER BY

Define Structures that make up the database◦ Tables◦ Views

CREATE ALTER DROP RENAME TRUNCATE

Modify the contents of tables◦ INSERT◦ UPDATE◦ DELETE

Tools to make changes to rows permanent, or to revoke the changes◦ COMMIT◦ ROLLBACK◦ SAVEPOINT

Who has access to what tables Who can log into the SQL Server System Access and Privileges for each user for

various tables

◦ GRANT◦ REVOKE

Write SQL statements to accomplish a database task

SQL-Server SQL Server Management Studio Interface

Can be written on multiple lines (cannot split words) Cannot abbreviate words Separate words by at least one white space Not Case Sensitive Commas separate lists Period delimits two names (tableName.fieldName) Single Quotation marks enclose literal character

strings (including dates) Semicolon indicates the end of a SQL Statement

04/18/2310

SQL SELECT Statement Column References ORDER BY Clause WHERE Clause SQL Statement String Construction

04/18/2311

Syntax:SELECT [DISTINCT | ALL] { * | <column list>}FROM <table list> [WHERE <search condition>][GROUP BY <group field list>][HAVING <group criteria>][ORDER BY <order condition>]

04/18/2312

Syntax:<derived column> [[AS] <column name>]

Derived column may◦ Be a column◦ Contain an expression referencing one or more

columns ◦ Contain function arguments

The ‘AS’ is for an alias, or alternate name, for the derived column result

04/18/2313

SELECT First, Last, CitySELECT Player.First, Team.LocationSELECT Price * Qty AS InvoiceAmountSELECT First, [Last Name] AS LastSELECT Max(TeamId)SELECT Avg(Price)SELECT IsNull(Name)SELECT DISTINCT StateSELECT *SELECT Player.*, Team.Nickname

04/18/2314

Specifies which records from the tables listed in the FROM clause are affected by the SELECT statement

Only those records satisfying <search condition> are included in the result

<search condition> is a logical expression which may include:◦ One or more of four types of logical predicates◦ the logical operators AND, OR, NOT

04/18/2315

WHERE clause has four logical predicates:◦ comparisons w/relational operators (<, <=, =,

>=, >, <>)expression1 comparison-operator expression2

◦ LIKE expression LIKE pattern

◦ INexpression [NOT] IN (value1, value2, ...)

◦ BETWEENexpression [NOT] BETWEEN value1 AND value2

04/18/2316

WHERE City = ‘New Orleans’ ‘* relational opsWHERE Rate > 5.50

WHERE State LIKE ‘?L’ ‘* LIKE predicateWHERE [Last Name] LIKE ‘S*’

WHERE State IN (‘AL’, ‘MS’, ‘FL’) ‘* IN predicate

‘* BETWEEN predicateWHERE Birthday BETWEEN #7/1/78# AND #7/30/78#WHERE [Pay Rate] BETWEEN 5.50 AND 10.00

‘* multiple comparisons with AND, OR, NOTWHERE City=‘New Orleans’ AND Name LIKE ‘L*’WHERE NOT State=‘AL’ AND Major=‘CIS’WHERE Class=‘Union’ OR Rate>10.00

04/18/2317

Syntax:ORDER BY <order condition>

Examples:ORDER BY LastName, FirstNameORDER BY HR DESCORDER BY TeamId ASC, HR DESC

04/18/2318

Strings can be constructed in code with concatenation and variables can be concatenated into the string Dim Sql As String

Sql = “Select LName, FName From Emp”

Sql = Sql & “Where Title = ‘“ & cboTitle.Text & “‘;”

When variable contains a string surround it with quotes

Sql = “Select ... WHERE City=‘Jacksonville‘;”or

Sql = “Select ... WHERE City=‘“ & txtCity.Text & “‘;”

When variable contains numeric data do not use quotesSql = “Select ... WHERE Age > “ & intAge & “ ORDER BY Age”

04/18/2319

SQL INSERT statement◦ Adds one or more rows to a table

SQL UPDATE statement◦ Modifies one or more columns of one or more

rows of a table SQL DELETE statement

◦ Removes one or more rows from a table

04/18/2320

Syntax:INSERT INTO <table name> [(<column name>[{,<column name>}…])]VALUES (<value>[{,<value>}…])

◦ Second line is optional If you omit, then values list must be complete and in

order of field creation If you include column list, values list must match

column list in number and order (but not in field creation order

04/18/2321

INSERT INTO Team (League, Location, Nickname, Stadium) VALUES (‘AL’, ‘Mobile’, ‘Bay Bears’, ‘Hank Aaron Stadium’)

04/18/2322

Syntax:UPDATE <table name> SET <set clause expression> [{, <set clause

expression>}…][WHERE <search condition>]

◦ <set clause expression> syntax:<column name> = <value expression>

◦ Omitting WHERE updates all rows

04/18/2323

UPDATE TeamSET Stadium=‘Citizens Bank Park’WHERE Stadium=‘Veterans Stadium’

UPDATE PlayerSET HR=HR + 1WHERE PlayerId=22

04/18/2324

Syntax:DELETE FROM <table name> [WHERE <search condition>]

◦ Omission of WHERE removes all rows

04/18/2325

DELETE FROM TeamWHERE Nickname=‘Bay Bears’

DELETE FROM TeamWHERE League NOT IN ('AL', 'NL')

04/18/2326

A function that generates a single value from a group of values◦ often used with Group By and Having clauses◦ a.k.a. set function

Examples:◦ Avg, Count, Max, Min, and Sum

04/18/23 27

Aggregate function Description

AVG(expr)Average of the values in a column. The column can contain only numeric data.

COUNT(expr), COUNT(*)

A count of the values in a column (if you specify a column name as expr) or of all rows in a table or group (if you specify *). COUNT(expr) ignores null values, but COUNT(*) includes them in the count.

MAX(expr)Highest value in a column (last value alphabetically for text data types). Ignores null values.

MIN(expr)Lowest value in a column (first value alphabetically for text data types). Ignores null values.

SUM(expr)Total of values in a column. The column can contain only numeric data.

04/18/2328

A query (SQL statement) that summarizes information from multiple rows by including an aggregate function such as Sum or Avg◦ For example, you can create a query that

averages the contents of a price columnSELECT Avg(Price) AS AvgPriceFROM Book

04/18/2329

Aggregate queries can also display subtotal information by creating groups of rows that have data in common◦ An example would be a query that displays the

average price of a book for each publisher◦ Use the GROUP BY clauseSELECT PublisherID, Avg(Price) As

AvgPriceFROM BookGROUP BY PublisherID

04/18/2330

Combines records with identical values in the specified field list into a single record.

Syntax:

A summary value is created for each record if you include an SQL aggregate function, such as Sum or Count, in the SELECT statement.

For example total the home runs for each team:SELECT TeamId, Sum(HR) As TeamTotalHRFROM PlayerGroup By TeamId

SELECT <fieldlist>SELECT <fieldlist>

FROM <tableList>FROM <tableList>

[WHERE <criteria>][WHERE <criteria>]

[GROUP BY <groupfieldlist>] [GROUP BY <groupfieldlist>]

[HAVING <condition>][HAVING <condition>]

04/18/2331

Use the WHERE clause to exclude rows you don't want grouped, and use the HAVING clause to filter records after they've been grouped.

For example, team’s with more than 100 homers:SELECT TeamId, Sum(HR) As TotalTeamHR FROM PlayerGROUP BY TeamId HAVING Sum(HR)>100

Or, a count of each team’s players with less than 10 homers:SELECT TeamId, Count(*) As LowHRcount FROM PlayerWHERE HR<10GROUP BY TeamId

Direct Execution◦ Communicate directly through a client application

SQL Server Management Studio Module Binding

◦ Create blocks of SQL statements and combined with a complete application through a linker program

Embedded SQL◦ Statements are placed directly into the host

programming language (C++ or Java)◦ Requires a SQL Server preprocessor

CLI (Call-Level Interface)◦ Invoke SQL statements by passing the statements

directly to the subroutines that process them◦ Executed directly by the DBMS

Rich, Easy to Use environment for creating and executing SQL instructions

Windows dialog box GUI Interface – closely matches Visual

Studio.Net 2005 interface