0% found this document useful (0 votes)
112 views57 pages

Chapter 7 - Introduction To Structured Query Language (SQL)

This document introduces structured query language (SQL) and covers the key elements of SQL statements including predicates, operators, functions, variables, expressions, comments, and control of flow. It explains the different types of SQL statements such as data definition language, data manipulation language, transaction control language, and data control language. Finally, it provides details on the clauses and functions of the SELECT statement which is used to retrieve data in SQL queries.

Uploaded by

DaXon Xavi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views57 pages

Chapter 7 - Introduction To Structured Query Language (SQL)

This document introduces structured query language (SQL) and covers the key elements of SQL statements including predicates, operators, functions, variables, expressions, comments, and control of flow. It explains the different types of SQL statements such as data definition language, data manipulation language, transaction control language, and data control language. Finally, it provides details on the clauses and functions of the SELECT statement which is used to retrieve data in SQL queries.

Uploaded by

DaXon Xavi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 57

Chapter 7 -Introduction to Structured Query Language (SQL)

1
Learning Objectives
• After completing this chapter, you will be able to:
• Retrieve specified columns of data from a database
• Join multiple tables in a single SQL query
• Restrict data retrievals to rows that match complex criteria
• Aggregate data across groups of rows
• Create subqueries to preprocess data for inclusion in other queries
• Identify and use a variety of SQL functions for string, numeric, and date
manipulation
• Explain the key principles in crafting a SELECT query

2
SQL Statement Elements

Predicates
Predicates and
and Operators
Operators Batch
Batch Separators
Separators

Functions
Functions Control
Control of
of Flow
Flow

Variables
Variables Comments
Comments

Expressions
Expressions

3
Predicates
Predicates and
and Operators
Operators

Predicates and
Elements: Operators:
IN, BETWEEN, LIKE,
Predicates ISNULL,EXISTS,DISTINCT <COLUMN1> BETWEEN 1 AND 5
<COLUMN1> LIKE “DAL%”
=, >, <, >=, <=, <>, !=, !>, !
Comparison Operators <

Logical Operators AND, OR, NOT

Arithmetic Operators +, -, *, /, %

SELECT
SELECT unitprice,
unitprice, OrderQty,
OrderQty, (unitprice
(unitprice ** OrderQty)
OrderQty) FROM
FROM sales.salesorderdetail;
sales.salesorderdetail;
SELECT
SELECT ** FROM
FROM Customers
Customers WHERE
WHERE City
City == "London"
"London" OR
OR Country
Country == "UK";
"UK";
SELECT
SELECT ** FROM
FROM Products
Products WHERE
WHERE Price
Price >=
>= 30;
30;
SELECT
SELECT ** FROM
FROM Customers
Customers WHERE
WHERE City
City IN
IN ('Paris','London');
('Paris','London');
SELECT
SELECT ** FROM
FROM Products
Products WHERE
WHERE Price
Price BETWEEN
BETWEEN 50
50 AND
AND 60;
60; 4
Comments
Comments

• Marks T-SQL code as a comment:


• For a block, enclose it between /* and */ characters

/*
This is a block
of
of commented
commented code
*/

• For inline text, precede the comments with --

• T-SQL
-- This
This line
-- Editors of
of text
linesuchtextaswill
SSMS
will be
be ignored
will typically color-code comments,
ignored
as shown above
5
Variables
Variables

• Local variables in T-SQL temporarily store a value of a specific data type


• Name begins with single @ sign
• @@ reserved for system functions
• Assigned a data type
• Must be declared and used within the same batch
• In SQL Server 2008 and later, can declare and initialize in the same statement

DECLARE @MyVar int = 30;

6
Functions
Functions

String Functions Date and Time Functions Aggregate Functions

• SUBSTRING • GETDATE • SUM


