You are on page 1of 40

Structured Query Language

SQL

Transact-SQL Statements
You can group SQL statements into three categories:
Data Definition Language (DDL) statements,
which enable you to create database objects.
Data Manipulation Language (DML) statements,
which enable you to query or modify data.
Data Control Language (DCL) statements, which
enable you to determine, set, or revoke users per
missions to SQL databases and their object

SELECT

SELECT select_list (
)
[INTO new table] ( select new
table)
FROM table_source ( 1 )
[WHERE search_condition] ( select)
[GROUP BY group_by_expression] (

)
[HAVING search_condition] ()
[ORDER BY order_expression [ASC|DESC]] (
order_exp)


select customerid, companyname, city, country
from customers
Select * from customers
()
select customerid , companyname
[], city as [], country
from customers
select customerid, , companyname
from customers


select orderid, productid, unitprice,
quantity, quantity*unitprice as [total]
from [order details]
total
()

arithmetic operators
+-*/%
The arithmetic operators that perform addition,
subtraction, division, and multiplication can be
used on any numeric column or expression ( int,
smallint, tinyint, decimal, numeric, float, real,
money, or smallmoney).
The modulo operator can only be used on int,
smallint, or tinyint columns or expressions

Math. Function- Ceiling(), Floor(),


The CEILING function returns the smallest
integer greater than or equal to the given
numeric expression.
The FLOOR function returns the largest
integer less than or equal to the given
numeric expression.
For example, given a numeric expression of
12.9273, CEILING returns 13, and FLOOR
returns 12.

Math. Function - Round()


Returns a numeric expression, rounded to the specified
length or precision.
Syntax
ROUND ( numeric_expression , length [ , function ] )

Arguments
numeric_expression
Is an expression of the exact numeric or approximate
numeric data type category, except for the bit data
type.

Math. Function - Round()


length
Is the precision to which numeric_expression is to be
rounded. length must be tinyint, smallint, or int. When
length is a positive number, numeric_expression is
rounded to the number of decimal places specified by lengt
h. When length is a negative number, numeric_expression
is rounded on the left side of the decimal point, as
specified by length.
function
Is the type of operation to perform. function must be
tinyint, smallint, or int. When function is omitted or has a
value of 0 (default), numeric_expression is rounded. When
a value other than 0 is specified, numeric_expression is
truncated.

String function : str


Returns character data converted from numeric data.
Syntax
STR ( float_expression [ , length [ , decimal ] ] )
Arguments
float_expression
Is an expression of approximate numeric (float) data type with a
decimal point. Do not use a function or subquery as the
float_expression in the STR function.

length
Is the total length, including decimal point, sign, digits, and
spaces. The default is 10.

decimal
Is the number of places to the right of the decimal point

String function :

Len()
Left()/Right()
LTrim()/RTrim()
SubString()
Lower()/Upper()

Date function:
GetDate() // Default
datetime
DatePart()
DateName()
Day() / Month() / Year()
DateAdd()
DateDiff()

exercise SQL
1. select *,quantity*unitprice as total from "order
details
2. 1) total (
)
3. 1) total (
)
4. 1) total (
)
( )

Filtering Rows with WHERE and HAVING


The WHERE and HAVING clauses in a SELECT statement
control the rows from the source tables that are used to build
the result set.
WHERE and HAVING are filters.
They specify a series of search conditions, and only those
rows that meet the terms of the search conditions are used to
build the result set
The HAVING clause is typically used in conjunction with
the GROUP BY clause, although it can be specified without
GROUP BY. The HAVING clause specifies further filters
that are applied after the WHERE clause filters
Ex.
SELECT CustomerID, CompanyName
FROM Customers WHERE Region = 'WA'

search conditions
Comparison Search Conditions
>, <, >=, <=, <>,!=,!>, !< ; WHERE [not] Col >
Range Search Conditions
WHERE Col [not] Between and
List Search Conditions
WHERE Col [not] in (,,)
Pattern Matching in Search Conditions
WHERE Col [not] Like ( Wildcard % _ [] [^])
NULL Comparison Search Conditions
WHERE Col is [not] null
(Col = column expression)


select productname, unitprice, unitsinstock
from products
where unitsinstock >=100
select productname,unitprice,unitsinstock
from products
where unitsinstock between 100 and 200


