Sei sulla pagina 1di 39

SQL TOP Clause

The TOP Clause


The TOP clause is used to specify the number of records to return. The TOP clause can be very useful on large tables with thousands of records. Returning a large number of records can impact on performance. Note: ot all database systems support the TOP clause.

SQL Server Syntax


S!L!CT TOP number"percent column#name$s% &RO' table#name

SQL SELECT TOP Equivalent in MySQL and Oracle


MySQL Syntax
S!L!CT column#name$s% &RO' table#name L('(T number

Example
S!L!CT ) &RO' Persons L('(T *

Oracle Syntax
S!L!CT column#name$s% &RO' table#name +,!R! RO+ -' ./ number

Example
S!L!CT ) &RO' Persons +,!R! RO+ -' ./*

SQL TOP Example


The 0Persons0 table1 P_Id 2 4 6 8 LastName ,ansen Svendson Pettersen ilsen FirstName Ola Tove 7ari Tom Address Timoteivn 23 5orgvn 46 Storgt 43 9ingvn 46 City Sandnes Sandnes Stavanger Stavanger

ow we want to select only the two first records in the table above. +e use the following S!L!CT statement1 S!L!CT TOP 4 ) &RO' Persons The result:set will loo; li;e this1

P_Id 2 4

LastName ,ansen Svendson

FirstName Ola Tove

Address Timoteivn 23 5orgvn 46

City Sandnes Sandnes

SQL TOP PERCENT Example


The 0Persons0 table1 P_Id 2 4 6 8 LastName ,ansen Svendson Pettersen ilsen FirstName Ola Tove 7ari Tom Address Timoteivn 23 5orgvn 46 Storgt 43 9ingvn 46 City Sandnes Sandnes Stavanger Stavanger

ow we want to select only *3< of the records in the table above. +e use the following S!L!CT statement1 S!L!CT TOP *3 P!RC! T ) &RO' Persons The result:set will loo; li;e this1 P_Id 2 4 LastName ,ansen Svendson FirstName Ola Tove Address Timoteivn 23 5orgvn 46 City Sandnes Sandnes

SQL L(7! Operator


The L(7! operator is used in a +,!R! clause to search for a specified pattern in a column.

The LI E Operat!r
The L(7! operator is used to search for a specified pattern in a column.

SQL LI E Syntax
S!L!CT column#name$s% &RO' table#name +,!R! column#name L(7! pattern

LI E Operat!r Example
The 0Persons0 table1 P_Id 2 4 6 LastName ,ansen Svendson Pettersen FirstName Ola Tove 7ari Address Timoteivn 23 5orgvn 46 Storgt 43 City Sandnes Sandnes Stavanger

ow we want to select the persons living in a city that starts with 0s0 from the table above. +e use the following S!L!CT statement1

S!L!CT ) &RO' Persons +,!R! City L(7! =s<= The 0<0 sign can be used to define wildcards $missing letters in the pattern% both before and after the pattern. The result:set will loo; li;e this1 P_Id 2 4 6 LastName ,ansen Svendson Pettersen FirstName Ola Tove 7ari Address Timoteivn 23 5orgvn 46 Storgt 43 City Sandnes Sandnes Stavanger

e>t? we want to select the persons living in a city that ends with an 0s0 from the 0Persons0 table. +e use the following S!L!CT statement1 S!L!CT ) &RO' Persons +,!R! City L(7! =<s= The result:set will loo; li;e this1 P_Id 2 4 LastName ,ansen Svendson FirstName Ola Tove Address Timoteivn 23 5orgvn 46 City Sandnes Sandnes

e>t? we want to select the persons living in a city that contains the pattern 0tav0 from the 0Persons0 table. +e use the following S!L!CT statement1 S!L!CT ) &RO' Persons +,!R! City L(7! =<tav<= The result:set will loo; li;e this1 P_Id 6 LastName Pettersen FirstName 7ari Address Storgt 43 City Stavanger

(t is also possible to select the persons living in a city that 0Persons0 table? by using the OT ;eyword. +e use the following S!L!CT statement1 S!L!CT ) &RO' Persons +,!R! City OT L(7! =<tav<= The result:set will loo; li;e this1 P_Id 2 4 LastName ,ansen Svendson FirstName Ola Tove

OT contains the pattern 0tav0 from the

Address Timoteivn 23 5orgvn 46

City Sandnes 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(7! operator. +ith SQL? the following wildcards can be used1 Wildcard < # BcharlistC BDcharlistC or [!charlist] Description @ substitute for Aero or more characters @ substitute for e>actly one character @ny single character in charlist @ny single character not in charlist

SQL "ildcard Examples


+e have the following 0Persons0 table1 P_Id 2 4 6 LastName ,ansen Svendson Pettersen FirstName Ola Tove 7ari Address Timoteivn 23 5orgvn 46 Storgt 43 City Sandnes Sandnes Stavanger

#sin$ the % "ildcard


ow we want to select the persons living in a city that starts with 0sa0 from the 0Persons0 table. +e use the following S!L!CT statement1 S!L!CT ) &RO' Persons +,!R! City L(7! =sa<= The result:set will loo; li;e this1 P_Id 2 4 LastName ,ansen Svendson FirstName Ola Tove Address Timoteivn 23 5orgvn 46 City Sandnes Sandnes

e>t? we want to select the persons living in a city that contains the pattern 0nes0 from the 0Persons0 table. +e use the following S!L!CT statement1 S!L!CT ) &RO' Persons +,!R! City L(7! =<nes<= The result:set will loo; li;e this1 P_Id 2 4 LastName ,ansen Svendson FirstName Ola Tove Address Timoteivn 23 5orgvn 46 City Sandnes Sandnes

#sin$ the & "ildcard


ow we want to select the persons with a first name that starts with any character? followed by 0la0 from the 0Persons0 table.

+e use the following S!L!CT statement1 S!L!CT ) &RO' Persons +,!R! &irst ame L(7! =#la= The result:set will loo; li;e this1 P_Id 2 LastName ,ansen FirstName Ola Address Timoteivn 23 City Sandnes

e>t? we want to select the persons with a last name that starts with 0S0? followed by any character? followed by 0end0? followed by any character? followed by 0on0 from the 0Persons0 table. +e use the following S!L!CT statement1 S!L!CT ) &RO' Persons +,!R! Last ame L(7! =S#end#on= The result:set will loo; li;e this1 P_Id 4 LastName Svendson FirstName Tove Address 5orgvn 46 City Sandnes

#sin$ the 'charlist( "ildcard


ow we want to select the persons with a last name that starts with 0b0 or 0s0 or 0p0 from the 0Persons0 table. +e use the following S!L!CT statement1 S!L!CT ) &RO' Persons +,!R! Last ame L(7! =BbspC<= The result:set will loo; li;e this1 P_Id 4 6 LastName Svendson Pettersen FirstName Tove 7ari Address 5orgvn 46 Storgt 43 City Sandnes Stavanger

e>t? we want to select the persons with a last name that do not start with 0b0 or 0s0 or 0p0 from the 0Persons0 table. +e use the following S!L!CT statement1 S!L!CT ) &RO' Persons +,!R! Last ame L(7! =BEbspC<= The result:set will loo; li;e this1 P_Id 2 LastName ,ansen FirstName Ola Address Timoteivn 23 City Sandnes

SQL (
The (

Operator

The IN Operat!r
operator allows you to specify multiple values in a +,!R! clause.

SQL IN Syntax
S!L!CT column#name$s%

&RO' table#name +,!R! column#name (

$value2?value4?...%

IN Operat!r Example
The 0Persons0 table1 P_Id 2 4 6 LastName ,ansen Svendson Pettersen FirstName Ola Tove 7ari Address Timoteivn 23 5orgvn 46 Storgt 43 City Sandnes Sandnes Stavanger

ow we want to select the persons with a last name eFual to 0,ansen0 or 0Pettersen0 from the table above. +e use the following S!L!CT statement1 S!L!CT ) &RO' Persons +,!R! Last ame ( $=,ansen=?=Pettersen=% The result:set will loo; li;e this1 P_Id 2 6 LastName ,ansen Pettersen FirstName Ola 7ari Address Timoteivn 23 Storgt 43 City Sandnes Stavanger

SQL 5!T+!!

Operator

The 5!T+!! operator is used in a +,!R! clause to select a range of data between two values.

The )ET"EEN Operat!r


The 5!T+!! or dates. operator selects a range of data between two values. The values can be numbers? te>t?

SQL )ET"EEN Syntax


S!L!CT column#name$s% &RO' table#name +,!R! column#name 5!T+!! value2 @ G value4

)ET"EEN Operat!r Example


The 0Persons0 table1 P_Id 2 4 6 LastName ,ansen Svendson Pettersen FirstName Ola Tove 7ari Address Timoteivn 23 5orgvn 46 Storgt 43 City Sandnes Sandnes Stavanger

ow we want to select the persons with a last name alphabetically between 0,ansen0 and 0Pettersen0 from the table above. +e use the following S!L!CT statement1

S!L!CT ) &RO' Persons +,!R! Last ame 5!T+!! =,ansen= @ G =Pettersen= The result:set will loo; li;e this1 P_Id 2 LastName ,ansen FirstName Ola Address Timoteivn 23 City Sandnes

Note: The 5!T+!!

operator is treated differently in different databases.

(n some databases? persons with the Last ame of 0,ansen0 or 0Pettersen0 will not be listed? because the 5!T+!! operator only selects fields that are between and e>cluding the test values%. (n other databases? persons with the Last ame of 0,ansen0 or 0Pettersen0 will be listed? because the 5!T+!! operator selects fields that are between and including the test values%. @nd in other databases? persons with the Last ame of 0,ansen0 will be listed? but 0Pettersen0 will not be listed $li;e the e>ample above%? because the 5!T+!! operator selects fields between the test values? including the first test value and e>cluding the last test value. Therefore1 Chec; how your database treats the 5!T+!! operator.

Example *
To display the persons outside the range in the previous e>ample? use S!L!CT ) &RO' Persons +,!R! Last ame OT 5!T+!! =,ansen= @ G =Pettersen= The result:set will loo; li;e this1 P_Id 4 6 LastName Svendson Pettersen FirstName Tove 7ari Address 5orgvn 46 Storgt 43 City Sandnes Stavanger OT 5!T+!! 1

SQL @lias
+ith SQL? an alias name can be given to a table or to a column.

SQL +lias
Hou 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 Syntax ,!r Ta-les


S!L!CT column#name$s% &RO' table#name @S alias#name

SQL +lias Syntax ,!r C!lumns


S!L!CT column#name @S alias#name &RO' table#name

+lias Example
@ssume we have a table called 0Persons0 and another table called 0Product#Orders0. +e will give the table aliases of 0p0 and 0po0 respectively. ow we want to list all the orders that 0Ola ,ansen0 is responsible for.

+e use the following S!L!CT statement1 S!L!CT po.Order(G? p.Last ame? p.&irst ame &RO' Persons @S p? Product#Orders @S po +,!R! p.Last ame/=,ansen= @ G p.&irst ame/=Ola= The same S!L!CT statement without aliases1 S!L!CT Product#Orders.Order(G? Persons.Last ame? Persons.&irst ame &RO' Persons? Product#Orders +,!R! Persons.Last ame/=,ansen= @ G Persons.&irst ame/=Ola= @s you=ll see from the two S!L!CT statements aboveI aliases can ma;e Fueries easier to both write and to read.

SQL Joins
SQL Koins are used to Fuery data from two or more tables? based on a relationship between certain columns in these tables.

SQL .OIN
The JO( ;eyword is used in an SQL statement to Fuery 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 ;eys. @ primary ;ey is a column $or a combination of columns% with a uniFue value for each row. !ach primary ;ey value must be uniFue within the table. The purpose is to bind data together? across tables? without repeating all of the data in every table. Loo; at the 0Persons0 table1 P_Id 2 4 6 LastName ,ansen Svendson Pettersen FirstName Ola Tove 7ari Address Timoteivn 23 5orgvn 46 Storgt 43 City Sandnes Sandnes Stavanger

ote that the 0P#(d0 column is the primary ;ey in the 0Persons0 table. This means that no two rows can have the same P#(d. The P#(d distinguishes two persons even if they have the same name. e>t? we have the 0Orders0 table1 O_Id 2 4 6 8 * OrderNo LLMN* 88OLM 448*O 48*O4 68LO8 P_Id 6 6 2 2 2*

ote that the 0O#(d0 column is the primary ;ey in the 0Orders0 table and that the 0P#(d0 column refers to the persons in the 0Persons0 table without using their names. otice that the relationship between the two tables above is the 0P#(d0 column.

/i,,erent SQL .OINs


5efore we continue with e>amples? we will list the types of JO( between them. you can use? and the differences

JOIN1 Return rows when there is at least one match in both tables LEFT JOIN1 Return all rows from the left table? even if there are no matches in the right table RI !T JOIN1 Return all rows from the right table? even if there are no matches in the left table F"LL JOIN1 Return rows when there is a match in one of the tables

SQL INNER JOIN Keyword


SQL INNER .OIN
The ( !R JO(

ey0!rd

;eyword return rows when there is at least one match in both tables.

SQL INNER .OIN Syntax


S!L!CT column#name$s% &RO' table#name2 ( !R JO( table#name4 O table#name2.column#name/table#name4.column#name P#: ( !R JO( is the same as JO( .

SQL INNER .OIN Example


The 0Persons0 table1 P_Id 2 4 6 LastName ,ansen Svendson Pettersen FirstName Ola Tove 7ari Address Timoteivn 23 5orgvn 46 Storgt 43 City Sandnes Sandnes Stavanger

The 0Orders0 table1 O_Id 2 4 6 8 * OrderNo LLMN* 88OLM 448*O 48*O4 68LO8 P_Id 6 6 2 2 2*

ow we want to list all the persons with any orders. +e use the following S!L!CT statement1 S!L!CT Persons.Last ame? Persons.&irst ame? Orders.Order o &RO' Persons ( !R JO( Orders O Persons.P#(d/Orders.P#(d ORG!R 5H Persons.Last ame The result:set will loo; li;e this1

LastName ,ansen ,ansen Pettersen Pettersen

FirstName Ola Ola 7ari 7ari

OrderNo 448*O 48*O4 LLMN* 88OLM

The ( !R JO( ;eyword return rows when there is at least one match in both tables. (f there are rows in 0Persons0 that do not have matches in 0Orders0? those rows will OT be listed.

SQL L!&T JO(


SQL LE1T .OIN

7eyword
ey0!rd

The L!&T JO( ;eyword returns all rows from the left table $table#name2%? even if there are no matches in the right table $table#name4%.

SQL LE1T .OIN Syntax


S!L!CT column#name$s% &RO' table#name2 L!&T JO( table#name4 O table#name2.column#name/table#name4.column#name P#: (n some databases L!&T JO( is called L!&T O-T!R JO( .

SQL LE1T .OIN Example


The 0Persons0 table1 P_Id 2 4 6 LastName ,ansen Svendson Pettersen FirstName Ola Tove 7ari Address Timoteivn 23 5orgvn 46 Storgt 43 City Sandnes Sandnes Stavanger

The 0Orders0 table1 O_Id 2 4 6 8 * OrderNo LLMN* 88OLM 448*O 48*O4 68LO8 P_Id 6 6 2 2 2*

ow we want to list all the persons and their orders : if any? from the tables above. +e use the following S!L!CT statement1 S!L!CT Persons.Last ame? Persons.&irst ame? Orders.Order o &RO' Persons L!&T JO( Orders O Persons.P#(d/Orders.P#(d ORG!R 5H Persons.Last ame

The result:set will loo; li;e this1 LastName ,ansen ,ansen Pettersen Pettersen Svendson FirstName Ola Ola 7ari 7ari Tove OrderNo 448*O 48*O4 LLMN* 88OLM

The L!&T JO( ;eyword returns all the rows from the left table $Persons%? even if there are no matches in the right table $Orders%.

SQL RIGHT JOIN Keyword


SQL RI23T .OIN ey0!rd
The R(P,T JO( ;eyword Return all rows from the right table $table#name4%? even if there are no matches in the left table $table#name2%.

SQL RI23T .OIN Syntax


S!L!CT column#name$s% &RO' table#name2 R(P,T JO( table#name4 O table#name2.column#name/table#name4.column#name P#: (n some databases R(P,T JO( is called R(P,T O-T!R JO( .

SQL RI23T .OIN Example


The 0Persons0 table1 P_Id 2 4 6 LastName ,ansen Svendson Pettersen FirstName Ola Tove 7ari Address Timoteivn 23 5orgvn 46 Storgt 43 City Sandnes Sandnes Stavanger

The 0Orders0 table1 O_Id 2 4 6 8 * OrderNo LLMN* 88OLM 448*O 48*O4 68LO8 P_Id 6 6 2 2 2*

ow we want to list all the orders with containing persons : if any? from the tables above. +e use the following S!L!CT statement1 S!L!CT Persons.Last ame? Persons.&irst ame? Orders.Order o &RO' Persons

R(P,T JO( Orders O Persons.P#(d/Orders.P#(d ORG!R 5H Persons.Last ame The result:set will loo; li;e this1 LastName ,ansen ,ansen Pettersen Pettersen FirstName Ola Ola 7ari 7ari OrderNo 448*O 48*O4 LLMN* 88OLM 68LO8 The R(P,T JO( ;eyword returns all the rows from the right table $Orders%? even if there are no matches in the left table $Persons%.

SQL &-LL JO(


SQL 1#LL .OIN
The &-LL JO(

7eyword
ey0!rd

;eyword return rows when there is a match in one of the tables.

SQL 1#LL .OIN Syntax


S!L!CT column#name$s% &RO' table#name2 &-LL JO( table#name4 O table#name2.column#name/table#name4.column#name

SQL 1#LL .OIN Example


The 0Persons0 table1 P_Id 2 4 6 LastName ,ansen Svendson Pettersen FirstName Ola Tove 7ari Address Timoteivn 23 5orgvn 46 Storgt 43 City Sandnes Sandnes Stavanger

The 0Orders0 table1 O_Id 2 4 6 8 * OrderNo LLMN* 88OLM 448*O 48*O4 68LO8 P_Id 6 6 2 2 2*

ow we want to list all the persons and their orders? and all the orders with their persons. +e use the following S!L!CT statement1

S!L!CT Persons.Last ame? Persons.&irst ame? Orders.Order o &RO' Persons &-LL JO( Orders O Persons.P#(d/Orders.P#(d ORG!R 5H Persons.Last ame The result:set will loo; li;e this1 LastName ,ansen ,ansen Pettersen Pettersen Svendson FirstName Ola Ola 7ari 7ari Tove 68LO8 The &-LL JO( ;eyword returns all the rows from the left table $Persons%? and all the rows from the right table $Orders%. (f there are rows in 0Persons0 that do not have matches in 0Orders0? or if there are rows in 0Orders0 that do not have matches in 0Persons0? those rows will be listed as well. OrderNo 448*O 48*O4 LLMN* 88OLM

SQL - (O
The SQL - (O

Operator
operator combines two or more S!L!CT statements.

The SQL #NION Operat!r


The - (O operator is used to combine the result:set of two or more S!L!CT statements. otice that each S!L!CT statement within the - (O must have the same number of columns. The columns must also have similar data types. @lso? the columns in each S!L!CT statement must be in the same order.

SQL #NION Syntax


S!L!CT column#name$s% &RO' table#name2 - (O S!L!CT column#name$s% &RO' table#name4 Note: The - (O - (O @LL. operator selects only distinct values by default. To allow duplicate values? use

SQL #NION +LL Syntax


S!L!CT column#name$s% &RO' table#name2 - (O @LL S!L!CT column#name$s% &RO' table#name4 P#: The column names in the result:set of a - (O S!L!CT statement in the - (O . are always eFual to the column names in the first

SQL #NION Example


Loo; at the following tables1 $Employees_Nor%ay$1 E_ID 32 E_Name ,ansen? Ola

34 36 38 $Employees_"#A$1 E_ID 32 34 36 38

Svendson? Tove Svendson? Stephen Pettersen? 7ari

E_Name Turner? Sally 7ent? Clar; Svendson? Stephen Scott? Stephen orway and -S@.

ow we want to list all t&e di''erent employees in +e use the following S!L!CT statement1 S!L!CT !# ame &RO' !mployees# orway - (O S!L!CT !# ame &RO' !mployees#-S@ The result:set will loo; li;e this1 E_Name ,ansen? Ola Svendson? Tove Svendson? Stephen Pettersen? 7ari Turner? Sally 7ent? Clar; Scott? Stephen

Note: This command cannot be used to list all employees in orway and -S@. (n the e>ample above we have two employees with eFual names? and only one of them will be listed. The - (O command selects only distinct values.

SQL #NION +LL Example


ow we want to list all employees in orway and -S@1 S!L!CT !# ame &RO' !mployees# orway - (O @LL S!L!CT !# ame &RO' !mployees#-S@ Res(lt E_Name ,ansen? Ola Svendson? Tove Svendson? Stephen

Pettersen? 7ari Turner? Sally 7ent? Clar; Svendson? Stephen Scott? Stephen

SQL S!L!CT ( TO Statement


The SQL S!L!CT ( TO statement can be used to create bac;up copies of tables.

The SQL SELECT INTO Statement


The S!L!CT ( TO statement selects data from one table and inserts it into a different table. The S!L!CT ( TO statement is most often used to create bac;up copies of tables.

SQL SELECT INTO Syntax


+e can select all columns into the new table1 S!L!CT ) ( TO new#table#name B( &RO' old#tablename

e>ternaldatabaseC

Or we can select only the columns we want into the new table1 S!L!CT column#name$s% ( TO new#table#name B( &RO' old#tablename

e>ternaldatabaseC

SQL SELECT INTO Example


)a*e a +ac*(p Copy : ow we want to ma;e an e>act copy of the data in our 0Persons0 table. +e use the following SQL statement1 S!L!CT ) ( TO Persons#5ac;up &RO' Persons +e can also use the ( S!L!CT ) ( TO Persons#5ac;up ( &RO' Persons clause to copy the table into another database1

=5ac;up.mdb=

+e can also copy only a few fields into the new table1 S!L!CT Last ame?&irst ame ( TO Persons#5ac;up &RO' Persons

SQL SELECT INTO 4 "ith a "3ERE Clause


+e can also add a +,!R! clause. The following SQL statement creates a 0Persons#5ac;up0 table with only the persons who lives in the city 0Sandnes01

S!L!CT Last ame?&irstname ( TO Persons#5ac;up &RO' Persons +,!R! City/=Sandnes=

SQL SELECT INTO 4 .!ined Ta-les


Selecting data from more than one table is also possible. The following e>ample creates a 0Persons#Order#5ac;up0 table contains data from the two tables 0Persons0 and 0Orders01 S!L!CT Persons.Last ame?Orders.Order o ( TO Persons#Order#5ac;up &RO' Persons ( !R JO( Orders O Persons.P#(d/Orders.P#(d

SQL CR!@T! G@T@5@S! Statement


The CRE+TE /+T+)+SE Statement
The CR!@T! G@T@5@S! statement is used to create a database.

SQL CRE+TE /+T+)+SE Syntax


CR!@T! G@T@5@S! database#name

CRE+TE /+T+)+SE Example


ow we want to create a database called 0my#db0. +e use the following CR!@T! G@T@5@S! statement1 CR!@T! G@T@5@S! my#db Gatabase tables can be added with the CR!@T! T@5L! statement.

SQL CR!@T! T@5L! Statement


The CRE+TE T+)LE Statement
The CR!@T! T@5L! statement is used to create a table in a database.

SQL CRE+TE T+)LE Syntax


CR!@T! T@5L! table#name $ column#name2 data#type? column#name4 data#type? column#name6 data#type? .... % The data type specifies what type of data the column can hold. &or a complete reference of all the data types available in 'S @ccess? 'ySQL? and SQL Server? go to our complete Gata Types reference.

CRE+TE T+)LE Example


ow we want to create a table called 0Persons0 that contains five columns1 P#(d? Last ame? &irst ame? @ddress? and City. +e use the following CR!@T! T@5L! statement1 CR!@T! T@5L! Persons

$ P#(d int? Last ame varchar$4**%? &irst ame varchar$4**%? @ddress varchar$4**%? City varchar$4**% % The P#(d column is of type int and will hold a number. The Last ame? &irst ame? @ddress? and City columns are of type varchar with a ma>imum length of 4** characters. The empty 0Persons0 table will now loo; li;e this1 P_Id LastName FirstName Address City

The empty table can be filled with data with the ( S!RT ( TO statement.

SQL Constraints
SQL C!nstraints
Constraints are used to limit the type of data that can go into a table. Constraints can be specified when a table is created $with the CR!@T! T@5L! statement% or after the table is created $with the @LT!R T@5L! statement%. +e will focus on the following constraints1

OT

-LL

- (Q-! PR('@RH 7!H &OR!(P C,!C7 G!&@-LT 7!H

SQL

OT

-LL Constraint
-LL values.

5y default? a table column can hold

SQL NOT N#LL C!nstraint


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 0P#(d0 column and the 0Last ame0 column to not accept CR!@T! T@5L! Persons $ P#(d int OT -LL? Last ame varchar$4**% OT &irst ame varchar$4**%? @ddress varchar$4**%? City varchar$4**% % -LL values1

-LL?

SQL UNIQUE

o!strai!t

SQL #NIQ#E C!nstraint


The - (Q-! constraint uniFuely identifies each record in a database table. The - (Q-! and PR('@RH 7!H constraints both provide a guarantee for uniFueness for a column or set of columns. @ PR('@RH 7!H constraint automatically has a - (Q-! constraint defined on it. ote that you can have many - (Q-! constraints per table? but only one PR('@RH 7!H constraint per table.

SQL #NIQ#E C!nstraint !n CRE+TE T+)LE


The following SQL creates a - (Q-! constraint on the 0P#(d0 column when the 0Persons0 table is created1 )y#,L: CR!@T! T@5L! Persons $ P#(d int OT -LL? Last ame varchar$4**% OT &irst ame varchar$4**%? @ddress varchar$4**%? City varchar$4**%? - (Q-! $P#(d% %

-LL?

#,L #er-er . Oracle . )# Access: CR!@T! T@5L! Persons $ P#(d int OT -LL - (Q-!? Last ame varchar$4**% OT &irst ame varchar$4**%? @ddress varchar$4**%? City varchar$4**% %

-LL?

To allow naming of a - (Q-! constraint? and for defining a - (Q-! constraint on multiple columns? use the following SQL synta>1 )y#,L . #,L #er-er . Oracle . )# Access: CR!@T! T@5L! Persons $ P#(d int OT -LL? Last ame varchar$4**% OT -LL? &irst ame varchar$4**%? @ddress varchar$4**%? City varchar$4**%? CO STR@( T uc#Person(G - (Q-! $P#(d?Last ame% %

SQL #NIQ#E C!nstraint !n +LTER T+)LE


To create a - (Q-! constraint on the 0P#(d0 column when the table is already created? use the following SQL1 )y#,L . #,L #er-er . Oracle . )# Access: @LT!R T@5L! Persons @GG - (Q-! $P#(d% To allow naming of a - (Q-! constraint? and for defining a - (Q-! constraint on multiple columns? use the following SQL synta>1

)y#,L . #,L #er-er . Oracle . )# Access: @LT!R T@5L! Persons @GG CO STR@( T uc#Person(G - (Q-! $P#(d?Last ame%

T! /ROP a #NIQ#E C!nstraint


To drop a - (Q-! constraint? use the following SQL1 )y#,L: @LT!R T@5L! Persons GROP ( G!Q uc#Person(G #,L #er-er . Oracle . )# Access: @LT!R T@5L! Persons GROP CO STR@( T uc#Person(G

SQL PR('@RH 7!H Constraint


SQL PRIM+R5 E5 C!nstraint
The PR('@RH 7!H constraint uniFuely identifies each record in a database table. Primary ;eys must contain uniFue values. @ primary ;ey column cannot contain -LL values.

!ach table should have a primary ;ey? and each table can have only O ! primary ;ey.

SQL PRIM+R5
)y#,L: CR!@T! T@5L! Persons $ P#(d int OT -LL? Last ame varchar$4**% OT &irst ame varchar$4**%? @ddress varchar$4**%? City varchar$4**%? PR('@RH 7!H $P#(d% %

E5 C!nstraint !n CRE+TE T+)LE

The following SQL creates a PR('@RH 7!H on the 0P#(d0 column when the 0Persons0 table is created1

-LL?

#,L #er-er . Oracle . )# Access: CR!@T! T@5L! Persons $ P#(d int OT -LL PR('@RH 7!H? Last ame varchar$4**% OT -LL? &irst ame varchar$4**%? @ddress varchar$4**%? City varchar$4**% % To allow naming of a PR('@RH 7!H constraint? and for defining a PR('@RH 7!H constraint on multiple columns? use the following SQL synta>1 )y#,L . #,L #er-er . Oracle . )# Access: CR!@T! T@5L! Persons $ P#(d int OT -LL?

Last ame varchar$4**% OT -LL? &irst ame varchar$4**%? @ddress varchar$4**%? City varchar$4**%? CO STR@( T p;#Person(G PR('@RH 7!H $P#(d?Last ame% %

SQL PRIM+R5

E5 C!nstraint !n +LTER T+)LE

To create a PR('@RH 7!H constraint on the 0P#(d0 column when the table is already created? use the following SQL1 )y#,L . #,L #er-er . Oracle . )# Access: @LT!R T@5L! Persons @GG PR('@RH 7!H $P#(d% To allow naming of a PR('@RH 7!H constraint? and for defining a PR('@RH 7!H constraint on multiple columns? use the following SQL synta>1 )y#,L . #,L #er-er . Oracle . )# Access: @LT!R T@5L! Persons @GG CO STR@( T p;#Person(G PR('@RH 7!H $P#(d?Last ame% Note: (f you use the @LT!R T@5L! statement to add a primary ;ey? the primary ;ey column$s% must already have been declared to not contain -LL values $when the table was first created%.

T! /ROP a PRIM+R5
)y#,L: @LT!R T@5L! Persons GROP PR('@RH 7!H #,L #er-er . Oracle . )# Access: @LT!R T@5L! Persons GROP CO STR@( T p;#Person(G

E5 C!nstraint

To drop a PR('@RH 7!H constraint? use the following SQL1

SQL &OR!(P
SQL 1OREI2N
@ &OR!(P

7!H Constraint
E5 C!nstraint

7!H in one table points to a PR('@RH 7!H in another table.

Let=s illustrate the foreign ;ey with an e>ample. Loo; at the following two tables1 The 0Persons0 table1 P_Id 2 4 6 LastName ,ansen Svendson Pettersen FirstName Ola Tove 7ari Address Timoteivn 23 5orgvn 46 Storgt 43 City Sandnes Sandnes Stavanger

The 0Orders0 table1 O_Id 2 OrderNo LLMN* P_Id 6

4 6 8

88OLM 448*O 48*O4

6 4 2

ote that the 0P#(d0 column in the 0Orders0 table points to the 0P#(d0 column in the 0Persons0 table. The 0P#(d0 column in the 0Persons0 table is the PR('@RH 7!H in the 0Persons0 table. The 0P#(d0 column in the 0Orders0 table is a &OR!(P The &OR!(P 7!H in the 0Orders0 table.

7!H constraint is used to prevent actions that would destroy lin;s between tables.

The &OR!(P 7!H constraint also prevents that invalid data form being inserted into the foreign ;ey column? because it has to be one of the values contained in the table it points to.

SQL 1OREI2N
)y#,L:

E5 C!nstraint !n CRE+TE T+)LE


7!H on the 0P#(d0 column when the 0Orders0 table is created1

The following SQL creates a &OR!(P

CR!@T! T@5L! Orders $ O#(d int OT -LL? Order o int OT -LL? P#(d int? PR('@RH 7!H $O#(d%? &OR!(P 7!H $P#(d% R!&!R! C!S Persons$P#(d% % #,L #er-er . Oracle . )# Access: CR!@T! T@5L! Orders $ O#(d int OT -LL PR('@RH 7!H? Order o int OT -LL? P#(d int &OR!(P 7!H R!&!R! C!S Persons$P#(d% % To allow naming of a &OR!(P 7!H constraint? and for defining a &OR!(P columns? use the following SQL synta>1 )y#,L . #,L #er-er . Oracle . )# Access: CR!@T! T@5L! Orders $ O#(d int OT -LL? Order o int OT -LL? P#(d int? PR('@RH 7!H $O#(d%? CO STR@( T f;#PerOrders &OR!(P R!&!R! C!S Persons$P#(d% % 7!H constraint on multiple

7!H $P#(d%

SQL 1OREI2N

E5 C!nstraint !n +LTER T+)LE

To create a &OR!(P 7!H constraint on the 0P#(d0 column when the 0Orders0 table is already created? use the following SQL1 )y#,L . #,L #er-er . Oracle . )# Access:

@LT!R T@5L! Orders @GG &OR!(P 7!H $P#(d% R!&!R! C!S Persons$P#(d% To allow naming of a &OR!(P 7!H constraint? and for defining a &OR!(P columns? use the following SQL synta>1 )y#,L . #,L #er-er . Oracle . )# Access: @LT!R T@5L! Orders @GG CO STR@( T f;#PerOrders &OR!(P 7!H $P#(d% R!&!R! C!S Persons$P#(d% 7!H constraint on multiple

T! /ROP a 1OREI2N
To drop a &OR!(P )y#,L: @LT!R T@5L! Orders GROP &OR!(P 7!H f;#PerOrders #,L #er-er . Oracle . )# Access: @LT!R T@5L! Orders GROP CO STR@( T f;#PerOrders

E5 C!nstraint

7!H constraint? use the following SQL1

SQL

HE K

o!strai!t

SQL C3EC

C!nstraint

The C,!C7 constraint is used to limit the value range that can be placed in a column. (f you define a C,!C7 constraint on a single column it allows only certain values for this column. (f you define a C,!C7 constraint on a table it can limit the values in certain columns based on values in other columns in the row.

SQL C3EC

C!nstraint !n CRE+TE T+)LE

The following SQL creates a C,!C7 constraint on the 0P#(d0 column when the 0Persons0 table is created. The C,!C7 constraint specifies that the column 0P#(d0 must only include integers greater than 3. )y #,L: CR!@T! T@5L! Persons $ P#(d int OT -LL? Last ame varchar$4**% OT &irst ame varchar$4**%? @ddress varchar$4**%? City varchar$4**%? C,!C7 $P#(dR3% %

-LL?

#,L #er-er . Oracle . )# Access: CR!@T! T@5L! Persons $ P#(d int OT -LL C,!C7 $P#(dR3%? Last ame varchar$4**% OT -LL? &irst ame varchar$4**%? @ddress varchar$4**%?

City varchar$4**% % To allow naming of a C,!C7 constraint? and for defining a C,!C7 constraint on multiple columns? use the following SQL synta>1 )y#,L . #,L #er-er . Oracle . )# Access: CR!@T! T@5L! Persons $ P#(d int OT -LL? Last ame varchar$4**% OT -LL? &irst ame varchar$4**%? @ddress varchar$4**%? City varchar$4**%? CO STR@( T ch;#Person C,!C7 $P#(dR3 @ G City/=Sandnes=% %

SQL C3EC

C!nstraint !n +LTER T+)LE

To create a C,!C7 constraint on the 0P#(d0 column when the table is already created? use the following SQL1 )y#,L . #,L #er-er . Oracle . )# Access: @LT!R T@5L! Persons @GG C,!C7 $P#(dR3% To allow naming of a C,!C7 constraint? and for defining a C,!C7 constraint on multiple columns? use the following SQL synta>1 )y#,L . #,L #er-er . Oracle . )# Access: @LT!R T@5L! Persons @GG CO STR@( T ch;#Person C,!C7 $P#(dR3 @ G City/=Sandnes=%

T! /ROP a C3EC

C!nstraint

To drop a C,!C7 constraint? use the following SQL1 #,L #er-er . Oracle . )# Access: @LT!R T@5L! Persons GROP CO STR@( T ch;#Person

SQL G!&@-LT Constraint


SQL /E1+#LT C!nstraint
The G!&@-LT constraint is used to insert a default value into a column. The default value will be added to all new records? if no other value is specified.

SQL /E1+#LT C!nstraint !n CRE+TE T+)LE


The following SQL creates a G!&@-LT constraint on the 0City0 column when the 0Persons0 table is created1 )y #,L . #,L #er-er . Oracle . )# Access: CR!@T! T@5L! Persons $ P#(d int OT -LL? Last ame varchar$4**% OT &irst ame varchar$4**%? @ddress varchar$4**%?

-LL?

City varchar$4**% G!&@-LT =Sandnes= % The G!&@-LT constraint can also be used to insert system values? by using functions li;e P!TG@T!$%1 CR!@T! T@5L! Orders $ O#(d int OT -LL? Order o int OT -LL? P#(d int? OrderGate date G!&@-LT P!TG@T!$% %

SQL /E1+#LT C!nstraint !n +LTER T+)LE


To create a G!&@-LT constraint on the 0City0 column when the table is already created? use the following SQL1 )y#,L: @LT!R T@5L! Persons @LT!R City S!T G!&@-LT =S@ G !S= #,L #er-er . Oracle . )# Access: @LT!R T@5L! Persons @LT!R COL-' City S!T G!&@-LT =S@ G !S=

T! /ROP a /E1+#LT C!nstraint


To drop a G!&@-LT constraint? use the following SQL1 )y#,L: @LT!R T@5L! Persons @LT!R City GROP G!&@-LT #,L #er-er . Oracle . )# Access: @LT!R T@5L! Persons @LT!R COL-' City GROP G!&@-LT

SQL CR!@T! ( G!Q Statement


The CR!@T! ( G!Q statement is used to create inde>es in tables. (nde>es allow the database application to find data fastI without reading the whole table.

(nde>es
@n inde> can be created in a table to find data more Fuic;ly and efficiently. The users cannot see the inde>es? they are Kust used to speed up searchesSFueries. Note: -pdating a table with inde>es ta;es more time than updating a table without $because the inde>es also need an update%. So you should only create inde>es on columns $and tables% that will be freFuently searched against.

SQL CRE+TE IN/E6 Syntax


Creates an inde> on a table. Guplicate values are allowed1 CR!@T! ( G!Q inde>#name O table#name $column#name%

SQL CRE+TE #NIQ#E IN/E6 Syntax


Creates a uniFue inde> on a table. Guplicate values are not allowed1 CR!@T! - (Q-! ( G!Q inde>#name O table#name $column#name% Note: The synta> for creating inde>es varies amongst different databases. Therefore1 Chec; the synta> for creating inde>es in your database.

CRE+TE IN/E6 Example


The SQL statement below creates an inde> named 0P(nde>0 on the 0Last ame0 column in the 0Persons0 table1 CR!@T! ( G!Q P(nde> O Persons $Last ame% (f you want to create an inde> on a combination of columns? you can list the column names within the parentheses? separated by commas1 CR!@T! ( G!Q P(nde> O Persons $Last ame? &irst ame%

SQL "RO# IN"E$% "RO# T&'LE% a!d "RO# "&T&'&SE


(nde>es? tables? and databases can easily be deletedSremoved with the GROP statement.

The /ROP IN/E6 Statement


The GROP ( G!Q statement is used to delete an inde> in a table.

/ROP IN/E6 Syntax ,!r MS +ccess7


GROP ( G!Q inde>#name O table#name

/ROP IN/E6 Syntax ,!r MS SQL Server7


GROP ( G!Q table#name.inde>#name

/ROP IN/E6 Syntax ,!r /)*8Oracle7


GROP ( G!Q inde>#name

/ROP IN/E6 Syntax ,!r MySQL7


@LT!R T@5L! table#name GROP ( G!Q inde>#name

The /ROP T+)LE Statement


The GROP T@5L! statement is used to delete a table. GROP T@5L! table#name

The /ROP /+T+)+SE Statement


The GROP G@T@5@S! statement is used to delete a database. GROP G@T@5@S! database#name

The TR#NC+TE T+)LE Statement


+hat if we only want to delete the data inside the table? and not the table itselfT Then? use the TR- C@T! T@5L! statement1 TR- C@T! T@5L! table#name

SQL @LT!R T@5L! Statement


The +LTER T+)LE Statement
The @LT!R T@5L! statement is used to add? delete? or modify columns in an e>isting table.

SQL +LTER T+)LE Syntax


To add a column in a table? use the following synta>1 @LT!R T@5L! table#name @GG column#name datatype To delete a column in a table? use the following synta> $notice that some database systems don=t allow deleting a column%1 @LT!R T@5L! table#name GROP COL-' column#name To change the data type of a column in a table? use the following synta>1 @LT!R T@5L! table#name @LT!R COL-' column#name datatype

SQL +LTER T+)LE Example


Loo; at the 0Persons0 table1 P_Id 2 4 6 LastName ,ansen Svendson Pettersen FirstName Ola Tove 7ari Address Timoteivn 23 5orgvn 46 Storgt 43 City Sandnes Sandnes Stavanger

ow we want to add a column named 0GateOf5irth0 in the 0Persons0 table. +e use the following SQL statement1 @LT!R T@5L! Persons @GG GateOf5irth date otice that the new column? 0GateOf5irth0? is of type date and is going to hold a date. The data type specifies what type of data the column can hold. &or a complete reference of all the data types available in 'S @ccess? 'ySQL? and SQL Server? go to our complete Gata Types reference. The 0Persons0 table will now li;e this1 P_Id 2 4 LastName ,ansen Svendson FirstName Ola Tove Address Timoteivn 23 5orgvn 46 City Sandnes Sandnes DateO'+irt&

Pettersen

7ari

Storgt 43

Stavanger

Chan$e /ata Type Example


ow we want to change the data type of the column named 0GateOf5irth0 in the 0Persons0 table. +e use the following SQL statement1 @LT!R T@5L! Persons @LT!R COL-' GateOf5irth year otice that the 0GateOf5irth0 column is now of type year and is going to hold a year in a two:digit or four:digit format.

/ROP COL#MN Example


e>t? we want to delete the column named 0GateOf5irth0 in the 0Persons0 table. +e use the following SQL statement1 @LT!R T@5L! Persons GROP COL-' GateOf5irth The 0Persons0 table will now li;e this1 P_Id 2 4 6 LastName ,ansen Svendson Pettersen FirstName Ola Tove 7ari Address Timoteivn 23 5orgvn 46 Storgt 43 City Sandnes Sandnes Stavanger

SQL @-TO ( CR!'! T &ield


@uto:increment allows a uniFue number to be generated when a new record is inserted into a table.

+#TO INCREMENT a 1ield


9ery often we would li;e the value of the primary ;ey field to be created automatically every time a new record is inserted. +e would li;e to create an auto:increment field in a table.

Syntax ,!r MySQL


The following SQL statement defines the 0P#(d0 column to be an auto:increment primary ;ey field in the 0Persons0 table1 CR!@T! T@5L! Persons $ P#(d int OT -LL @-TO#( CR!'! T? Last ame varchar$4**% OT -LL? &irst ame varchar$4**%? @ddress varchar$4**%? City varchar$4**%? PR('@RH 7!H $P#(d% % 'ySQL uses the @-TO#( CR!'! T ;eyword to perform an auto:increment feature.

5y default? the starting value for @-TO#( CR!'! T is 2? and it will increment by 2 for each new record. To let the @-TO#( CR!'! T seFuence start with another value? use the following SQL statement1 @LT!R T@5L! Persons @-TO#( CR!'! T/233 To insert a new record into the 0Persons0 table? we will not have to specify a value for the 0P#(d0 column $a uniFue value will be added automatically%1 ( S!RT ( TO Persons $&irst ame?Last ame% 9@L-!S $=Lars=?='onsen=% The SQL statement above would insert a new record into the 0Persons0 table. The 0P#(d0 column would be assigned a uniFue value. The 0&irst ame0 column would be set to 0Lars0 and the 0Last ame0 column would be set to 0'onsen0.

Syntax ,!r SQL Server


The following SQL statement defines the 0P#(d0 column to be an auto:increment primary ;ey field in the 0Persons0 table1 CR!@T! T@5L! Persons $ P#(d int PR('@RH 7!H (G! T(TH? Last ame varchar$4**% OT -LL? &irst ame varchar$4**%? @ddress varchar$4**%? City varchar$4**% % The 'S SQL Server uses the (G! T(TH ;eyword to perform an auto:increment feature. 5y default? the starting value for (G! T(TH is 2? and it will increment by 2 for each new record. To specify that the 0P#(d0 column should start at value 23 and increment by *? change the identity to (G! T(TH$23?*%. To insert a new record into the 0Persons0 table? we will not have to specify a value for the 0P#(d0 column $a uniFue value will be added automatically%1 ( S!RT ( TO Persons $&irst ame?Last ame% 9@L-!S $=Lars=?='onsen=% The SQL statement above would insert a new record into the 0Persons0 table. The 0P#(d0 column would be assigned a uniFue value. The 0&irst ame0 column would be set to 0Lars0 and the 0Last ame0 column would be set to 0'onsen0.

Syntax ,!r +ccess


The following SQL statement defines the 0P#(d0 column to be an auto:increment primary ;ey field in the 0Persons0 table1 CR!@T! T@5L! Persons $ P#(d PR('@RH 7!H @-TO( CR!'! T? Last ame varchar$4**% OT -LL? &irst ame varchar$4**%? @ddress varchar$4**%? City varchar$4**% % The 'S @ccess uses the @-TO( CR!'! T ;eyword to perform an auto:increment feature. 5y default? the starting value for @-TO( CR!'! T is 2? and it will increment by 2 for each new record. To specify that the 0P#(d0 column should start at value 23 and increment by *? change the autoincrement to @-TO( CR!'! T$23?*%.

To insert a new record into the 0Persons0 table? we will not have to specify a value for the 0P#(d0 column $a uniFue value will be added automatically%1 ( S!RT ( TO Persons $&irst ame?Last ame% 9@L-!S $=Lars=?='onsen=% The SQL statement above would insert a new record into the 0Persons0 table. The 0P#(d0 column would be assigned a uniFue value. The 0&irst ame0 column would be set to 0Lars0 and the 0Last ame0 column would be set to 0'onsen0.

Syntax ,!r Oracle


(n Oracle the code is a little bit more tric;y. Hou will have to create an auto:increment field with the seFuence obKect $this obKect generates a number seFuence%. -se the following CR!@T! S!Q-! C! synta>1 CR!@T! S!Q-! C! seF#person '( 9@L-! 2 ST@RT +(T, 2 ( CR!'! T 5H 2 C@C,! 23 The code above creates a seFuence obKect called seF#person? that starts with 2 and will increment by 2. (t will also cache up to 23 values for performance. The cache option specifies how many seFuence values will be stored in memory for faster access. To insert a new record into the 0Persons0 table? we will have to use the ne>tval function $this function retrieves the ne>t value from seF#person seFuence%1 ( S!RT ( TO Persons $P#(d?&irst ame?Last ame% 9@L-!S $seF#person.ne>tval?=Lars=?='onsen=% The SQL statement above would insert a new record into the 0Persons0 table. The 0P#(d0 column would be assigned the ne>t number from the seF#person seFuence. The 0&irst ame0 column would be set to 0Lars0 and the 0Last ame0 column would be set to 0'onsen0.

SQL (iews
@ view is a virtual table. This chapter shows how to create? update? and delete a view.

SQL CRE+TE 9IE" Statement


(n SQL? a view is a virtual table based on the result:set of an SQL statement. @ view contains rows and columns? Kust li;e a real table. The fields in a view are fields from one or more real tables in the database. Hou can add SQL functions? +,!R!? and JO( data were coming from one single table. statements to a view and present the data as if the

SQL CRE+TE 9IE" Syntax


CR!@T! 9(!+ view#name @S S!L!CT column#name$s% &RO' table#name +,!R! condition Note: @ view always shows up:to:date dataE The database engine recreates the data? using the view=s SQL statement? every time a user Fueries a view.

SQL CRE+TE 9IE" Examples


(f you have the orthwind database you can see that it has several views installed by default.

The view 0Current Product List0 lists all active products $products that are not discontinued% from the 0Products0 table. The view is created with the following SQL1 CR!@T! 9(!+ BCurrent Product ListC @S S!L!CT Product(G?Product ame &RO' Products +,!R! Giscontinued/ o +e can Fuery the view above as follows1 S!L!CT ) &RO' BCurrent Product ListC @nother view in the orthwind sample database selects every product in the 0Products0 table with a unit price higher than the average unit price1 CR!@T! 9(!+ BProducts @bove @verage PriceC @S S!L!CT Product ame?-nitPrice &RO' Products +,!R! -nitPriceR$S!L!CT @9P$-nitPrice% &RO' Products% +e can Fuery the view above as follows1 S!L!CT ) &RO' BProducts @bove @verage PriceC @nother view in the orthwind database calculates the total sale for each category in 2NNL. this view selects its data from another view called 0Product Sales for 2NNL01 CR!@T! 9(!+ BCategory Sales &or 2NNLC @S S!L!CT G(ST( CT Category ame?Sum$ProductSales% @S CategorySales &RO' BProduct Sales for 2NNLC PRO-P 5H Category ame +e can Fuery the view above as follows1 S!L!CT ) &RO' BCategory Sales &or 2NNLC +e can also add a condition to the Fuery. 05everages01 S!L!CT ) &RO' BCategory Sales &or 2NNLC +,!R! Category ame/=5everages= ow we want to see the total sale only for the category ote that

SQL #pdatin$ a 9ie0


Hou can update a view by using the following synta>1

SQL CRE+TE OR REPL+CE 9IE" Syntax


CR!@T! OR R!PL@C! 9(!+ view#name @S S!L!CT column#name$s% &RO' table#name +,!R! condition ow we want to add the 0Category0 column to the 0Current Product List0 view. +e will update the view with the following SQL1 CR!@T! 9(!+ BCurrent Product ListC @S S!L!CT Product(G?Product ame?Category &RO' Products +,!R! Giscontinued/ o

SQL /r!ppin$ a 9ie0


Hou can delete a view with the GROP 9(!+ command.

SQL /ROP 9IE" Syntax


GROP 9(!+ view#name

SQL Gate &unctions


SQL /ates
The most difficult part when wor;ing with dates is to be sure that the format of the date you are trying to insert? matches the format of the date column in the database. @s long as your data contains only the date portion? your Fueries will wor; as e>pected. ,owever? if a time portion is involved? it gets complicated. 5efore tal;ing about the complications of Fuerying for dates? we will loo; at the most important built: in functions for wor;ing with dates.

MySQL /ate 1uncti!ns


The following table lists the most important built:in date functions in 'ySQL1 F(nction NO)*+ UR"&TE*+ URTI,E*+ "&TE*+ E$TR& T*+ "&TE-&""*+ "&TE-SU'*+ "&TE"I..*+ "&TE-.OR,&T*+ Description Returns the current date and time Returns the current date Returns the current time !>tracts the date part of a date or dateStime e>pression Returns a single part of a dateStime @dds a specified time interval to a date Subtracts a specified time interval from a date Returns the number of days between two dates Gisplays dateStime data in different formats

SQL Server /ate 1uncti!ns


The following table lists the most important built:in date functions in SQL Server1 F(nction GET"&TE*+ "&TE#&RT*+ "&TE&""*+ "&TE"I..*+ ON(ERT*+ Description Returns the current date and time Returns a single part of a dateStime @dds or subtracts a specified time interval from a date Returns the time between two dates Gisplays dateStime data in different formats

SQL /ate /ata Types


)y#,L comes with the following data types for storing a date or a dateStime value in the database1

G@T! : format HHHH:'':GG

G@T!T('! : format1 HHHH:'':GG ,,1''1SS T('!ST@'P : format1 HHHH:'':GG ,,1''1SS H!@R : format HHHH or HH

#,L #er-er comes with the following data types for storing a date or a dateStime value in the database1

G@T! : format HHHH:'':GG G@T!T('! : format1 HHHH:'':GG ,,1''1SS S'@LLG@T!T('! : format1 HHHH:'':GG ,,1''1SS T('!ST@'P : format1 a uniFue number

Note: The date types are chosen for a column when you create a new table in your databaseE &or an overview of all data types available? go to our complete Gata Types reference.

SQL "!r:in$ 0ith /ates


Hou can compare two dates easily if there is no time component involvedE @ssume we have the following 0Orders0 table1 OrderId 2 4 6 8 Prod(ctName Peitost Camembert Pierrot 'oAAarella di Piovanni 'ascarpone &abioli OrderDate 433M:22:22 433M:22:3N 433M:22:22 433M:23:4N

ow we want to select the records with an OrderGate of 0433M:22:220 from the table above. +e use the following S!L!CT statement1 S!L!CT ) &RO' Orders +,!R! OrderGate/=433M:22:22= The result:set will loo; li;e this1 OrderId 2 6 Prod(ctName Peitost 'oAAarella di Piovanni OrderDate 433M:22:22 433M:22:22

ow? assume that the 0Orders0 table loo;s li;e this $notice the time component in the 0OrderGate0 column%1 OrderId 2 4 6 8 Prod(ctName Peitost Camembert Pierrot 'oAAarella di Piovanni 'ascarpone &abioli OrderDate 433M:22:22 26146188 433M:22:3N 2*18*142 433M:22:22 22124132 433M:23:4N 281*O1*N

(f we use the same S!L!CT statement as above1 S!L!CT ) &RO' Orders +,!R! OrderGate/=433M:22:22= we will get no resultE This is because the Fuery is loo;ing only for dates with no time portion.

Tip: (f you want to ;eep your Fueries simple and easy to maintain? do not allow time components in your datesE

SQL

-LL 9alues
-LL values. OT -LL operators. -LL and (S

-LL values represent missing un;nown data. 5y default? a table column can hold This chapter will e>plain the (S

SQL N#LL 9alues


(f a column in a table is optional? we can insert a new record or update an e>isting record without adding a value to this column. This means that the field will be saved with a -LL value. -LL values are treated differently from other values. -LL is used as a placeholder for un;nown or inapplicable values. Note: (t is not possible to compare -LL and 3I they are not eFuivalent.

SQL "!r:in$ 0ith N#LL 9alues


Loo; at the following 0Persons0 table1 P_Id 2 4 6 LastName ,ansen Svendson Pettersen FirstName Ola Tove 7ari 5orgvn 46 Address City Sandnes Sandnes Stavanger

Suppose that the 0@ddress0 column in the 0Persons0 table is optional. This means that if we insert a record with no value for the 0@ddress0 column? the 0@ddress0 column will be saved with a -LL value. ,ow can we test for -LL valuesT -LL values with comparison operators? such as /? .? or .R. -LL and (S OT -LL operators instead.

(t is not possible to test for +e will have to use the (S

SQL IS N#LL
,ow do we select only the records with +e will have to use the (S -LL values in the 0@ddress0 columnT -LL operator1

S!L!CT Last ame?&irst ame?@ddress &RO' Persons +,!R! @ddress (S -LL The result:set will loo; li;e this1 LastName ,ansen Pettersen Tip: @lways use (S FirstName Ola 7ari -LL to loo; for -LL values. Address

SQL IS NOT N#LL


,ow do we select only the records with no +e will have to use the (S OT -LL values in the 0@ddress0 columnT -LL operator1

S!L!CT Last ame?&irst ame?@ddress &RO' Persons +,!R! @ddress (S OT -LL

The result:set will loo; li;e this1 LastName Svendson FirstName Tove Address 5orgvn 46

SQL

-LL &unctions

SQL ISN#LL;<= N9L;<= I1N#LL;< and CO+LESCE;< 1uncti!ns


Loo; at the following 0Products0 table1 P_Id 2 4 6 Prod(ctName Jarlsberg 'ascarpone PorgonAola "nitPrice 23.8* 64.*O 2*.OL "nitsIn#toc* 2O 46 N 43 -LL values. "nitsOnOrder 2*

Suppose that the 0-nitsOnOrder0 column is optional? and may contain +e have the following S!L!CT statement1 S!L!CT Product ame?-nitPrice)$-nits(nStoc;U-nitsOnOrder% &RO' Products (n the e>ample above? if any of the 0-nitsOnOrder0 values are

-LL? the result is -LL values.

-LL.

'icrosoft=s (S -LL$% function is used to specify how we want to treat The

9L$%? (& -LL$%? and CO@L!SC!$% functions can also be used to achieve the same result. -LL values to be Aero. -LL it will not harm the calculation? because (S -LL$% returns a Aero if

(n this case we want

5elow? if 0-nitsOnOrder0 is the value is -LL1 #,L #er-er . )# Access

S!L!CT Product ame?-nitPrice)$-nits(nStoc;U(S -LL$-nitsOnOrder?3%% &RO' Products Oracle Oracle does not have an (S -LL$% function. ,owever? we can use the same result1 S!L!CT Product ame?-nitPrice)$-nits(nStoc;U 9L$-nitsOnOrder?3%% &RO' Products )y#,L 'ySQL does have an (S -LL$% function. ,owever? it wor;s a little bit different from 'icrosoft=s (S -LL$% function. (n 'ySQL we can use the (& -LL$% function? li;e this1 S!L!CT Product ame?-nitPrice)$-nits(nStoc;U(& -LL$-nitsOnOrder?3%% &RO' Products or we can use the CO@L!SC!$% function? li;e this1 S!L!CT Product ame?-nitPrice)$-nits(nStoc;UCO@L!SC!$-nitsOnOrder?3%% 9L$% function to achieve the

SQL Gata Types

Gata types and ranges for 'icrosoft @ccess? 'ySQL and SQL Server.

Micr!s!,t +ccess /ata Types


Data type Te>t Description -se for te>t or combinations of te>t and numbers. 4** characters ma>imum 'emo is used for larger amounts of te>t. Stores up to O*?*6O characters. Note: Hou cannot sort a memo field. ,owever? they are searchable @llows whole numbers from 3 to 4** @llows whole numbers between :64?LOM and 64?LOL @llows whole numbers between :4?28L?8M6?O8M and 4?28L?8M6?O8L Single precision floating:point. +ill handle most decimals Gouble precision floating:point. +ill handle most decimals -se for currency. ,olds up to 2* digits of whole dollars? plus 8 decimal places. Tip: Hou can choose which country=s currency to use @uto umber fields automatically give each record its own number? usually starting at 2 -se for dates and times 2 byte 4 bytes 8 bytes 8 bytes M bytes M bytes #tora/e

'emo

5yte (nteger Long Single Gouble Currency

@uto umber

8 bytes

GateSTime HesS o

M bytes

@ logical field can be displayed as HesS o? TrueS&alse? or OnSOff. (n 2 bit code? use the constants True and &alse $eFuivalent to :2 and 3%. Note: ull values are not allowed in HesS o fields Can store pictures? audio? video? or other 5LO5s $5inary Large O5Kects% up to 2P5 Contain lin;s to other files? including web pages Let you type a list of options? which can then be chosen from a drop: down list 8 bytes

Ole ObKect ,yperlin; Loo;up +iAard

MySQL /ata Types


(n 'ySQL there are three main types 1 te>t? number? and GateSTime types. Te0t types: Data type C,@R$siAe% Description ,olds a fi>ed length string $can contain letters? numbers? and special characters%. The fi>ed siAe is specified in parenthesis. Can store up to 4** characters ,olds a variable length string $can contain letters? numbers? and special characters%. The ma>imum siAe is specified in parenthesis. Can store up to 4** characters. Note: (f you put a greater value than 4** it will be converted to a T!QT type ,olds a string with a ma>imum length of 4** characters ,olds a string with a ma>imum length of O*?*6* characters &or 5LO5s $5inary Large O5Kects%. ,olds up to O*?*6* bytes of data

9@RC,@R$siAe%

T( HT!QT T!QT 5LO5

'!G(-'T!QT '!G(-'5LO5 LO PT!QT LO P5LO5 ! -'$>?y?A?etc.%

,olds a string with a ma>imum length of 2O?LLL?42* characters &or 5LO5s $5inary Large O5Kects%. ,olds up to 2O?LLL?42* bytes of data ,olds a string with a ma>imum length of 8?4N8?NOL?4N* characters &or 5LO5s $5inary Large O5Kects%. ,olds up to 8?4N8?NOL?4N* bytes of data Let you enter a list of possible values. Hou can list up to O**6* values in an ! -' list. (f a value is inserted that is not in the list? a blan; value will be inserted. Note: The values are sorted in the order you enter them. Hou enter the possible values in this format1 ! -'$=Q=?=H=?=V=%

S!T

Similar to ! -' e>cept that S!T may contain up to O8 list items and can store more than one choice

N(m1er types: Data type T( H( T$siAe% Description :24M to 24L normal. 3 to 4** - S(P !G). The ma>imum number of digits may be specified in parenthesis :64LOM to 64LOL normal. 3 to O**6* - S(P !G). The ma>imum number of digits may be specified in parenthesis :M6MMO3M to M6MMO3L normal. 3 to 2OLLL42* - S(P !G). The ma>imum number of digits may be specified in parenthesis :428L8M6O8M to 428L8M6O8L normal. 3 to 84N8NOL4N* - S(P !G). The ma>imum number of digits may be specified in parenthesis :N4466L436OM*8LL*M3M to N4466L436OM*8LL*M3L normal. 3 to 2M88OL883L6L3N**2O2* - S(P !G). The ma>imum number of digits may be specified in parenthesis @ small number with a floating decimal point. The ma>imum number of digits may be specified in the siAe parameter. The ma>imum number of digits to the right of the decimal point is specified in the d parameter @ large number with a floating decimal point. The ma>imum number of digits may be specified in the siAe parameter. The ma>imum number of digits to the right of the decimal point is specified in the d parameter @ GO-5L! stored as a string ? allowing for a fi>ed decimal point. The ma>imum number of digits may be specified in the siAe parameter. The ma>imum number of digits to the right of the decimal point is specified in the d parameter

S'@LL( T$siAe%

'!G(-'( T$siAe%

( T$siAe%

5(P( T$siAe%

&LO@T$siAe?d%

GO-5L!$siAe?d%

G!C('@L$siAe?d%

)The integer types have an e>tra option called - S(P !G. ormally? the integer goes from an negative to positive value. @dding the - S(P !G attribute will move that range up so it starts at Aero instead of a negative number. Date types: Data type G@T!$% Description @ date. &ormat1 HHHH:'':GG Note: The supported range is from =2333:32:32= to =NNNN:24:62= G@T!T('!$% )@ date and time combination. &ormat1 HHHH:'':GG ,,1''1SS

Note: The supported range is from =2333:32:32 33133133= to =NNNN:24:62 461*N1*N= T('!ST@'P$% )@ timestamp. T('!ST@'P values are stored as the number of seconds since the -ni> epoch $=2NL3:32:32 33133133= -TC%. &ormat1 HHHH:'':GG ,,1''1SS Note: The supported range is from =2NL3:32:32 33133132= -TC to =436M:32:3N 3612813L= -TC T('!$% @ time. &ormat1 ,,1''1SS Note: The supported range is from =:M6M1*N1*N= to =M6M1*N1*N= H!@R$% @ year in two:digit or four:digit format. Note: 9alues allowed in four:digit format1 2N32 to 42**. 9alues allowed in two: digit format1 L3 to ON? representing years from 2NL3 to 43ON )!ven if G@T!T('! and T('!ST@'P return the same format? they wor; very differently. (n an ( S!RT or -PG@T! Fuery? the T('!ST@'P automatically set itself to the current date and time. T('!ST@'P also accepts various formats? li;e HHHH''GG,,''SS? HH''GG,,''SS? HHHH''GG? or HH''GG.

SQL Server /ata Types


C&aracter strin/s: Data type char$n% varchar$n% varchar$ma>% te>t "nicode strin/s: Data type nchar$n% nvarchar$n% nvarchar$ma>% nte>t +inary types: Data type bit binary$n% varbinary$n% varbinary$ma>% image N(m1er types: Description @llows 3? 2? or -LL #tora/e Description &i>ed:length -nicode data. 'a>imum 8?333 characters 9ariable:length -nicode data. 'a>imum 8?333 characters 9ariable:length -nicode data. 'a>imum *6O?ML3?N24 characters 9ariable:length -nicode data. 'a>imum 4P5 of te>t data #tora/e Description &i>ed:length character string. 'a>imum M?333 characters 9ariable:length character string. 'a>imum M?333 characters 9ariable:length character string. 'a>imum 2?3L6?L82?M48 characters 9ariable:length character string. 'a>imum 4P5 of te>t data #tora/e n

&i>ed:length binary data. 'a>imum M?333 bytes 9ariable:length binary data. 'a>imum M?333 bytes 9ariable:length binary data. 'a>imum 4P5 9ariable:length binary data. 'a>imum 4P5

Data type tinyint smallint int bigint

Description @llows whole numbers from 3 to 4** @llows whole numbers between :64?LOM and 64?LOL @llows whole numbers between :4?28L?8M6?O8M and 4?28L?8M6?O8L @llows whole numbers between :N?446?6L4?36O?M*8?LL*?M3M and N?446?6L4?36O?M*8?LL*?M3L &i>ed precision and scale numbers. @llows numbers from :23D6M U2 to 23D6M W2. The p parameter indicates the ma>imum total number of digits that can be stored $both to the left and to the right of the decimal point%. p must be a value from 2 to 6M. Gefault is 2M. The s parameter indicates the ma>imum number of digits stored to the right of the decimal point. s must be a value from 3 to p. Gefault value is 3

#tora/e 2 byte 4 bytes 8 bytes M bytes

decimal$p?s%

*:2L bytes

numeric$p?s%

&i>ed precision and scale numbers. @llows numbers from :23D6M U2 to 23D6M W2. The p parameter indicates the ma>imum total number of digits that can be stored $both to the left and to the right of the decimal point%. p must be a value from 2 to 6M. Gefault is 2M. The s parameter indicates the ma>imum number of digits stored to the right of the decimal point. s must be a value from 3 to p. Gefault value is 3

*:2L bytes

smallmoney money

'onetary data from :428?L8M.6O8M to 428?L8M.6O8L 'onetary data from :N44?66L?436?OM*?8LL.*M3M to N44?66L?436?OM*?8LL.*M3L &loating precision number data from :2.LN! U 63M to 2.LN! U 63M. The n parameter indicates whether the field should hold 8 or M bytes. float$48% holds a 8:byte field and float$*6% holds an M:byte field. Gefault value of n is *6.

8 bytes M bytes

float$n%

8 or M bytes

real Date types: Data type datetime

&loating precision number data from :6.83! U 6M to 6.83! U 6M

8 bytes

Description &rom January 2? 2L*6 to Gecember 62? NNNN with an accuracy of 6.66 milliseconds &rom January 2? 3332 to Gecember 62? NNNN with an accuracy of 233 nanoseconds &rom January 2? 2N33 to June O? 43LN with an accuracy of 2 minute Store a date only. &rom January 2? 3332 to Gecember 62? NNNN Store a time only to an accuracy of 233 nanoseconds The same as datetime4 with the addition of a time Aone offset

#tora/e M bytes

datetime4

O:M bytes

smalldatetime date time datetimeoffset

8 bytes 6 bytes 6:* bytes M:23 bytes

timestamp

Stores a uniFue number that gets updated every time a row gets created or modified. The timestamp value is based upon an internal cloc; and does not correspond to real time. !ach table may have only one timestamp variable

Ot&er data types: Data type sFl#variant Description Stores up to M?333 bytes of data of various data types? e>cept te>t? nte>t? and timestamp Stores a globally uniFue identifier $P-(G% Stores Q'L formatted data. 'a>imum 4P5 Stores a reference to a cursor used for database operations Stores a result:set for later processing

uniFueidentifier >ml cursor table

Potrebbero piacerti anche