• LEFT, RIGHT • SYSTDATETIME • MIN
• LEN • GETUTCDATE • MAX
• DATALENGTH • DATEADD • AVG
• REPLACE • DATEDIFF • COUNT
• REPLICATE • YEAR
• UPPER, LOWER • MONTH
• RTRIM, LTRIM • DAY

7
Expressions
Expressions

• Combination of identifiers, values, and operators evaluated to obtain a single result


• Can be used in SELECT statements
• SELECT clause
• WHERE clause
• Can be single constant, single-valued function, or variable
• Can be combined if expressions have same the data type

SELECT
SELECT YEAR(OrderDate) ++ 1 ...

SELECT
SELECT OrderQty
OrderQty * UnitPrice ...

8
Batch
Batch Separators
Separators

• Batches are sets of commands sent to SQL Server as a unit


• Batches determine variable scope, name resolution
• To separate statements into batches, use a separator:
• SQL Server tools use the GO keyword
• They are very useful during to deployment
• Most of them works backend and write error logs in files.

9
Control
Control of
of Flow
Flow

• Allow you to control the flow of execution within code, handle errors,
and maintain transactions
• Used in programmatic code objects
• Stored procedures, triggers, statement blocks

Control of Flow Error Handling Transaction Control

• IF...ELSE •• TRY...CATCH
TRY...CATCH • BEGIN TRANSACTION
• WHILE
• COMMIT TRANSACTION
• BREAK
• ROLLBACK TRANSACTION
• CONTINUE
• BEGIN...END

10
Introduction to SQL
SQL Statements

DDL-Data Definition DML-Data Manipulation TCL-Transactional Control DCL- Data Control


Language Language Language Language

 CREATE  SELECT  COMMIT  GRANT


 ALTER  INSERT  ROLLBACK  REVOKE
 RENAME  UPDATE  SAVEPOINT
 DROP  DELETE
 TRUNCATE

• SQL is relatively easy to learn


• Nonprocedural language with basic command vocabulary set of
less than 100 words
• Differences in SQL dialects are minor
11
DML –Data Manipulation Language DML-Data
Manipulation
Language
Each clause in a SELECT query performs a specific function  SELECT
 INSERT
SELECT: specifies the attributes to be returned by the query  UPDATE
 DELETE
FROM: specifies the table(s) from which the data will be retrieved
WHERE: filters the rows of data based on provided criteria
GROUP BY: groups the rows of data into collections based on
sharing the same values in one or more attributes
HAVING: filters the groups formed in the GROUP BY clause based
on provided criteria
ORDER BY: sorts the final query result rows in ascending or descending
order based on the values of one or more attributes

• SQL commands can be grouped together on a single line


• Complex command sequences are best shown on separate lines,
with space between the SQL command and the command’s
components

Memorize this slide !!!


12
SELECT statement order !!!! DML-Data
(1 of 6)
Manipulation
Language
 SELECT
• Data retrieval is done in SQL with SELECT query  INSERT
 UPDATE
• Elements of a SELECT statement and the order they  DELETE
are evaluated :
1. FROM • The SELECT query specifies the columns to be
retrieved as a column list
2. WHERE Syntax:
SELECT columnlist
3. GROUP BY FROM tablelist;
4. HAVING • The columnlist represents one or more attributes,
separated by commas
5. SELECT • A wildcard character is a symbol that can be used
as a general substitute for other characters or
6. ORDER BY commands
SELECT * FROM Person.Person
SELECT FistName FROM Person.Person
All attributes from Person table
Only FirstName attributes from Person table 13
Examples (2 of 6)

How can I find all person list from HR ?


SELECT * FROM Person.Person ;

R
o
w
s

14
Examples (3 of 6)

How can I find all person names and last names only from HR ?
SELECT FirstName,LastName FROM Person.Person ;

How can I find all person list from HR ?


SELECT FirstName,LastName,MiddleName
FROM Person.Person WHERE
MiddleName=‘Q’ ;

15
Applying the logical order of operations
to writing SELECT statements (4 of 6)
USE
USE AdventureWorks2012;

