Tải bản đầy đủ (.ppt) (50 trang)

Structured Query Language

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (237.39 KB, 50 trang )

Structured Query Language
Structured Query Language
Introduction

SQL stands for “Structured Query Language.”
SQL stands for “Structured Query Language.”

SQL is a language used to interact with the database.
SQL is a language used to interact with the database.

SQL is a data access language.
SQL is a data access language.

SQL is based on relational tuple calculus.
SQL is based on relational tuple calculus.

SQL is a standard relational database management
SQL is a standard relational database management
language.
language.

SQL commands consist of English-like statements which
SQL commands consist of English-like statements which
are used to query, insert, update, and delete data.
are used to query, insert, update, and delete data.

SQL is referred to as nonprocedural database language.
SQL is referred to as nonprocedural database language.
Commands in SQL

SQL commands can be classified in to three types:


SQL commands can be classified in to three types:

Data Definition Language commands (DDL)

Data Manipulation Language commands (DML)

Data Control Language commands (DCL)

DDL commands are used to define a database, including
DDL commands are used to define a database, including
creating, altering, and dropping tables and establishing
creating, altering, and dropping tables and establishing
constraints.
constraints.

DML commands are used to maintain and query a database,
DML commands are used to maintain and query a database,
including updating, inserting, modifying, and querying data.
including updating, inserting, modifying, and querying data.

DCL commands are used to control a database including
DCL commands are used to control a database including
administering privileges and saving of data.
administering privileges and saving of data.
Datatypes in SQL

In relational model the data are stored in the form of tables. A
In relational model the data are stored in the form of tables. A
table is composed of rows and columns.When we create a
table is composed of rows and columns.When we create a

table we must specify a datatype for each of its columns.
table we must specify a datatype for each of its columns.

These datatypes define the domain of values that each
These datatypes define the domain of values that each
column can take.
column can take.

Datatypes:
Datatypes:

built-in

user-defined types

Some of the built-in datatypes are string datatype to store
Some of the built-in datatypes are string datatype to store
characters, number datatype to store numerical value, and
characters, number datatype to store numerical value, and
date and time datatype to store when the event happened
date and time datatype to store when the event happened
(history, date of birth, etc.).
(history, date of birth, etc.).
Datatypes in SQL

Char
Char


CHAR datatype to store fixed-length character data.

CHAR datatype to store fixed-length character data.


Maximum size = 2000 bytes
Maximum size = 2000 bytes

Varchar
Varchar
Varchar datatype to store variable-length character data.
Varchar datatype to store variable-length character data.

Number
Number
Number types let you store numeric data (integers, real
Number types let you store numeric data (integers, real
numbers, and floating-point numbers), represent
numbers, and floating-point numbers), represent
quantities, and do calculations.
quantities, and do calculations.
Datatypes in SQL

NChar
NChar
To store multi byte fixed length character data. Its same
To store multi byte fixed length character data. Its same
as Char only difference is it is used to store characters of
as Char only difference is it is used to store characters of
different language like Japenese , chinese etc.
different language like Japenese , chinese etc.
Number of characters it can store depend on language.

Number of characters it can store depend on language.

NVarchar
NVarchar
To store multi byte variable length character data. Its
To store multi byte variable length character data. Its
same as Varchar2 only difference is it is used to store
same as Varchar2 only difference is it is used to store
characters of different language like Japenese , chinese
characters of different language like Japenese , chinese
etc.
etc.
Number of characters it can store depend on language.
Number of characters it can store depend on language.
Datatypes in SQL

Datetime
Datetime
DATETIME datatype to store fixed-length datetimes.
DATETIME datatype to store fixed-length datetimes.
Date range
Date range


from
from
1753-1-1 to 9999-12-31.
1753-1-1 to 9999-12-31.




Smalldatetime
Smalldatetime


Date range from 1900-1-1 to 2079-6-6
Date range from 1900-1-1 to 2079-6-6

Money
Money
represent monetary or currency values.
represent monetary or currency values.
Data Definition Language (DDL)

The di erent structures that are created by DDL are ff
The di erent structures that are created by DDL are ff
Tables, Views, Sequences, Triggers, Indexes, etc.
Tables, Views, Sequences, Triggers, Indexes, etc.

Tables
Tables

It is a relation that is used to store records of
related data. It is a logical structure maintained by
the database manager.

It is made up of columns and rows.

