Sql2
- 2. © Cengage Learning 2014
Objectives
• Analyze and manipulate data stored in a SQL Server
2012 database using the Transact-SQL language
• Create and modify database objects on a SQL
Server 2012 instance using the Transact-SQL
language
• Construct a simple but effective logical security
model for a SQL Server 2012 database using the
Transact-SQL language
2
- 3. © Cengage Learning 2014
Data Manipulation Language (DML)
• Query Editor has a number of features that will help
accelerate learning to read and write SQL code
• Query Editor distinguishes between different
elements in SQL syntax through color coding the
text as follows:
– Blue: keywords
– Black: data values
– Red: text strings
– Teal: database objects
– Green: comments
– Gray: operators
3
- 4. © Cengage Learning 2014
Data Manipulation Language (DML)
• IntelliSense: a text AutoComplete feature that
helps with navigating the object hierarchy and SQL
language
• The SQL language is not case sensitive
– The normal convention is to write all keywords in
uppercase (e.g., SELECT)
• Statement terminator is a semicolon placed to mark
the end of a SQL statement
– Not currently required for all statements but is
considered good practice
4
- 5. © Cengage Learning 2014
A Simple Query
• The SELECT statement is used to retrieve data
– The most commonly used statement in SQL
• Basic syntax for a SELECT statement:
SELECT [Column Name]
FROM [Table Name] ;
– After specifying the column names, follow the FROM
keyword with a list of the table and view names to be
used to retrieve data
– View: a virtual table that uses the result set of a
saved query
5
- 6. © Cengage Learning 2014
A Simple Query
• When a SQL Server session is established, you
connect to an individual database known as the
database context
– Database context is the default database and will be
used if a database is not specified in a query
• A USE statement can be executed to change the
database context:
USE [Database Name] ;
6
- 7. © Cengage Learning 2014
A Simple Query
• Qualified name: a combination of identifiers that
uniquely defines the location of a database object
– Constructed by using up to four identifiers that
represent the:
• Logical structure and hierarchy of the SQL Server
instance
• Database name
• Database schema
• Database object
• An object that is referenced with a four-part
identifier is known as a fully qualified name
7
- 8. © Cengage Learning 2014
Renaming the Columns Returned in a
Result Set
• The AS keyword can be used to create a column
alias for an individual column
– Necessary when naming a computed column or to
remove ambiguity when merging tables with similar
or same column names
• Syntax:
SELECT [Column Name] AS [Column Alias]
FROM [Table Name] ;
8
- 9. © Cengage Learning 2014
Managing Duplicate Records in a
Result Set
• The SELECT statement implicitly returns all rows
from the table or view
– May include duplicate records
• The use of the keyword DISTINCT removes
duplicates from the result set
SELECT DISTINCT [Column Name]
FROM [Table Name] ;
9
- 10. © Cengage Learning 2014
Limiting the Number of Records
Returned in a Result Set
• The keyword TOP limits the result set to the
number of rows defined by the expression that
follows in parentheses
– Expression can be either an absolute number or a
percentage of the row count
• The TOP keyword is often used in conjunction with
an ordered query:
SELECT TOP (expression) [Column Name]
FROM [Table Name] ;
10
- 11. © Cengage Learning 2014
Adding Computed Columns to the
Result Set
• Computed columns: calculated using arithmetic or
string concatenation operators applied to values in
existing columns
11
Table 5-1 Arithmetic operators
- 12. © Cengage Learning 2014
Adding Computed Columns to the
Result Set
• The syntax to select a computed column using an
arithmetic operator:
SELECT [Column Name1] * [Column Name2] as [Column Alias]
FROM [Table Name] ;
• Columns containing character strings may be
combined using the string concatenation operator
(+)
SELECT [Column Name1] + [Column Name2] as [Column Alias]
FROM [Table Name] ;
12
- 13. © Cengage Learning 2014
Filtering the Records in a Result Set
• The WHERE keyword is used to filter the result set
from a SELECT statement
– Comparison and logical operators are used in the
WHERE clause to specify the filter criteria:
SELECT [Column Name]
FROM [Table Name]
WHERE [Criteria] ;
13
- 14. © Cengage Learning 2014
MCSA Guide to Microsoft SQL Server 2012 14
Table 5-2 Comparison operators
- 15. © Cengage Learning 2014
Filtering the Records in a Result Set
• Logical operators:
– AND - All conditions must be true
– OR - Any condition must be true
– NOT - Reverses the truth of the original condition
– IS NULL - Evaluates a column for the presence of a
null value
– LIKE - Matches a string based on a pattern
– IN - Used to compare a value of a column against
multiple values
– EXISTS - Used to compare a value of a column
against the results of a subquery
15
- 16. © Cengage Learning 2014
Sorting the Records in a Result Set
• The ORDER BY clause is used to sort the result set
– Should be added after the WHERE clause
SELECT [Column Name]
FROM [Table Name]
WHERE [Criteria] ;
ORDER BY [Column Name] [ASC | DESC] ;
– A comma-separated list of column names must be
provided after the ORDER BY keyword
16
- 17. © Cengage Learning 2014
Grouping and Summarizing Records in
a Result Set
• The GROUP BY clause can be used to collect data
across multiple records and group the results by one
or more columns
• The HAVING clause is used instead of the WHERE
clause to filter group data
SELECT [Column Name]
FROM [Table Name]
GROUP BY [Column Name] ;
HAVING [Criteria] ;
17
- 18. © Cengage Learning 2014
Grouping and Summarizing Records in
a Result Set
• Aggregate functions: used to summarize data in a
grouped column or for all records in a table
– Their syntax allows them to accept one or more
arguments that are required to return a result
– Arguments are specified in parentheses
SELECT [Aggregate Function] (Arg1, Arg2, …)
FROM [Table Name] ;
18
- 20. © Cengage Learning 2014
Combining Data Using Joins
• Join: a database operation that can be used to
merge and retrieve data that is stored in more than
one table or view
• Join conditions: specify which columns from each
table should be used as the matching key
Use the ON clause
SELECT t1.[Column Name], t2. [Column Name]
FROM [Table Name 1] t1
INNER JOIN [Table Name 2] t2
ON t1.[Column Name] = t2.[Column Name] ;
20
- 22. © Cengage Learning 2014
Merging Data Using Unions
• The UNION, INTERSECT, and EXCEPT operators
allow the results of multiple SQL statements to be
merged together
• UNION operator: combines the rows from multiple
SQL statements into a single result set
• INTERSECT operator: combines rows that exist in
both result sets
• EXCEPT operator: returns rows from the first query
that do not exist in the second query
22
- 23. © Cengage Learning 2014
Combining Data Using Subqueries
• Subquery: a SQL query embedded within another
SQL query
• In the following example, a subquery is nested in the
SELECT clause, and second subquery is nested in the
WHERE clause:
SELECT
(SELECT [Column Name1] FROM [Table Name1]) as
[Column Alias], [Column Name],
FROM [Table Name2]
WHERE
[Column Name] IN
(SELECT DISTINCT [Column Name] FROM [Table Name3]) ;
23
- 24. © Cengage Learning 2014
Modifying Data Using INSERT,
UPDATE, and DELETE Statements
• A DELETE statement is used to delete rows from a
table:
DELETE
FROM [Table Name]
WHERE [Criteria] ;
• The scope of a DELETE statement is at the row
level
– No columns need to be specified
– Syntax is similar to the SELECT statement
24
- 25. © Cengage Learning 2014
Modifying Data Using INSERT,
UPDATE, and DELETE Statements
• An INSERT statement is used to insert a new row
into a table
– Use the VALUES clause to enter column values:
INSERT INTO [Table Name] (Column1, Column2, Column3)
VALUES (Value1, Value2, Value3)
• A SELECT statement can be used in place of the
VALUES clause to insert multiple rows into a table:
INSERT INTO [Table Name] (Column1, Column2, Column3)
SELECT Value1, Value2, Value3
FROM [Table Name2]
WHERE [Criteria] ;
25
- 26. © Cengage Learning 2014
Modifying Data Using INSERT,
UPDATE, and DELETE Statements
• Key requirements when creating an INSERT
statement:
– Column values in the VALUES or SELECT clause
must match the order and the data types of the
columns specified
– Column values in the VALUES or SELECT clause
must respect any constraints present in the table
– Columns do not have to be individually listed in the
INSERT statement
• If not listed, they are assumed to follow the default
column order in the table…a value must be provided
for each column
26
- 27. © Cengage Learning 2014
Modifying Data Using INSERT,
UPDATE, and DELETE Statements
• AN UPDATE statement is used to modify column
values of an existing row in a table:
UPDATE [Table Name]
SET Column1 = Value1, Column2 = Value2
WHERE [Criteria] ;
27
- 28. © Cengage Learning 2014
Data Definition Language (DDL)
• DDL components are used to define the database
schema
• DDL SQL syntax can be used to create, modify, or
delete database objects and their attributes
28
- 29. © Cengage Learning 2014
Creating a Table or View and Adding
an Index
• The CREATE TABLE statement is used to create
new tables:
CREATE TABLE [Table Name]
([Column Name] [Data Type]) ;
• Data types describe the type of data values that a
column can store
– Main data type categories are number, dates and
times, and strings
29
- 30. © Cengage Learning 2014
Creating a Table or View and Adding
an Index
• Tables need constraints beyond data types to
control data that can be added
• Common constraints:
– NOT NULL - A column-level constraint specifying
that the column may not accept a null value
– PRIMARY KEY - A table-level constraint that
uniquely identifies each record in the table
– FOREIGN KEY - A column-level constraint that
references a field in another table
– UNIQUE - A column-level constraint that enforces a
unique value in the column
30
- 31. © Cengage Learning 2014
Creating a Table or View and Adding
an Index
• Common constraints (cont’d):
– DEFAULT - A constraint that causes the value of a
field to be autopopulated on insertion of a record if
the value is not specified
– CHECK - A constraint that can be used to limit
values of a column before a change is committed to
the database
31
- 32. © Cengage Learning 2014
Creating a Table or View and Adding
an Index
• Indexes can improve performance of queries on a
table
– Can be added to the database using the CREATE
INDEX statement
• For an index on multiple columns, the column
names can be specified in a comma-separated list
inside the parenthesis:
CREATE INDEX [Index Name]
ON [Table Name] ([Column Name]) ;
32
- 33. © Cengage Learning 2014
Modifying a Table or View
• The DROP statement is used to delete objects in a
database:
DROP [Object Name] ;
• The ALTER statement is used to modify or rename
existing views and tables
• To drop a column or constraint:
ALTER [Table Name]
DROP COLUMN [Column Name] | CONSTRAINT
[Constraint Name] ;
33
- 34. © Cengage Learning 2014
Modifying a Table or View
• To alter a column and change the data type:
ALTER [Table Name]
ALTER COLUMN [Column Name] [Data Type] ;
• To add a column or constraint:
ALTER [Table Name]
ADD [Column Name] [Data Type];
ALTER [Table Name]
ADD CONSTRAINT [Name] [ConstraintType] [Criteria];
34
- 35. © Cengage Learning 2014
Data Control Language (DCL)
• This section covers granting and revoking
permissions to database users and using schemas
and roles to manage permissions
– Using the DCL component of SQL
35
- 36. © Cengage Learning 2014
Creating a SQL Server Login
• SQL Server can be configured to use either
Windows authentication, a local SQL Server login
using SQL Server authentication, or both
– Authentication mode is set during the SQL Server
installation
– Can be changed using the properties of SQL Server
instance in Microsoft SQL Server Management
Studio
• A new login can be added using the CREATE
LOGIN statement
36
- 37. © Cengage Learning 2014
Creating a SQL Server Login
• The CREATE LOGIN syntax is slightly different
depending on the authentication mode
• For Windows authentication:
CREATE LOGIN [DomainNameLogin] FROM
WINDOWS ;
• For SQL Server authentication:
CREATE LOGIN [Login Name]
WITH PASSWORD = [Password] ;
37
- 38. © Cengage Learning 2014
Creating a Database User
• A database user must be created and then linked
to a login
– Permissions can then be granted
• Syntax to create a user:
CREATE USER [User Name]
FROM LOGIN [Login Name] ;
38
- 39. © Cengage Learning 2014
Removing a Login or User
• Logins and users can be removed using the DROP
LOGIN and DROP USER statement:
DROP USER [User Name] ;
DROP LOGIN [Login Name] ;
39
- 40. © Cengage Learning 2014
Granting and Removing Permissions
• Permissions can be assigned to a user using the
GRANT statement:
GRANT [Permission Name]
ON [Object Name]
To [User Name] ;
• To enable the user to grant the permission to other
database users, use the WITH GRANT OPTION
GRANT [Permission Name] WITH GRANT OPTION
ON [Object Name]
To [User Name] ;
40
- 41. © Cengage Learning 2014
Granting and Removing Permissions
• Permissions can be removed from a database user
using the REVOKE statement:
REVOKE [Permission Name]
ON [Object Name]
To [User Name] ;
41
- 43. © Cengage Learning 2014
Managing Permissions Using
Schemas and Roles
• A database schema can be created to manage
groups of objects
– Created using the CREATE SCHEMA statement
• The user specified in the AUTHORIZATION clause
is the owner of the schema
CREATE SCHEMA [Schema Name] AUTHORIZATION
[Database User] ;
• Objects can be added to the schema:
CREATE TABLE [Database Name] . [Schema Name] . [Table
Name] ([Column Name] [Data Type]);
43
- 44. © Cengage Learning 2014
Managing Permissions Using
Schemas and Roles
• A database role is an object that can be used to
manage permissions on behalf of database users
– Members of the role inherit the permissions of the
role
• To create a role:
CREATE ROLE [Role Name] ;
• To grant or revoke permissions:
GRANT [Permission Name] ON [Object Name] TO [Role
Name] ;
REVOKE [Permission Name] ON [Object Name] TO [Role
Name] ;
44
- 45. © Cengage Learning 2014
Managing Permissions Using
Schemas and Roles
• A database role can be granted a permission on a
database schema:
GRANT SELECT ON SCHEMA : : [Schema Name] TO
[Role Name] ;
• The ALTER statement adds or removes members:
ALTER ROLE [Role Name]
ADD MEMBER [Database User] ;
ALTER ROLE [Role Name]
DROP MEMBER [Database User] ;
45
- 46. © Cengage Learning 2014
Summary
• SQL is the standard programming language for
managing and retrieving data from a relational
database management system
• SQL is a declarative language that uses a set of
logical expressions to specify what it is trying to
accomplish
• Data manipulation language (DML) provides the
means to query and manipulate data
• Data definition language (DDL) provides the means
to create and manage the schema of logical objects
in a database
46
- 47. © Cengage Learning 2014
Summary
• Data control language (DCL) allows you to configure
the logical security in the database
• The SELECT statement is used to retrieve data and
is the most commonly used statement in SQL
• The WHERE clause is used to filter a result set
• A null value is a column value that does not exist
• Joins can be used to merge and retrieve data that is
stored in more than one table or view
• The UNION, EXCEPT, and INTERSECT operators
allow the results of multiple SQL statements be
merged together
47
- 48. © Cengage Learning 2014
Summary
• Data can also be combined using a subquery
• Rows in a table can be modified using the INSERT,
UPDATE, and DELETE statements
• The CREATE TABLE statement is used to create
new tables in a database
• Database objects can be changed or deleted using
the ALTER and DROP statements
• A permission is a right granted to a database user or
role that enables it to perform an action against an
object in a database
48