5 SELECT
SELECT SalesPersonID, YEAR(OrderDate) AS
AS OrderYear
OrderYear
1 FROM
FROM Sales.SalesOrderHeader
2 WHERE
WHERE CustomerID = 29974
3 GROUP
GROUP BY
BY SalesPersonID, YEAR(OrderDate)
YEAR(OrderDate)
4 HAVING
HAVING COUNT(*) > 11
ORDER
ORDER BY
BY SalesPersonID, OrderYear;
OrderYear;
6

1. FROM
2. WHERE
3. GROUP BY
4. HAVING
5. SELECT
6. ORDER BY
16
SQL Data Types
• Data type: specification about the kinds of data that can be stored
in an attribute
• Fundamental types of data
• Character data (alphabetic characters , digits ,some special charters,
strings)
• Numeric data ( numbers as digit)
• Date data ( day ,year )

There are more data type in SQL.


We will explore them in next chapters

17
SQL Wildcard Types
• Wildcards are symbol that can be used as a general
substitute for other characters or commands
Fundamental types
% A substitute for zero or more characters
_ A substitute for a single character
[charlist] Sets and ranges of characters to match
[^charlist] Matches only a character NOT specified within
or the brackets
[!charlist]

18
SELECT Statement with DISTINCT Options (5 of 6)

• Listing unique values


• SQL’s DISTINCT clause produces a list of only those values that are
different from one another
SELECT safetystocklevel SELECT DISTINCT safetystocklevel
FROM FROM Production.Product
Production.Product

SELECT COUNT(DISTINCT safetystocklevel )


FROM Production.Product

19
SELECT Statement with Column Aliases (6 of 6)

• Generally, attribute names in table either short acronym or fallows the


name convention that sets by programmers such as LName , StdID.
When that column(s) retrieved programmer may want to relabeled
output with better ones such as Last Name or Student-ID this relabeling
or renaming know as an alias.alias

SELECT ListPrice ,(ListPrice*1.25) as "MSRP Price"


FROM Production.Product WHERE FinishedGoodsFlag =1 ;

(ListPrice*1.25) new MSRP Price column is also called


computed column there is no MSRP Price column in DB

20
Aggregate Functions ( 1 of 2) Aggregate
Functions
•• SUM
SUM
• Takes a collection of rows and reduces it to a •• MIN
MIN
single row in whole table •• MAX
MAX
•• AVG
AVG
• Aggregate functions are most commonly •• COUNT
COUNT
used in SELECT column list to return an
aggregate values that has been calculated Table1
across a collection of row
• COUNT
SELECT function
COUNT is used
(Name) FROM to tally
Table1 ; the number
of non-null values of and attribute.
SELECT COUNT (fk) FROM Table1 ;

21
Aggregate Functions ( 2 of 2) Aggregate
Functions
• MIN and MAX finds highest and lowest numbers •• SUM
SUM
SELECT max (fk) FROM Table1 ; •• MIN
MIN
•• MAX
MAX
SELECT min (fk) FROM Table1 ; •• AVG
AVG
•• COUNT
COUNT
SELECT min (fk) ,MAX (FK) FROM Table1 ;

Table1

• SUM functions computes the total sum of any specified


numeric attribute
SELECT SUM (fk),using with any
SUM (id) FROMcondition(s)
Table1 ;

• AVG function is computes simple average of any


SELECT AVG(fk)
specified numericFROM Table1 ;
attributes.
22
Any question about SELECT clause?

Do not forget ,order of select statement


Now, we are moving to “FROM” clause

23
FROM Clause Options (1 of 10)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved

Gathering information from different tables requires Join operation


Text book explain Natural Joins as ;

Syntax: SELECT column-list FROM table1 NATURAL JOIN table2

Only some of the DBMS use this syntax ,MS-SQL prefer inner joins for Natural Joins
and don’t support Cross joins at all.