At the intersection of every column and row there
is a speciffic data item called a value.


A base table is created with the CREATE TABLE
statement and is used to hold persistent user data.
Create Table Command

Steps in Table Creation
Steps in Table Creation

Identify datatypes for
Identify datatypes for
attributes
attributes

Identify columns that can
Identify columns that can
and cannot be null
and cannot be null

Identify columns that
Identify columns that
must be unique
must be unique

Identify primary key–
Identify primary key–
foreign key mates
foreign key mates

Determine default values
Determine default values


Identify constraints on
Identify constraints on
columns (domain
columns (domain
specifications)
specifications)

Create the table
Create the table
Sample Database
Sample Database

The data of the sample database can be represented using four
The data of the sample database can be represented using four
tables:
tables:

The department table represents all departments of the
company.

department (dept_no, dept_name, location)

dept_no represents the unique number of each
department.

The employee table represents all employees working
for a company.

employee (emp_no, emp_fname, emp_lname, dept_no)


emp_no represents the unique number of each employee.
Sample Database

Each project of a company is represented in the
Each project of a company is represented in the
project
project
table.
table.

project (project_no, project_name, budget)

project_no represents the unique number of each
project.

The
The
works_on
works_on
table specifies the relationship between
table specifies the relationship between
employees and projects.
employees and projects.

works_on (emp_no, project_no, job, enter_date)

emp_no specifies the employee number and
project_no specifies the number of the project on
which the employee works. The combination of data

values belonging to these two columns is always
unique.
Sample Database
Sample Database

Rows
Rows
in a table do not have any particular order.
in a table do not have any particular order.

Columns
Columns
in a table do not have any particular order.
in a table do not have any particular order.

Every column must have a
Every column must have a
unique
unique
name within a table. On the
name within a table. On the
other hand, columns from different tables may have the same
other hand, columns from different tables may have the same
name.
name.

Every row and column position of a table there is never a set of
Every row and column position of a table there is never a set of
multiple data values.
multiple data values.


For every table, there is at least one column (i.e., a combination
For every table, there is at least one column (i.e., a combination
of columns) with the property that no two rows have the same
of columns) with the property that no two rows have the same
combination of data values for these columns. In the relational
combination of data values for these columns. In the relational
data model, such an identifier is called a
data model, such an identifier is called a
candidate key
candidate key
. If there is
. If there is
more than one
more than one
candidate key
candidate key
within a table, the database
within a table, the database
designer designates one of them as the
designer designates one of them as the
primary key
primary key
of the table.
of the table.

In a table, there are never two identical rows.
In a table, there are never two identical rows.
CREATE TABLE Command


department (dept_no, dept_name, location)
department (dept_no, dept_name, location)

Primary key: dept_no

Candidate key: dept_name

CREATE TABLE
CREATE TABLE
department (
department (
dept_no char(3) primary key,
dept_no char(3) primary key,
dept_name varchar(36) unique not null,
dept_name varchar(36) unique not null,
location varchar(20)
location varchar(20)
)
)
CREATE TABLE Command

employee (emp_no, emp_fname, emp_lname, dept_no)
employee (emp_no, emp_fname, emp_lname, dept_no)

Primary key: emp_no

Foreign key: dept_no

create table employee(
create table employee(

emp_no char(6) primary key ,
emp_fname varchar(10) not null ,
emp_lname varchar(20) not null,
dept_no char(4) references department(dept_no)
on delete set null
on update cascade,
constraint emp_no_ck check (emp_no like '[0-9][0-9][0-9][0-9][0-
9][0-9]')
)
)
DROP TABLE statement

Removes a table definition and all data, indexes,
Removes a table definition and all data, indexes,
constraints, and permission specifications for that table.
constraints, and permission specifications for that table.

Example:
Example:

Drop table Employee

Drop table Department
Table Modification Commands

Modifies a table definition by modifying, adding, or
Modifies a table definition by modifying, adding, or
dropping columns and constraints.
dropping columns and constraints.


Adding a Column to the Table
Adding a Column to the Table
ALTER TABLE table name
ADD column name datatype

Modifying the Column of the Table
Modifying the Column of the Table
ALTER table name
ALTER COLUMN column-name datatype

Deleting the Column of the Table
Deleting the Column of the Table
ALTER table name
DROP COLUMN column name;
Imposition of Constraints

