sql queries part1
TRANSCRIPT
-
8/19/2019 SQL Queries Part1
1/42
SQL Tutorial
SQL is a standard language for accessing databases.
Our SQL tutorial will teach you how to use SQL to access and manipulatedata in:
MySQL, SQL Server, ccess, Oracle, Sybase, !"#, and other database
systems.
SQL is a standard language for accessing and manipulating databases.
$ntroduction to SQL
SQL is a standard language for accessing and manipulating databases.
%hat is SQL&
• SQL stands for Structured Query Language
• SQL lets you access and manipulate databases
• SQL is an 'S$ (merican 'ational Standards $nstitute) standard
%hat *an SQL do&
• SQL can e+ecute ueries against a database
• SQL can retrieve data from a database
• SQL can insert records in a database
• SQL can update records in a database
• SQL can delete records from a database
• SQL can create new databases
• SQL can create new tables in a database
-
8/19/2019 SQL Queries Part1
2/42
• SQL can create stored procedures in a database
• SQL can create views in a database
• SQL can set permissions on tables, procedures, and views
SQL is a Standard - "T....
lthough SQL is an 'S$ (merican 'ational Standards $nstitute) standard, there are many
different versions of the SQL language.
/owever, to be compliant with the 'S$ standard, they all support at least the ma0or commands
(such as S1L1*T, 2!T1, !1L1T1, $'S13T, %/131) in a similar manner.
Note: Most of the SQL database programs also have their own proprietary e+tensions in addition
to the SQL standard4
sing SQL in 5our %eb Site
To build a web site that shows some data from a database, you will need the following:
• n 3!"MS database program (i.e. MS ccess, SQL Server, MySQL)
• server-side scripting language, li6e 2/2 or S2
• SQL
• /TML 7 *SS
3!"MS
3!"MS stands for 3elational !atabase Management System.
3!"MS is the basis for SQL, and for all modern database systems li6e MS SQL Server, $"M !"#,
Oracle, MySQL, and Microsoft ccess.
The data in 3!"MS is stored in database ob0ects called tables.
table is a collection of related data entries and it consists of columns and rows.
SQL Synta+
!atabase Tables
database most often contains one or more tables. 1ach table is identified by a name (e.g.
8*ustomers8 or 8Orders8). Tables contain records (rows) with data.
-
8/19/2019 SQL Queries Part1
3/42
"elow is an e+ample of a table called 82ersons8:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
4/42
• SELECT - e+tracts data from a database
• UPDATE - updates data in a database
• DELETE - deletes data from a database
• INSERT INTO - inserts new data into a database
The !!L part of SQL permits database tables to be created or deleted. $t also define inde+es
(6eys), specify lin6s between tables, and impose constraints between tables. The most important
!!L statements in SQL are:
• CREATE DATABASE - creates a new database
• ALTER DATABASE - modifies a database
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table
• CREATE INDEX - creates an inde+ (search 6ey)
• DROP INDEX - deletes an inde+
SQL S1L1*T Statement
This chapter will e+plain the S1L1*T and the S1L1*T ? statements.
The SQL S1L1*T Statement
The S1L1*T statement is used to select data from a database.
The result is stored in a result table, called the result-set.
SQL S1L1*T Synta+
SELECT column_name(s)
FROM table_name
and
SELECT * FROM table_name
Note: SQL is not case sensitive. S1L1*T is the same as select.
-
8/19/2019 SQL Queries Part1
5/42
n SQL S1L1*T 1+ample
The 82ersons8 table:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
; 2ettersen irst'ame8 from the
table above.
%e use the following S1L1*T statement:
SELECT LastName,FirstName FROM Persons
The result-set will loo6 li6e this:
LastName FirstName
/ansen Ola
Svendson Tove
2ettersen
-
8/19/2019 SQL Queries Part1
6/42
; 2ettersen
-
8/19/2019 SQL Queries Part1
7/42
; 2ettersen
-
8/19/2019 SQL Queries Part1
8/42
'ow we want to select only the persons living in the city 8Sandnes8 from the table above.
%e use the following S1L1*T statement:
SELECT * FROM Persons
"#ERE Cit!&'Sannes'
The result-set will loo6 li6e this:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
Quotes round Te+t >ields
SQL uses single uotes around te+t values (most database systems will also accept double
uotes).
lthough, numeric values should not be enclosed in uotes.
>or te+t values:
Tis is correct
SELECT * FROM Persons "#ERE FirstName&'To%e'
Tis is +ron
SELECT * FROM Persons "#ERE FirstName&To%e
>or numeric values:
Tis is correct
SELECT * FROM Persons "#ERE -ear&./01
Tis is +ron
SELECT * FROM Persons "#ERE -ear&'./01'
-
8/19/2019 SQL Queries Part1
9/42
Operators llowed in the %/131 *lause
%ith the %/131 clause, the following operators can be used:
Operator Descriptio
A 1ual
BC 'ot eual
C @reater than
B Less than
CA @reater than or eual
BA Less than or eual
"1T%11' "etween an inclusive range
L$
-
8/19/2019 SQL Queries Part1
10/42
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
11/42
'ow we want to select only the persons with the last name eual to 8Svendson8 '! the first
name eual to 8Tove8 O3 to 8Ola8:
%e use the following S1L1*T statement:
SELECT * FROM Persons "#ERELastName&'S%enson'
2ND (FirstName&'To%e' OR FirstName&'Ola')
The result-set will loo6 li6e this:
P_Id LastName FirstName Address City
# Svendson Tove "orgvn #; Sandnes
SQL O3!13 "5
-
8/19/2019 SQL Queries Part1
12/42
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
13/42
9 /ansen Ola Timoteivn 9 Sandnes
SQL $'S13T $'TO Statement
The $'S13T $'TO statement is used to insert new records in a table.
The $'S13T $'TO Statement
The $'S13T $'TO statement is used to insert a new row in a table.
SQL $'S13T $'TO Synta+
$t is possible to write the $'S13T $'TO statement in two forms.
The first form doesnGt specify the column names where the data will be inserted, only their values:
NSERT NTO table_name
52L6ES (%alue., %alue7, %alue8,999)
The second form specifies both the column names and the values to be inserted:
NSERT NTO table_name (column., column7, column8,999)
52L6ES (%alue., %alue7, %alue8,999)
SQL $'S13T $'TO 1+ample
%e have the following 82ersons8 table:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
14/42
NSERT NTO Persons
52L6ES (:,'Nilsen', ';oan', '3a
-
8/19/2019 SQL Queries Part1
15/42
The 2!T1 Statement
The 2!T1 statement is used to update e+isting records in a table.
SQL 2!T1 Synta+
6PD2TE table_name
SET column.&%alue, column7&%alue7,999
"#ERE some_column&some_%alue
Note: 'otice the %/131 clause in the 2!T1 synta+. The %/131 clause specifies which record
or records that should be updated. $f you omit the %/131 clause, all records will be updated4
SQL 2!T1 1+ampleThe 82ersons8 table:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
16/42
I T0essem Ha6ob 'issestien JK Sandnes
SQL 2!T1 %arning
"e careful when updating records. $f we had omitted the %/131 clause in the e+ample above, li6e
this:
6PD2TE Persons
SET 2ress&'Nissestien 0>', Cit!&'Sannes'
The 82ersons8 table would have loo6ed li6e this:
P_Id LastName FirstName Address City
9 /ansen Ola 'issestien JK Sandnes
# Svendson Tove 'issestien JK Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
17/42
SQL !1L1T1 1+ample
The 82ersons8 table:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
18/42
SQL TO2 *lause
The TO2 *lause
The TO2 clause is used to specify the number of records to return.
The TO2 clause can be very useful on large tables with thousands of records. 3eturning a large
number of records can impact on performance.
Note: 'ot all database systems support the TO2 clause.
SQL Server Synta+
SELECT TOP number4$ercent column_name(s)
FROM table_name
SQL S1L1*T TO2 1uivalent in MySQL and Oracle
MySQL Synta+
SELECT column_name(s)
FROM table_name
LMT number
1+ample
SELECT *
FROM Persons
LMT 1
Oracle Synta+
SELECT column_name(s)
FROM table_name
"#ERE RO"N6M ?& number
1+ample
SELECT *
FROM Persons
"#ERE RO"N6M ?&1
-
8/19/2019 SQL Queries Part1
19/42
SQL TO2 1+ample
The 82ersons8 table:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
20/42
The result-set will loo6 li6e this:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
SQL L$
-
8/19/2019 SQL Queries Part1
21/42
"#ERE Cit! LAE 'sB'
The 88 sign can be used to define wildcards (missing letters in the pattern) both before and after
the pattern.
The result-set will loo6 li6e this:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
22/42
The result-set will loo6 li6e this:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
SQL %ildcards
SQL wildcards can be used when searching for data in a database.
SQL %ildcards
SQL wildcards can substitute for one or more characters when searching for data in a database.
SQL wildcards must be used with the SQL L$
-
8/19/2019 SQL Queries Part1
23/42
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
24/42
SELECT * FROM Persons
"#ERE FirstName LAE '_la'
The result-set will loo6 li6e this:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
'e+t, we want to select the persons with a last name that starts with 8S8, followed by any
character, followed by 8end8, followed by any character, followed by 8on8 from the 82ersons8 table.
%e use the following S1L1*T statement:
SELECT * FROM Persons
"#ERE LastName LAE 'S_en_on'
The result-set will loo6 li6e this:
P_Id LastName FirstName Address City
# Svendson Tove "orgvn #; Sandnes
sing the Ncharlist %ildcard
'ow we want to select the persons with a last name that starts with 8b8 or 8s8 or 8p8 from the
82ersons8 table.
%e use the following S1L1*T statement:
SELECT * FROM Persons
"#ERE LastName LAE 'bs$B'
The result-set will loo6 li6e this:
P_Id LastName FirstName Address City
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
25/42
"#ERE LastName LAE 'bs$B'
The result-set will loo6 li6e this:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
SQL $' Operator
The $' Operator
The $' operator allows you to specify multiple values in a %/131 clause.
SQL $' Synta+
SELECT column_name(s)
FROM table_name
"#ERE column_name N (%alue.,%alue7,999)
$' Operator 1+ample
The 82ersons8 table:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
26/42
9 /ansen Ola Timoteivn 9 Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
27/42
The result-set will loo6 li6e this:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
Note: The "1T%11' operator is treated differently in different databases4
$n some databases, persons with the Last'ame of 8/ansen8 or 82ettersen8 will not be listed,
because the "1T%11' operator only selects fields that are between and e+cluding the test values.
$n other databases, persons with the Last'ame of 8/ansen8 or 82ettersen8 will be listed, because
the "1T%11' operator selects fields that are between and including the test values.
nd in other databases, persons with the Last'ame of 8/ansen8 will be listed, but 82ettersen8 will
not be listed (li6e the e+ample above), because the "1T%11' operator selects fields between the
test values, including the first test value and e+cluding the last test value.
Therefore: *hec6 how your database treats the "1T%11' operator.
1+ample #
To display the persons outside the range in the previous e+ample, use 'OT "1T%11':
SELECT * FROM Persons
"#ERE LastName
NOT 3ET"EEN '#ansen' 2ND 'Pettersen'
The result-set will loo6 li6e this:
P_Id LastName FirstName Address City
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
28/42
SQL lias
5ou can give a table or a column another name by using an alias. This can be a good thing to do if
you have very long or comple+ table names or column names.
n alias name could be anything, but usually it is short.
SQL lias Synta+ for Tables
SELECT column_name(s)
FROM table_name
2S alias_name
SQL lias Synta+ for *olumns
SELECT column_name 2S alias_name
FROM table_name
lias 1+ample
ssume we have a table called 82ersons8 and another table called 82roduct=Orders8. %e will give
the table aliases of 8p8 and 8po8 respectively.
'ow we want to list all the orders that 8Ola /ansen8 is responsible for.
%e use the following S1L1*T statement:
SELECT $o9OrerD, $9LastName, $9FirstName
FROM Persons 2S $,
Prouct_Orers 2S $o
"#ERE $9LastName&'#ansen' 2ND $9FirstName&'Ola'
The same S1L1*T statement without aliases:
SELECT Prouct_Orers9OrerD, Persons9LastName, Persons9FirstName
FROM Persons,
Prouct_Orers
"#ERE Persons9LastName&'#ansen' 2ND Persons9FirstName&'Ola'
s youGll see from the two S1L1*T statements above aliases can ma6e ueries easier to both
write and to read.
SQL Hoins
SQL 0oins are used to uery data from two or more tables, based on a relationshipbetween certain columns in these tables.
-
8/19/2019 SQL Queries Part1
29/42
SQL HO$'
The HO$' 6eyword is used in an SQL statement to uery data from two or more tables, based on a
relationship between certain columns in these tables.
Tables in a database are often related to each other with 6eys.
primary 6ey is a column (or a combination of columns) with a uniue value for each row. 1ach
primary 6ey value must be uniue within the table. The purpose is to bind data together, across
tables, without repeating all of the data in every table.
Loo6 at the 82ersons8 table:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
30/42
• #OIN: 3eturn rows when there is at least one match in both tables
• LEFT #OIN: 3eturn all rows from the left table, even if there are no matches in the right
table
• RI$%T #OIN: 3eturn all rows from the right table, even if there are no matches in the left
table
• FULL #OIN: 3eturn rows when there is a match in one of the tables
SQL $''13 HO$'
-
8/19/2019 SQL Queries Part1
31/42
I ;EKJE 9I
'ow we want to list all the persons with any orders.
%e use the following S1L1*T statement:
SELECT Persons9LastName, Persons9FirstName, Orers9OrerNo
FROM Persons
NNER ;ON Orers
ON Persons9P_&Orers9P_
ORDER 3- Persons9LastName
The result-set will loo6 li6e this:
LastName FirstName OrderNo
/ansen Ola ##EIJ
/ansen Ola #EIJ#
2ettersen T HO$' T HO$' T HO$' 6eyword returns all rows from the left table (table=name9), even if there are no
matches in the right table (table=name#).
SQL L1>T HO$' Synta+SELECT column_name(s)
FROM table_name.
LEFT ;ON table_name7
ON table_name.9column_name&table_name79column_name
PS: $n some databases L1>T HO$' is called L1>T OT13 HO$'.
SQL L1>T HO$' 1+ample
The 82ersons8 table:
-
8/19/2019 SQL Queries Part1
32/42
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
33/42
SQL 3$@/T HO$'
-
8/19/2019 SQL Queries Part1
34/42
LastName FirstName OrderNo
/ansen Ola ##EIJ
/ansen Ola #EIJ#
2ettersen LL HO$' Synta+
SELECT column_name(s)
FROM table_name.
F6LL ;ON table_name7
ON table_name.9column_name&table_name79column_name
SQL >LL HO$' 1+ample
The 82ersons8 table:
P_Id LastName FirstName Address City
9 /ansen Ola Timoteivn 9 Sandnes
# Svendson Tove "orgvn #; Sandnes
; 2ettersen
-
8/19/2019 SQL Queries Part1
35/42
; ##EIJ 9
E #EIJ# 9
I ;EKJE 9I
'ow we want to list all the persons and their orders, and all the orders with their persons.
%e use the following S1L1*T statement:
SELECT Persons9LastName, Persons9FirstName, Orers9OrerNo
FROM Persons
F6LL ;ON Orers
ON Persons9P_&Orers9P_
ORDER 3- Persons9LastName
The result-set will loo6 li6e this:
LastName FirstName OrderNo
/ansen Ola ##EIJ
/ansen Ola #EIJ#
2ettersen
-
8/19/2019 SQL Queries Part1
36/42
'otice that each S1L1*T statement within the '$O' must have the same number of columns.
The columns must also have similar data types. lso, the columns in each S1L1*T statement must
be in the same order.
SQL '$O' Synta+
SELECT column_name(s) FROM table_name.6NON
SELECT column_name(s) FROM table_name7
Note: The '$O' operator selects only distinct values by default. To allow duplicate values, use
'$O' LL.
SQL '$O' LL Synta+
SELECT column_name(s) FROM table_name.
6NON 2LL
SELECT column_name(s) FROM table_name7
PS: The column names in the result-set of a '$O' are always eual to the column names in the
first S1L1*T statement in the '$O'.
SQL '$O' 1+ample
Loo6 at the following tables:
&Emp"oyees_Nor'ay&:
E_ID E_Name
9 /ansen, Ola
# Svendson, Tove
; Svendson, Stephen
E 2ettersen,
-
8/19/2019 SQL Queries Part1
37/42
%e use the following S1L1*T statement:
SELECT E_Name FROM Em$lo!ees_Nor+a!
6NON
SELECT E_Name FROM Em$lo!ees_6S2
The result-set will loo6 li6e this:
E_Name
/ansen, Ola
Svendson, Tove
Svendson, Stephen
2ettersen,
-
8/19/2019 SQL Queries Part1
38/42
-
8/19/2019 SQL Queries Part1
39/42
SELECT *
NTO Persons_3ac
-
8/19/2019 SQL Queries Part1
40/42
SQL *31T1 !T"S1 Synta+
CRE2TE D2T232SE atabase_name
*31T1 !T"S1 1+ample
'ow we want to create a database called 8my=db8.
%e use the following *31T1 !T"S1 statement:
CRE2TE D2T232SE m!_b
!atabase tables can be added with the *31T1 T"L1 statement.
SQL *31T1 T"L1 Statement
The *31T1 T"L1 Statement
The *31T1 T"L1 statement is used to create a table in a database.
SQL *31T1 T"L1 Synta+
CRE2TE T23LE table_name
(
column_name. ata_t!$e,
column_name7 ata_t!$e,
column_name8 ata_t!$e,
9999
)
The data type specifies what type of data the column can hold. >or a complete reference of all the
data types available in MS ccess, MySQL, and SQL Server, go to our complete !ata Types
reference.
*31T1 T"L1 1+ample
'ow we want to create a table called 82ersons8 that contains five columns: 2=$d, Last'ame,
>irst'ame, ddress, and *ity.
%e use the following *31T1 T"L1 statement:
CRE2TE T23LE Persons
(
P_ int,LastName %arcar(711),
http://www.w3schools.com/sql/sql_datatypes.asphttp://www.w3schools.com/sql/sql_datatypes.asphttp://www.w3schools.com/sql/sql_datatypes.asphttp://www.w3schools.com/sql/sql_datatypes.asp
-
8/19/2019 SQL Queries Part1
41/42
FirstName %arcar(711),
2ress %arcar(711),
Cit! %arcar(711)
)
The 2=$d column is of type int and will hold a number. The Last'ame, >irst'ame, ddress, and*ity columns are of type varchar with a ma+imum length of #II characters.
The empty 82ersons8 table will now loo6 li6e this:
P_Id LastName FirstName Address City
The empty table can be filled with data with the $'S13T $'TO statement.
SQL *onstraints
SQL *onstraints
*onstraints are used to limit the type of data that can go into a table.
*onstraints can be specified when a table is created (with the *31T1 T"L1 statement) or after
the table is created (with the LT13 T"L1 statement).
%e will focus on the following constraints:
• 'OT 'LL
• '$Q1
• 23$M35 O31$@' LT
SQL 'OT 'LL *onstraint
"y default, a table column can hold 'LL values.
-
8/19/2019 SQL Queries Part1
42/42
SQL 'OT 'LL *onstraint
The 'OT 'LL constraint enforces a column to 'OT accept 'LL values.
The 'OT 'LL constraint enforces a field to always contain a value. This means that you cannot
insert a new record, or update a record without adding a value to this field.
The following SQL enforces the 82=$d8 column and the 8Last'ame8 column to not accept 'LL
values:
CRE2TE T23LE Persons
(
P_ int NOT N6LL,
LastName %arcar(711) NOT N6LL,
FirstName %arcar(711),
2ress %arcar(711),
Cit! %arcar(711))