Syntax : SELECT column-list FROM table1


INNER JOIN table2 ON table1.id=table2.id;

• Inner joins return only rows from the tables that match on a common value
• Outer joins return the same matched rows as the inner join, plus unmatched rows
from one table or the other

24
Example

Table1 Table2

25
FROM Clause Options (2 of 10)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved

The INNER JOIN represents an intersection of


two data sets , Table1 and Table2. Its a way of
saying “show me the rows from Table1 that
match up with Table2, and just ignore or skip
all those rows that don’t match.
Inner Join output

26
FROM Clause Options (3 of 10)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved
The INNER JOIN only returns those rows that are
an exact match, and the LEFT OUTER JOIN
returns the rows that are an exact match, plus all
remaining unmatched rows from one LEFT table.

Left Outer Join output


Left Right

27
SELECT * FROM table_a INNER JOIN table_b ON table_a.id=table_b.id;

FROM Clause Options (4 of 10)


SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved
The INNER JOIN only returns those rows that are
an exact match, and the RIGHT OUTER JOIN
returns the rows that are an exact match, plus all
remaining unmatched rows from one RIGHT
table.
Right Outer Join output
Left Right

28
FROM Clause Options (6 of 10)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved
Full outer join returns not only the rows
matching but it also returns all of the rows
which unmatched values from both tables

Full Outer Join output

29
FROM Clause Options (10 of 10)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved

JOIN ON syntax
Express a join when the tables have no common attribute names
Query returns only the rows that meet the indicated join condition
An outer join is needed to
Recursive joins: include any employee who
Recursive query: joins a table to itself is not managed by anyone

SELECT E.lastName AS "Employee",


M.lastName AS "Manager"
FROM Employees E LEFT OUTER JOIN
Employees M
What join we need to use if all managers must
ON E.managerID = M.employeeID
have at least one employee business rule?
ORDER BY E.lastName

Employees M

Employees E
30
Relational Set Operators-Intersect (1 of 3)
• Can be used to combine rows from two queries, returning only the rows that appear
in both sets ( which costumers are in both table)

Fk={Null,1,2,3,5,8}
??

Intersect clause output id={1,2,3,4,5,6,7,8}

Attributes must have union compatible Number VarChar (30) Number Char(20)
31
Relational Set Operators -Union(2 of 3)
• Combines rows from two or more queries without including duplicate rows ( I want
to see all costumer list without duplication)
• UNION ALL
• Used to produce a relation that retains
the duplicate rows
• Used to unite more than just two queries

Fk={Null,1,2,3,5,8}
Union clause output
id={1,2,3,4,5,6,7,8}

32
Relational Set Operators –Except(Minus) (3 of 3)
• Combines rows from two queries and returns only the rows that appear in the first
set but not in the second ( which costumers are in the first table are not found in the
second table)

Fk={Null,1,2,3,5,8}

id={1,2,3,4,5,6,7,8}
Except cause output

33
Where Clause Options (1 of 4)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved
[WHERE: filters the rows of data based on provided criteria]
• WHERE clause is used to add conditional restriction(s) to the SELECT statement that
limit the rows returned by the query
• Syntax:
SELECT columnlist If all rows are required for output
FROM tablelist then WHERE clause is not needed !!
[WHERE conditionlist ]

Numerous condition restriction can be placed on


the selected attributes
IN, BETWEEN, LIKE,
Predicates ISNULL,EXISTS,DISTINCT

Comparison Operators =, >, <, >=, <=, <>, !=, !>, !<

Logical Operators AND, OR, NOT

Arithmetic Operators +, -, *, /, %

34
Where Clause Options (2 of 4)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved Table1
[WHERE: filters the rows of data based on provided criteria]

SELECT * FROM Table2


WHERE FavoriteColor = 'pink' or FavoriteColor ='blue' ;

SELECT * FROM Table2


Table2
WHERE FavoriteColor <> 'pink' and FavoriteColor <>'blue' ;