Constraints
Constraints

Null

Not null

Unique

Primary key

References (Foreign key)

Check


Default

On delete cascade

On update cascade

On delete set null
TRUNCATE TABLE command

The TRUNCATE TABLE command removes all the rows
The TRUNCATE TABLE command removes all the rows
from the table. The truncate table also releases the
from the table. The truncate table also releases the
storage space used by the table.
storage space used by the table.

The syntax of TRUNCATE command is:
The syntax of TRUNCATE command is:
TRUNCATE TABLE table name
Creating Tables with Identity Columns

IDENTITY (data_type [ , seed , increment ] ) AS
IDENTITY (data_type [ , seed , increment ] ) AS
column_name
column_name
create table project(
project_no int identity (1,1) primary key,
project_name nvarchar(50) unique not null,
budget money check (budget>0)

)

Inserting into a table does not require explicit customer ID
Inserting into a table does not require explicit customer ID
entry or field list
entry or field list
insert project values('high buildings',5000000000)
SELECT statement

The SQL syntax to see
The SQL syntax to see
all the columns
all the columns
of the table is:
of the table is:
SELECT * FROM table name

Syntax of SELECTION Operation:
Syntax of SELECTION Operation:
SELECT * FROM table name
WHERE condition;

Syntax of PROJECTION Operation
Syntax of PROJECTION Operation
SELECT column name1, column name2, Column name N
FROM table name

Syntax for SELECTION and PROJECTION
Syntax for SELECTION and PROJECTION
SELECT column name1, column name 2. column nameN

FROM table name
WHERE condition;s
Operators

Many types of search operators are possible. They include:
Many types of search operators are possible. They include:

Comparison operators (=, <, <=, <>, and so on)
Comparison operators (=, <, <=, <>, and so on)

String comparisons (LIKE, NOT LIKE)
String comparisons (LIKE, NOT LIKE)

Logical operators (AND, OR, NOT)
Logical operators (AND, OR, NOT)

Ranges (BETWEEN and NOT BETWEEN)
Ranges (BETWEEN and NOT BETWEEN)

Lists of values (IN and NOT IN)
Lists of values (IN and NOT IN)

Unknown Values (IS NULL and IS NOT NULL)
Unknown Values (IS NULL and IS NOT NULL)

Exists in Subquery (EXISTS and NOT EXISTS)
Exists in Subquery (EXISTS and NOT EXISTS)

Use DISTINCT to eliminate duplicates
Use DISTINCT to eliminate duplicates


[ TOP
[ TOP
(
(
expression
expression
)
)
[PERCENT] [ WITH TIES ] ]
[PERCENT] [ WITH TIES ] ]
Some Built-in functions

GETDATE():
GETDATE():
Returns the current system date and time
Returns the current system date and time

DAY ( date )
DAY ( date )
: Returns the day part of its argument
: Returns the day part of its argument

MONTH( date ):
MONTH( date ):
Returns the month part of its argument
Returns the month part of its argument

YEAR( date ):
YEAR( date ):

Returns the year part of its argument
Returns the year part of its argument

DATEPART ( datepart , date ):
DATEPART ( datepart , date ):


Returns an integer that represents the
Returns an integer that represents the
specified datepart of the specified date.
specified datepart of the specified date.



LOWER ( character_expression ):
LOWER ( character_expression ):
Returns a string with the
Returns a string with the
characters converted to lowercase
characters converted to lowercase

UPPER ( character_expression ):
UPPER ( character_expression ):


Returns a character expression
Returns a character expression
with lowercase character data converted to uppercase.
with lowercase character data converted to uppercase.


LEN ( string_expression ):
LEN ( string_expression ):
Returns the length of its argument.
Returns the length of its argument.

CAST ( expression AS data_type [ (length ) ])
CAST ( expression AS data_type [ (length ) ])

CONVERT
CONVERT
(
(
data_type
data_type
[
[
(
(
length
length
)
)
]
]
,
,
expression
expression
[
[

,
,
style
style
]
]
)
)


Wildcard Character

% Any string of zero or more characters
% Any string of zero or more characters

_ Any single character
_ Any single character

[] Any single character within a range
[] Any single character within a range

[^] Any single character not within a range
[^] Any single character not within a range

Example:
Example:
select emp_no, emp_fname, emp_lname
from dbo.employee
where emp_fname like 'An[^a]%'

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×