select customerid,city,country from customers
where country = 'usa' or country = 'uk
-- where country in('usa,'uk)
Select customerid,companyname from customers
where companyname like %De%
--where companyname like _[^aeiou]%
select customerid,region from customers
where region is not null

Aggregate Function
Aggregate functions (such as SUM, AVG,
COUNT, MAX, and MIN) generate summary valu
es in query result sets.
An aggregate function (with the exception of
COUNT(*)) processes all the selected values in a s
ingle column to produce a single result value.
Aggregate functions can be applied to all rows in a
table, to a subset of the table specified by a
WHERE clause, or to one or more groups of rows
in the table.


select sum(unitprice)/ count(unitprice) as
"AVG1", avg(unitprice) as "AVG2" from
products
select count(*) from customers
where country ='usa
select sum(unitprice*quantity)
from order details where orderid ='10248'

GROUP BY clause
The GROUP BY clause is used to produce
aggregate values for each row in the result set.
When used without a GROUP BY clause,
aggregate functions report only one aggregate
value for a SELECT statement.
The GROUP BY keywords are followed by a list
of columns, known as the grouping columns. The
GROUP BY clause restricts the rows of the result
set; there is only one row for each distinct value in
the grouping column or columns. Each result set
row contains summary data related to the specific
value in its grouping columns.


select orderid,sum(unitprice*quantity)
from "order details"group by orderid
select country,city,count(*) from customers
group by country,city
[order by 1,2]
select country,city,count(*)as test from customers
where city like 'C%
group by country,city
having country = 'uk'
order by 1,2

1.
2.
3.

4.

5.

1996

Exercise SQL

. .
order
order , order ()



5. order
6. 20
1.
2.
3.
4.

ORDER BY [ASC|DESC]
Select

ASC[ending] [DESCending]
Select
From
[where]
[group by]
[having ]
[order by [asc|desc]

(TOP N
[PERCENT])
DISTINCT

COMPUTE Aggregate Function


1 ()
ex. Compute Sum(quantity)
COMPUTE BY Aggregate Function
ex. Compute Sum(quantity) by ColA, ColB,
ColA, ColB,

INSERT
INSERT [INTO] <table_or_view_name>
[(<column_name>,...)]
VALUES (<literal> | <expression> | NULL |
DEFAULT,...)

Ex.
-- insert all column
Insert std
values('004','BBB,null)
-- insert some column
Insert std(std_id,std_name)
values('004','BBB')

INSERT: excercise
STD
001, AAA, null
002, CCC, null
003, CCC, null
SUBJECT
C01, Cal 1, null
C02, Cal 2, default
C03, Cal 3, default
REGIS
001,C01,null
001,C02,null
002,C01,null
002,C02,null

UPDATE
UPDATE <table_or_view_name>
SET {<column_name> =
<literal> | <expression> |
(<single_row_select_statement>) | NULL |
DEFAULT,...}
[WHERE <condition>]

Ex.
Update std
set std_name='BBB', tell='357222
where std_id='004
Update customers
set city = Bangkok
where country=Thailand

Update : exercise
cal 1 comp prog
. 2 BBB

DELETE
DELETE [FROM] <table_or_view_name>
WHERE <condition>
Ex.
delete std
where std_id ='001
delete customers
where country in (uk,usa)



Inner join (including self join)
Outer join (Left, Right, Full)
Cross join

Inner join
2

2 match

select companyname, orderid, orderdate


from customers c inner join orders o
on c.cust_id = o.cust_id

Outer join (Left join, Right join)


2

(
)
select cust_name, o.order_num, order_date
from customers c left|right|full join orders o
on c.cust_id = o.cust_id

Cross join

Cartesian Product

select cust_name, o.order_num, order_date
from customers c cross join orders o
Relational Database

Exercise:
1. .
.
2. .
(Left join Right join)
3. .
4. .
5. .
6. .

Where (Sql server


Syntax)
Select cust_name,o.order_num,order_date
from customers c , orders o
where c.cust_id = o.cust_id
select cust_name,o.order_num,order_date
from customers c , orders o
where c.cust_id *= o.cust_id
select cust_name,o.order_num,order_date
from customers c , orders o
where c.cust_id =* o.cust_id

Join : exercise SQL Server syntax


1. .
.
2. .
(Left join Right join)
3. .
4. .
5. .
6. .


$
$

You might also like