35
Where Clause Options (3 of 4)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved Table1
[WHERE: filters the rows of data based on provided criteria]

SELECT * FROM Table1


WHERE FK>3 AND FK <=8 ;

SELECT * FROM Table1 WHERE fk IS NULL ;

Table2
SELECT id,name FROM Table1 where fk IS NOT NULL ;

36
Where Clause Options (3 of 4)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved Table1
[WHERE: filters the rows of data based on provided criteria]

SELECT * FROM Table1 WHERE fk BETWEEN 2 AND 5 ;

Table2

• You may use comparison operators on dates


• Date procedures are often more software-specific than other
SQL procedures
• Date format is ‘YYYY-MM-DD’ for instance PurchaseDate = ‘
2018-02-02’

37
Where Clause Options (4 of 4)
SELECT: specifies the attributes to be returned by the query
FROM: specifies the table(s) from which the data will be retrieved Table1
[WHERE: filters the rows of data based on provided criteria]
SELECT * FROM Table1 WHERE Name BETWEEN 'ANNE' AND
'FRED' ;

SELECT * FROM Table2 WHERE FavoriteColor BETWEEN Table2


'InDiGo' AND 'OrAnGe' ;

38
Where clause vs JOINs !!!
SELECT name FROM Table1 as t1 inner join Table2 as t2 on t1.fk=t2.id ;
Table1
SELECT name FROM Table1 ,Table2 where table1.fk=table2.id ;

Output

Table2

39
Other Special Operators “IN” and ‘LIKE”

SELECT name FROM Table1 WHERE fk=1 or fk=5 ;

SELECT name FROM Table1 WHERE FK in (1,5) ; Table1

SELECT name FROM Table1 WHERE NAME LIKE 'A%' ;

SELECT name FROM Table1 WHERE NAME LIKE 'B_TH' ;


GROUP BY Clause Options (1 of 2)

SELECT: specifies the attributes to be returned by the query


FROM: specifies the table(s) from which the data will be retrieved
[WHERE]: filters the rows of data based on provided criteria
[ GROUP BY ]: groups the rows of data into collections based on sharing the same
values in one or more attributes

• Another way to do aggregation within small collection. It is aggregation clause.


• If no aggregate will be returned then GROUP BY clause is not needed
• Syntax:
SELECT columnlist
FROM tablelist
[WHERE conditionlist ]
[GROUP BY columnlist ]

SELECT SUM(OrderQty) AS TotalOrdered, ProductID


FROM Sales.SalesOrderDetail
GROUP BY ProductID;

41
GROUP BY Clause Options (2 of 2)

SELECT COUNT(id) FROM Table1 GROUP BY Country ;

SELECT AVG(fk) FROM Table1 GROUP BY Country ;

42
HAVING BY Clause Options

SELECT: specifies the attributes to be returned by the query


FROM: specifies the table(s) from which the data will be retrieved
[WHERE]: filters the rows of data based on provided criteria
[GROUP BY]: groups the rows of data into collections based on sharing the same values in one or more attributes
[HAVING] : filters the groups formed in the GROUP BY clause based on provided
criteria
• If the GROUP BY clause is not needed than HAVING clause is not needed either
• Operates very much like the WHERE clause in the SELECT statement however HAVING
clause is applied to output of a GROUP BY operation
•HAVING clause is applied to the output of a GROUP BY operation
• Syntax:
SELECT columnlist
FROM tablelist
[WHERE conditionlist ]
[GROUP BY columnlist ]
[HAVING BY conditionlist ]

SELECT COUNT(fk) FROM Table1 GROUP BY Country HAVING


(Country ='USA') ;

SELECT AVG(fk) FROM Table1 GROUP BY Country HAVING


(Country ='CANADA') ;
43
ORDER BY Clause Options

SELECT: specifies the attributes to be returned by the query


