SlideShare ist ein Scribd-Unternehmen logo
1 von 48
Downloaden Sie, um offline zu lesen
© Cengage Learning 2014
1
Transac - SQL
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© Cengage Learning 2014
MCSA Guide to Microsoft SQL Server 2012 14
Table 5-2 Comparison operators
© 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
© 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
© 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
© 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
© Cengage Learning 2014
19
Table 5-3 Aggregate functions
© 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
© Cengage Learning 2014
21
Figure 5-10 INNER and OUTER Joins
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© Cengage Learning 2014
42
Table 5-4 Database permission types
© 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
© 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
© 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
© 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
© 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
© 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

Weitere ähnliche Inhalte

Was ist angesagt? (20)

SQL Views
SQL ViewsSQL Views
SQL Views
 
Sql dml & tcl 2
Sql   dml & tcl 2Sql   dml & tcl 2
Sql dml & tcl 2
 
SQL Server Views
SQL Server ViewsSQL Server Views
SQL Server Views
 
Oracle Data Redaction
Oracle Data RedactionOracle Data Redaction
Oracle Data Redaction
 
Assg2 b 19121033-converted
Assg2 b 19121033-convertedAssg2 b 19121033-converted
Assg2 b 19121033-converted
 
View & index in SQL
View & index in SQLView & index in SQL
View & index in SQL
 
Sql intro & ddl 1
Sql intro & ddl 1Sql intro & ddl 1
Sql intro & ddl 1
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
The Database Environment Chapter 8
The Database Environment Chapter 8The Database Environment Chapter 8
The Database Environment Chapter 8
 
Getting Started with MySQL I
Getting Started with MySQL IGetting Started with MySQL I
Getting Started with MySQL I
 
Les10
Les10Les10
Les10
 
Sql database object
Sql database objectSql database object
Sql database object
 
01 basic orders
01   basic orders01   basic orders
01 basic orders
 
Dynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeDynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data Merge
 
SQL- Introduction to PL/SQL
SQL- Introduction to  PL/SQLSQL- Introduction to  PL/SQL
SQL- Introduction to PL/SQL
 
Sql commands
Sql commandsSql commands
Sql commands
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Language
 
Oracle SQL Part 2
Oracle SQL Part 2Oracle SQL Part 2
Oracle SQL Part 2
 

Ähnlich wie Sql2

Ähnlich wie Sql2 (20)

MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
Introduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusIntroduction to SQL, SQL*Plus
Introduction to SQL, SQL*Plus
 
SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data   SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data
 
Access2013 ch10
Access2013 ch10Access2013 ch10
Access2013 ch10
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
SQL
SQLSQL
SQL
 
ms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptxms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptx
 
Database Overview
Database OverviewDatabase Overview
Database Overview
 
Lab1 select statement
Lab1 select statementLab1 select statement
Lab1 select statement
 
Lab
LabLab
Lab
 
2..basic queries.pptx
2..basic queries.pptx2..basic queries.pptx
2..basic queries.pptx
 
UNIT2.ppt
UNIT2.pptUNIT2.ppt
UNIT2.ppt
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
Les01
Les01Les01
Les01
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
 
02 database oprimization - improving sql performance - ent-db
02  database oprimization - improving sql performance - ent-db02  database oprimization - improving sql performance - ent-db
02 database oprimization - improving sql performance - ent-db
 
Chapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfChapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdf
 
Relational Database Language.pptx
Relational Database Language.pptxRelational Database Language.pptx
Relational Database Language.pptx
 
SQL Query
SQL QuerySQL Query
SQL Query
 

Kürzlich hochgeladen

Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxMadhavi Dharankar
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineCeline George
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...Nguyen Thanh Tu Collection
 
An Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPAn Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPCeline George
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Shark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsShark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsArubSultan
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
The Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressThe Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressMaria Paula Aroca
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 
The role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipThe role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipKarl Donert
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptxmary850239
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfChristalin Nelson
 

Kürzlich hochgeladen (20)

Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptx
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command Line
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
 
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
 
An Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPAn Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERP
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Shark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsShark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristics
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
The Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressThe Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian Congress
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
CARNAVAL COM MAGIA E EUFORIA _
CARNAVAL COM MAGIA E EUFORIA            _CARNAVAL COM MAGIA E EUFORIA            _
CARNAVAL COM MAGIA E EUFORIA _
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 
The role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipThe role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenship
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdf
 

Sql2

  • 1. © Cengage Learning 2014 1 Transac - SQL
  • 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
  • 19. © Cengage Learning 2014 19 Table 5-3 Aggregate functions
  • 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
  • 21. © Cengage Learning 2014 21 Figure 5-10 INNER and OUTER Joins
  • 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
  • 42. © Cengage Learning 2014 42 Table 5-4 Database permission types
  • 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