SQL Basics
<Trainer-Name>
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Agenda
Ms SQL Server Overview
SQL Data Types
SQL Overview
Data Definition Language (DDL)
Data Manipulation Language (DML)
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Ms SQL Server Overview
MS SQL Server is a database server
Product of Microsoft
Enables user to write queries and other SQL
statements and execute them
Query Analyzer: one of the Ms SQL Server that:
Allows us to write queries and SQL statements
Checks syntax of the SQL statement written
Executes the statements
Store and reload statements
Save the results in file
View reports (either as grid or as a text)
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
SQL Data Types
Integer : Stores whole number
Float : Stores real numbers
Text : Stores characters
Decimal : Stores real numbers
Money : Stores monetary data. Supports 4 places
after decimal
Date : Stores date and time
Binary : Stores images and other large objects
Miscellaneous : Different types special to SQL Server.
(Refer to notes for more info)
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
SQL Overview
SQL (Structured Query Language) is the standard for
relational database management systems (RDBMS)
SQL-92 and SQL-99 Standards – Purpose:
Specify syntax/semantics for data definition and
manipulation
Define data structures
Enable portability
Specify minimal (level 1) and complete (level 2) standards
Allow for later growth/enhancement to standard
What Can SQL do?
Retrieve, insert, update, and delete database records
Create new or update database structures: table, view,
stored procedures, etc.
Grant access permission to database objects: tables, stored
procedures, views, etc.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 5 04e-BM/NS/HDCV/FSOFT v2/4
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 6 04e-BM/NS/HDCV/FSOFT v2/4
SQL Overview
SQL Environment
Schema
The structure that contains descriptions of objects
created by a user (base tables, views, constraints)
Data Definition Language (DDL)
Commands that define a database, including creating,
altering, and dropping tables and establishing
constraints
Data Manipulation Language (DML)
Commands that maintain and query a database
Data Control Language (DCL)
Commands that control a database, including
administering privileges and committing data
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 7 04e-BM/NS/HDCV/FSOFT v2/4
SQL Overview
SQL Database Objects
A SQL Server database has lot of objects like
Tables
Views
Stored Procedures
Functions
Rules
Defaults
Cursors
Triggers
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Table management
Create table tablename
(
col1 data type,
col2 data type
);
- Creates a table with two columns
Drop table tablename;
- Drops the table structure
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Table Constraints
Table Constraints: Constraints are used to
limit the type of data that can go into a table.
We will focus on the following constraints:
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Table Constraints
CHECK constraint: used to specify constraint
conditions to data. Whenever data changed
(INSERT, UPDATE), these constraints are used
to verify regular data.
Syntax:
[CONSTRAINT tên_ràng_buộc]
CHECK (điều_kiện)
Sample:
ALTER TABLE [dbo].[Products] ADD
CONSTRAINT [CK_Products_No_Nissan] CHECK
([Productname] <> 'nissan sentra')
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Table Primary-Key Constraint
PRIMARY constraint: used to specify
primary key of table.
Syntax:
[CONSTRAINT tên_ràng_buộc]
PRIMARY KEY [(danh_sách_cột)]
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Table Constraint Scope
•Column Level
CREATE TABLE [dbo].[Customers] (
[CustomerID] [int] IDENTITY (1, 1) NOT NULL PRIMARY KEY ,
[CustomerEmail] [varchar] (30) NULL ,
[CustomerState] [varchar] (5) NULL
) ON [PRIMARY]
GO
•Table Level
ALTER TABLE [dbo].[Products] ADD
CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED
(
[ProductID],
[ProductName]
) ON [PRIMARY]
GO
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Table Unique Constraint
UNIQUE constraint: used to define
candidate keys for the table.
Syntax:
[CONSTRAINT tên_ràng_buộc]
UNIQUE [(danh_sách_cột)]
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Table Foreign-Key Constraint
FOREIGN constraint: used to define
relationships between tables in the database.
Syntax:
[CONSTRAINT tên_ràng_buộc]
FOREIGN KEY [(danh_sách_cột)]
REFERENCES
tên_bảng_tham_chiếu(danh_sách_cột_tham_chiếu)
[ON DELETE CASCADE | NO ACTION | SET NULL | SET
DEFAULT]
[ON UPDATE CASCADE | NO ACTION | SET NULL | SET
DEFAULT]
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Default Constraint
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Sequences
This creates an auto increment for a
column
If a table has a column with sequence or
auto increment, the user need not insert
data explicitly for the column
Sequence is implemented using the
concept of Identity
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Identity
Identity has
A seed
An increment
Seed is the initial value
Increment is the value by which we need
to skip to fetch the nextvalue
Identity(1,2) will generate sequence
numbers 1,3,5,7…
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Identity Sample
Create table table1
(
Id integer identity(1,1),
Name varchar(10)
)
It is enough if we insert like this:
Insert into table1(name) values(‘Ram’);
Ram will automatically assigned value 1 for id
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Truncate statement
Truncate table tablename
Removes all rows in a table
Resets the table.
Truncate does the following, where as
delete statement does not
Releases the memory used
Resets the identity value
Does not invoke delete trigger
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Alter a Table
Used to modify table structure
Add new column
Change data type of existing column
Delete a column
Add or remove constraints like foreign key,
primary key
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Table Indexes
Indexes make search and retrieve fast in a
database
This is for optimizing the select statement
Types of index
Unique
Non unique
Clustered
Non clustered
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Create an Index
Create index indexname on
tablename(columnname)
This creates a non clustered index on a table
Create unique clustered index index_name on
Student(sname);
This creates a unique and clustered index on the
Column Sname.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Views Overview
Views are logical tables
They are pre compiled objects
We can select few columns or rows from a
table and put the data set in a view and
can use view in the same way as we use
tables
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Definition Language
Views Definition & Manipulation
Create views:
Create view viewname as select stmt
Create view view_emp as select empid,
empname from employee;
Select from views:
Select * from viewname
Select empid,empname view_emp;
Drop views:
Drop view viewname
Drop view view_emp;
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
Insert statements 1/2
Inserting data to all columns
Insert into tablename(col1,col2) values(v1,v2)
Insert into tablename values(v1,v2)
Inserting data to selected columns
Insert into tablename(col1) values (v1)
Insert into tablename(col2) values (v2)
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
Insert statements 2/2
Examples
Single-row insert
INSERT INTO Sinhvien VALUES(‘SV3’,’SUP3’,’BLORE’,10)
Inserting one row, many columns at a time
INSERT INTO Sinhvien (MaSV, Hoten) VALUES (‘SV3’, ‘Smith’);
Inserting many rows, all/some columns at a time.
INSERT INTO luusinhvien
SELECT hodem,ten,ngaysinh
FROM sinhvien
WHERE noisinh like ‘%Huế%’
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
Update statement 1/2
Update table tablename
Set colname=value
- This updates all rows with colname set to value
Update table tablename
Set colname=value
Where <<condition>>
- This updates selected rows with colname as
value only if the row satisfies the condition
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
Update statement 2/2
Examples
UPDATE S SET CITY = ‘KANPUR’ WHERE SNO=‘S1’
UPDATE EMP SET SAL = 1.10 * SAL
UPDATE nhatkybanhang
SET thanhtien = soluong*gia
FROM mathang
WHERE mathang.mahang
=(SELECT mathang.mahang
FROM mathang
WHERE mathang.mahang
= nhatkybanhang.mahang)
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
Delete statements
Delete from table1;
Deletes all rows in table1
Delete from table1 where <<condition>>
Deletes few rows from table1 if they satisfy the
condition
Exp:
DELETE FROM SP WHERE PNO= ‘P1’
DELETE FROM SP
DELETE FROM lop
WHERE malop NOT IN (SELECT DISTINCT malop
FROM sinhvien)
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
Select Statements 1/4
To execute a statement in MS SQL, Select the statement
and Click on the Execute button in the query analyser or
press F5
This is used to retrive records from a table
Syntax:
SELECT [ALL/DISTINCT] <Column name1>, <Column
name2>, …
FROM <Table name>
[WHERE <Search condition>]
[GROUP BY grouping columns]
[HAVING search condition]
[ORDER BY sort specification]
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
Select Statements 2/4
Eg. Select * from table1;
This will fetch all rows and all columns from table1
Eg. Select col1,col2 from table1
This will fetch col1 and col2 from table1 for all rows
Eg. Select * from table1 where <<condn>>
This will fetch all rows from table1 that satisfies a
condition
Eg. Select col1,col2 from table1 where <<condn>>
This will fetch col1 and col2 of rows from table1 that
satisfies a condition
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
Select Statements 3/4
The SELECT DISTINCT / TOP statements
DISTINCT: list only the different (distinct) values in a table.
TOP: specify the number of records to return.
Syntax:
SELECT TOP number|percent column_name(s)
FROM table_name
The SELECT INTO statement selects data from one
table and inserts it into a different table.
Syntax:
SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_tablename
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
Select Statements 4/4
SQL Alias syntax:
For table:
SELECT column_name(s)
FROM table_name AS alias_name
For column (s):
SELECT column_name AS alias_name
FROM table_name
Using constant & Expression
SELECT tenmonhoc,'Số tiết: ',sodvht*15 AS sotiet
FROM monhoc
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
SQL Operators
Arithmetic : +, -, *, /, %
Assignment : =
Comparison : <, >, <=, >= <>, =, !=, !<, !>
Logical : AND, OR, NOT, IN (set), LIKE, BETWEEN…
AND …, ANY, ALL, EXISTS, SOME, IS NULL
String : Concatenation (+)
Unary : -, +, ~
Bitwise: &, |, ^
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
Select Options
Aggregate functions
Sum(col1): sum of data in the column col1
Max(col1): data with maximum value in col1
Min(col1): data with minimum value in col1
Avg(col1): Average of data in col1
Count(col1): Number of not null records in table
Grouping – Group by col1 : Groups data by col1
Ordering – Order by col1 : Orders the result in
ascending order (default order) of col1
Filtering – Where <<condn>> and Having
<<condn>>
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
GROUP BY & HAVING
The GROUP BY statement is used in conjunction with
the aggregate functions to group the result-set by one or
more columns.
Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
The HAVING statement is used to specify condition on
group; Example:
SELECT SNO , COUNT(*) FROM SP
GROUP BY SNO
HAVING COUNT(*)>=2
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
String Functions 1/2
Substring(string,start,length) – Will fetch
characters starting at a specific index extending
to length specified.
Left(string,length) – Fetches number of
characters specified by length from left of the
string
Right(string,length) – Fetches number of
characters specified by length from right of the
string
Len(string) – Returns the length of a string
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
String Functions 2/2
Ltrim(string) – Removes leading spaces in
a string
Rtrim(string) – Removes trailing spaces in
a string
Lower(string) – Converts the characters in
a string to lower case
Upper(string) – Converts the characters in
a string to upper case
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
Numeric Functions 1/2
ABS(Number) – Fetches the modulo value
(Positive value) of a number
CEILING(Number) – Fetches the closest
integer greater than the number
FLOOR(Number) – Fetches the closest
integer smaller than the number
EXP(Number) – Fetches the exponent of a
number
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Data Manipulation Language
Numeric Functions 2/2
POWER(x,y) – Fetches x raised to the
power of y
LOG(Number) – Fetches the natural
logarithmic value of the number
LOG10(Number) – Fetches log to the base
10 of a number
SQRT(Number) – Fetches the square root
of a number
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4
Q&A
Q&A
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4