FROM: specifies the table(s) from which the data will be retrieved
WHERE: filters the rows of data based on provided criteria
GROUP BY: groups the rows of data into collections based on sharing the same values in one or more attributes
HAVING: filters the groups formed in the GROUP BY clause based on provided criteria
ORDER BY: sorts the final query result rows in ascending or descending order based on
the values of one or more attributes
• ORDER BY clause is especially useful when the listing order
is important
• Syntax:
SELECT columnlist
FROM tablelist
[ORDER BY columnlist [ASC|DESC] ];
• Multilevel ordered sequence is known cascading order sequence and
commonly use
• If ordering column is null we can sort those either fist or last with NULL
FIRST and NULL LAST clause .MS-SQL use null fist during ASC and Nulls last
during DESC
SELECT * FROM Invertory.table
ORDER BY inventory.amount DESC NULL FIRST ;
44
Subqueries (1 of 7)
• A subquery is a SQL query nested inside a larger query we can use them in DML a lot.
• A subquery may occur in :

• A SELECT clause
SELECT column1 = (SELECT column-name FROM table-name WHERE condition),
column-names
FROM table-name WHERE condition

• A FROM clause
SELECT column-names
FROM (SELECT column-names FROM table-name1 WHERE condition)
WHERE condition

**Most common type of subquery uses an inner SELECT subquery on


• A WHERE clause the right side of a WHERE comparison expression
SELECT column-name
FROM table-name
WHERE column-name IN (SELECT column-name FROM table-name2 WHERE condition)

45
Subqueries (2 of 7)
Key characteristics
1. A subquery is a query (SELECT statement) inside another query
2. A subquery is normally expressed inside parentheses
3. The first query in the SQL statement is known as the outer query
4. The query inside the SQL statement is known as the inner query
5. The inner query is executed first
6. The output of an inner query is used as the input for the outer query
7. The entire SQL statement is sometimes referred to as a nested query

SELECT ProductName
1
FROM Product
WHERE Id IN (SELECT ProductId
FROM OrderItem
WHERE Quantity > 100)

46
Subqueries (3 of 7)
Subquery can return one or more values
• One single value (one column and/or one row) include NULL !
• Conditional expression in use ( >,<,=,=>,<= )
• A list of values (one column and multiple rows)
• A virtual table (multicolumn, multi-row set of values)

SELECT ProductName
FROM Product
WHERE Id IN (SELECT ProductId,OrderId
FROM OrderItem
WHERE Quantity > 100)

47
Subqueries (4 of 7)
• IN subqueries –equality operator
• IN operator: used to compare a single attribute to a list of values
• IN subquery: values are not known beforehand, but can be derived
using a query Table1
• Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
SELECT * FROM Table1 WHERE fk in ( SELECT id =1
FROM Table2) ; Table2

SELECT DISTINCT t1.Name, t1.Country,t2.FavoriteColor


FROM Table1 as t1,Table2 as t2
WHERE t1.fk in ( SELECT t2.id FROM Table2 where t1.id=t2.id) ; 48
Subqueries (5 of 7)
• Multirow subquery operators: ALL and ANY –inequality
comparison operators ( < , > != etc.)
Table1
• ANY
• ANY operator compares a single value to a list of values and
select only the rows greater than or less than any value in the
list
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);
Table2
SELECT * FROM Table1 WHERE fk > ANY ( SELECT id
FROM Table2 WHERE id=1) ;

ANY operator compares a single value to a list of values and


select only the rows greater than or less than any value in the list
49
Subqueries (6 of 7)
• ALL
Table1
ALL operator compares a single value with a list
of values returned by the first subquery using a
comparison operator other than equals

SELECT column_name(s)
FROM table_name Table2
WHERE column_name operator ALL
(SELECT column_name FROM table_name
WHERE condition);

SELECT * FROM Table1 WHERE fk <> all


( SELECT id FROM Table2 WHERE
id>6) ; 50
Subqueries (7 of 7)
• Correlated subquery
• Executes once for each row in the outer query
• Inner query is related to the outer query; the inner query references a column of
the outer subquery
• Can also be used with the EXISTS special operator
• Can be used whenever there is a requirement to execute a command based on the
result of another query
• Can be used with uncorrelated subqueries, but it is almost always used with correlated
subqueries

SELECT column_name(s) FROM table_name


WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);

Any return ?

Please Read Tables 7.8 thru 7.13 SQL functions are explained with
examples we will use some of them in lab exercise 51
DML –Data Manipulation Language DML-Data
Manipulation
 INSERT Language
 SELECT
The insert statement is used, obviously, to add new rows to a table.  INSERT
 UPDATE
 DELETE
INSERT INTO <table name>
VALUES (<value 1>, ... <value n>);

• The comma-delimited list of values must match the table structure


exactly in the number of attributes and the data type of each
attribute. Character type values are always enclosed in single
quotes; number values are never in quotes; date values are often
(but not always) in the format 'yyyy-mm-dd' (for example, '2006-
11-30').

• Yes, you will need a separate INSERT statement for every row.
• The subquery can be nested inside a INSERT
INSERT INTO NewNrder
SELECT * FROM Orders
WHERE OldOrders in(2000,5000);
52
DML –Data Manipulation Language DML-Data
Manipulation
 UPDATE Language
 SELECT
 INSERT
The update statement is used to change values that are already in a  UPDATE
table.  DELETE
UPDATE <table name> SET <attribute> = <expression>
WHERE <condition>;

• The update expression can be a constant, any computed value, or


even the result of a SELECT statement that returns a single row and a
single column.
• If the WHERE clause is omitted, then the specified attribute is set to
the same value in every row of the table (which is usually not what
you want to do). You can also set multiple attribute values at the
same time with a comma-delimited list of attribute=expression pairs.
• The subquery can be nested inside a UPDATE
UPDATE neworder
SET ord_date='15-JAN-10'
WHERE ord_amount-advance_amount<
(SELECT MIN(ord_amount) FROM orders);
53
DML –Data Manipulation Language DML-Data
Manipulation
Language
 DELETE  SELECT
The delete statement does just that, for rows in a table.  INSERT
 UPDATE
 DELETE
DELETE FROM <table name>
WHERE <condition>;

• If the WHERE clause is omitted, then every row of the table is


deleted (which again is usually not what you want to do)—and
again, you will not get a “do you really want to do this?”
message.
• The subquery can be nested inside a UPDATE
DELETE FROM neworder
WHERE advance_amount<
(SELECT MAX (advance_amount) FROM orders);

54
Questions ?

55
Summary (1 of 2)
• SQL commands can be divided into two overall categories: data definition
language (DDL) commands and data manipulation language (DML) commands
• The ANSI standard data types are supported by all RDBMS vendors in different
ways
• The basic data types are NUMBER, NUMERIC, INTEGER, CHAR, VARCHAR, and DATE
• The SELECT statement is the main data retrieval command in SQL
• The column list represents one or more column names separated by commas
• Operations that join tables can be classified as inner joins and outer joins
• A natural join returns all rows with matching values in the matching columns
and eliminates duplicate columns
• Joins may use keywords such as USING and ON
• The ORDER BY clause is used to sort the output of a SELECT statement

56
Summary (2 of 2)
• The WHERE clause can be used with the SELECT, UPDATE, and DELETE
statements to restrict the rows affected by the DDL command
• Aggregate functions (COUNT, MIN, MAX, and AVG) are special
functions that perform arithmetic computations over a set of rows
• Subqueries and correlated queries are used when it is necessary to
process data based on other processed data
• Most subqueries are executed in a serial fashion
• SQL functions are used to extract or transform data
• SQL provides relational set operators to combine the output of two
queries to generate a new relation
• Crafting effective and efficient SQL queries requires a great deal of skill

57

You might also like