You are on page 1of 50

SQL, the Structured

Query Language

Structured Query Language
(SQL)

The ANSI standard language for the definition
and manipulation of relational database.
Includes data definition language (DDL),
statements that specify and modify database
schemas.
Includes a data manipulation language (DML),
statements that manipulate database content.

Some Facts on SQL
SQL data is case-sensitive, SQL commands are not.
First Version was developed at IBM by Donald D.
Chamberlin and Raymond F. Boyce. [SQL]
SQL query includes references to tuples variables
and the attributes of those variables

Introduction to SQL Server
System
Every SQL Server relies on four primary
system databases, each of which must
be present for the server to operate
effectively

Master database
The master database stores basic
configuration information for the
server. This includes information about
the file locations of the user databases,
as well as logon accounts, server
configuration settings, and a number of
other items such as linked servers and
startup stored procedures

Model Database The model database is a template database that is copied into a new database whenever it is created on the instance.   Database options set in model will be applied to new databases created on the instance. .

including the SQL Server Agent. and Service Broker.Msdb database The msdb database is used to support a number of technologies within SQL Server. Database Mail. SQL Server Management Studio.  .

including the backup and restore history for the databases on the server .Msdb database A great deal of history and metadata information is available in msdb.

online index operations. cursors. table variables .Tempdb The tempdb system databases is a shared temporary storage resource used by a number of features of SQL Server. and made available to all users. worktables.  Tempdb is used for temporary objects.

which means that no objects in tempdb are permanently stored. .Tempdb It is recreated every time that the server is restarted.

DROP TABLE: removes a table from a database.SQL: DDL Commands CREATE TABLE: used to create a table. ALTER TABLE: modifies a table after it was created. .

SQL: CREATE TABLE Statement Things to consider before you create your table are: The type of data the table name what column(s) will make up the primary key the names of the columns CREATE TABLE statement syntax: CREATE TABLE <table name> ( field1 datatype ( NOT NULL ). field2 datatype ( NOT NULL ) ). .

SQL: Attributes Types .

. ALTER TABLE statement syntax: ALTER TABLE <table name> ADD attr datatype. or DROP COLUMN attr.SQL: ALTER TABLE Statement To add or drop columns on existing tables.

. RESTRICT: blocks the deletion of the table of any foreign key constraint violations would be created. DROP TABLE statement syntax: DROP TABLE <table name> [ RESTRICT|CASCADE ].SQL: DROP TABLE Statement Has two options: CASCADE: Specifies that any foreign key constraint violations that are caused by dropping the table will cause the corresponding rows of the related table to be deleted.

ALTER TABLE FoodCart ( ADD sold int ). DROP TABLE FoodCart.Example: CREATE TABLE FoodCart ( date varchar(10). food varchar(20). profit float ). ALTER TABLE FoodCart( DROP COLUMN profit ). FoodCart date food profit FoodCart date food profit sold FoodCart date food sold .

DELETE: deletes one or more rows from a table. UPDATE: modifies one or more attributes.SQL: DML Commands INSERT: adds new rows to a table. .

and order matters. NULL). INSERT statement syntax: INSERT into <table name> VALUES ('value1'. Example: INSERT into FoodCart VALUES (’02/26/08'. ‘pizza'. 'value2'. 70 ). FoodCart date food sold 02/25/08 pizza 350 02/26/08 hotdog 500 date 02/25/08 02/26/08 02/26/08 food pizza hotdog pizza sold 350 500 70 .SQL: INSERT Statement To insert a row into a table. it is necessary to have a value for each attribute.

Example: UPDATE FoodCart SET sold = 349 WHERE date = ’02/25/08’ AND food = ‘pizza’. FoodCart date 02/25/08 02/26/08 02/26/08 food pizza hotdog pizza sold 350 500 70 date 02/25/08 02/26/08 02/26/08 food pizza hotdog pizza sold 349 500 70 .SQL: UPDATE Statement To update the content of the table: UPDATE statement syntax: UPDATE <table name> SET <attr> = <value> WHERE <selection condition>.

. Example: DELETE FROM FoodCart WHERE food = ‘hotdog’. FoodCart date 02/25/08 02/26/08 02/26/08 food pizza hotdog pizza sold 349 500 70 date food 02/25/08 pizza 02/26/08 pizza sold 349 70 Note: If the WHERE clause is omitted all rows of data are deleted from the table.SQL: DELETE Statement To delete rows from the table: DELETE statement syntax: DELETE FROM <table name> WHERE <condition>.

SQL Constraints .

Constraints  Database constraints are restrictions on the contents of the database or on database operations  Database constraints provide a way to guarantee that:  rows in a table have valid primary or unique key values  rows in a dependent table have valid foreign key values that reference rows in a parent table  individual column values are valid .

or referential integrity)  check constraint (to restrict a column's values. a partial enforcement of domain integrity)  You specify one or more of these constraints when you use the Create Table statement to create a base table.Database Constraints  SQL/400 constraints cover four specific integrity rules:  primary key constraint (to enforce existence integrity)  unique constraint (to enforce candidate key integrity)  foreign key constraint (to enforce foreign key.  You can also add or drop constraints with the Alter Table statement. .

2 ) Not Null. SaleTot Dec( 7. ShipDate Date Default Null. Constraint SaleShipDateChk Check( ShipDate Is Null Or ShipDate >= SaleDate ) ) . Not Null. Constraint SaleCustomerFK Foreign Key ( CustID ) References Customer ( CustID ) On Delete Cascade On Update Restrict. Constraint SaleCrdAutNbrUK Unique ( CrdAutNbr ). 0 ) Not Null Constraint SaleOrderIdChk Check( OrderID > 0 ). SaleDate Date Not Null. 0 ) Default Null. CrdAutNbr Int CustID Dec( 7. Primary Key( OrderID ).Create Table Sale ( OrderID Dec( 7.

 For a table with a primary key constraint.  The syntax of the primary key constraint (following the Constraint keyword and the constraint name. . )  Each primary key column's definition must include Not Null. UDB/400 blocks any attempt to insert or update a row that would cause two rows in the same table to have identical value(s) for their primary key column(s).Primary Key Constraints  A primary key serves as the unique identifier for rows in the table. ..  A table definition can have no more than one primary key constraint.. if they're specified) is  Primary Key( column-name.

 The SaleCrdAutNbrUK unique constraint specifies that any non-null value for the CrdAutNbr column must be unique. .  Recommend  always specify a constraint name for a unique constraint:  Constraint constraint-name Unique ( column-name. those paid by cash) may exist without a credit authorization number. )  Note that a unique constraint does not use the Key keyword.  Allowing the CrdAutNbr column to be null and specifying the SaleCrdAutNbrUK constraint together enforce a business rule that some orders (e. ..g. as do primary key and foreign key constraints. but any order that does have a credit authorization number must have a unique value.Unique Constraints  A unique constraint is similar to a primary key constraint doesn't have to be defined with Not Null...

delete. Although it might be valid for a customer row to exist without any corresponding sale rows. the referenced table). . A foreign key is one or more columns that contain a value identical to a primary key (or unique key) value in some row in the parent table (i.. it would normally be invalid for a sale row not to have a reference to a valid customer.Foreign Key Constraints  A foreign key constraint specifies how records in different tables are related and how UDB/400 should handle row insert. the relationship between rows in two tables is expressed by a foreign key in the dependent table.e.  For example. sales rows are generally related to the customers who place the orders.  With a relational DBMS. and update operations that might violate the relationship.

 Within SQL we might create the Customer and Sale tables so they have the following partial constraint definitions:  Customer table (parent)   Primary key column: CustID Sale table (dependent)  Primary key column: OrderID  Foreign key column: CustID  For each row in the Sale table. the CustID column should contain the same value as the CustID column of some Customer row because this value tells which customer placed the order. .  The purpose of specifying a foreign key constraint is to have UDB/400 ensure that the Sale table never has a row with a (non-null) value in the CustID column that has no matching Customer row.

The Sale table's foreign key constraint. . which is Constraint SaleCustomerFK References Customer Foreign Key ( CustID ) ( CustID ) On Delete Cascade On Update Restrict  Specifies that the CustID column in the Sale table is a foreign key that references the CustID primary key column in the Customer table.  Blocks any attempt to change the CustID column of a row in the Sale table to a value that doesn't exist in any row in the Customer table. [a new or updated Sale row must have a parent Customer row].Foreign Key Constraints cont.

other column definitions . 0 ) Not Null. Dec ( 7. Constraint EmpMgrFK References Employee On Update Restrict On Delete Restrict ) Foreign Key ( MgrEmpID ) ( EmpID ) . : Create Table Employee ( EmpID MgrEmpID Dec ( 7.. . Suppose you have an Employee table with an EmpID primary key column and a MgrEmpID column that holds the employee ID for the person's manager. Primary Key ( EmpID )..A foreign key constraint can specify the same table for the dependent and parent tables. 0 ) Not Null.

Check Constraints  Used to enforce the validity of column values. to another column in the same table (such as in the second example).g.e.. . ColA + 3). or to an expression (e. meaning "unknown") or the ship date is on or after the sale date]. the ShipDate column is null.  A check constraint can compare a column to a constant (such as in the first example).  Constraint SaleOrderIdChk Check( OrderID > 0 ) [guarantees that the OrderID primary key column is always greater than zero]  Constraint SaleShipDateChk Check( ShipDate Is Null Or ShipDate >= SaleDate ) [guarantees that either a row has no ship date (i..

You can combine check constraints for more than one column into a single check constraint.check constraints cont. as in the following example: Constraint CustStatusNameChk Check ( ( Status = 'A' Or Status = 'I' And Name <> ' ' ( )) ) .

foreign key. just specify the Primary Key keywords: Alter Table Sale Drop Primary Key . you can use the Alter Table statement to  add or remove a primary key. unique.Add/Remove Constraints  After you create a table. or check constraint  To drop a table's primary key constraint.

Add/Remove Constraints  To drop a unique. you must specify the constraint name: Alter Table Sale Drop Constraint SaleCustomerFK  To add a new constraint. use the same constraint syntax as in a Create Table statement: Alter Table Sale Add Constraint SaleSaleTotChk Check( SaleTot >= 0 ) . foreign key. or check constraint.

SQL Statements. Clauses SQL Statements: Select SQL Operations: Join Left Join Right Join Like SQL Clauses: Order By Group By Having . Operations.

Note: that you don't need to use WHERE .SQL: SELECT Statement A basic SELECT statement includes 3 clauses SELECT <attribute name> FROM <tables> WHERE <condition> SELECT FROM WHERE Specifies the attributes that are part of the resulting relation Specifies the tables that serve as the input to the statement Specifies the selection condition. including the join condition.

SQL: SELECT Statement (cont. To get unique rows. type the keyword DISTINCT after SELECT. . Example: SELECT * FROM … WHERE ….) Using a “*” in a select statement indicates that every attribute of the input table is to be selected. Example: SELECT DISTINCT * FROM … WHERE ….

3) SELECT distinct weight FROM person WHERE age > 30. Weight Weight 80 80 54 54 80 . Name Age Weight Harry 34 80 Name Age Weight Sally 28 64 Harry 34 80 George 29 70 Helena 54 54 Helena 54 54 Peter 34 80 Peter 34 80 2) SELECT weight FROM person WHERE age > 30.Example: Person 1) SELECT * FROM person WHERE age > 30.

SQL: Join operation A join can be specified in the FROM clause which list the two input relations and the WHERE clause which lists the join condition. Example: Emp ID 1000 1001 1002 Dept State CA MA TN ID 1001 1002 1003 Division IT Sales Biotech .

) inner join = join SELECT * FROM emp join dept (or FROM emp.ID Dept.ID Emp. Emp.id = dept.Division 1001 MA 1001 IT 1002 TN 1002 Sales .SQL: Join operation (cont. dept) on emp.State Dept.id.

State CA MA TN Dept. Emp.ID 1000 1001 1002 Emp.SQL: Join operation (cont.) left outer join = left join SELECT * FROM emp left join dept on emp.ID null 1001 1002 Dept.Division null IT Sales .id = dept.id.

SQL: Join operation (cont.id.Division IT Sales Biotech .ID 1001 1002 1003 Dept. Emp.State MA TN null Dept.id = dept.ID 1001 1002 null Emp.) right outer join = right join SELECT * FROM emp right join dept on emp.

etc _ (a single character) SELECT * FROM emp WHERE ID like ‘_01_’.g.  finds ID that ends with 01.g. 1013.  finds ID that has the second and third character as 01. 2001. 1001. etc . e. e.SQL: Like operation Pattern matching selection % (arbitrary string) SELECT * FROM emp WHERE ID like ‘%01’. 1011. 1012. 1010.

1003 . e.g. 1002. e. MA. TN.SQL: The ORDER BY Clause Ordered result selection desc (descending order) SELECT * FROM emp order by state desc  puts state in descending order.g. 1001. CA asc (ascending order) SELECT * FROM emp order by id asc  puts ID in ascending order.

FoodCart date 02/25/08 02/26/08 02/26/08 food pizza hotdog pizza sold 349 500 70 food totalSold hotdog 500 pizza 419 . Usually. sum(sold) as totalSold FROM FoodCart group by food. it is an aggregate function’s companion SELECT food.SQL: The GROUP BY Clause The function to divide the tuples into groups and returns an aggregate for each group.

sum(sold) as totalSold FROM FoodCart group by food having sum(sold) > 450. it is an aggregate function’s companion SELECT food. FoodCart date 02/25/08 02/26/08 02/26/08 food pizza hotdog pizza sold 349 500 70 food totalSold hotdog 500 .SQL: The HAVING Clause The substitute of WHERE for aggregate functions Usually.

SQL: Aggregate Functions Are used to provide summarization information for SQL statements. . except in COUNT(*) . NULL values are not considered. which return a single value. COUNT(attr) SUM(attr) MAX(attr) MIN(attr) AVG(attr) Note: when using aggregate functions.

-> 919 MAX(attr) -> return the highest value from the attr Ex: MAX(sold) from FoodCart. -> 2 SUM(attr) -> return the sum of values in the attr Ex: SUM(sold) from FoodCart.SQL: Aggregate Functions (cont. -> 500 .) FoodCart date 02/25/08 02/26/08 02/26/08 food pizza hotdog pizza sold 349 500 70 COUNT(attr) -> return # of rows that are not null Ex: COUNT(distinct food) from FoodCart.

SQL: Aggregate Functions (cont. -> 70 AVG(attr) -> return the average value from the attr Ex: AVG(sold) from FoodCart.33 Note: value is rounded to the precision of the datatype .) FoodCart date 02/25/08 02/26/08 02/26/08 food pizza hotdog pizza sold 349 500 70 MIN(attr) -> return the lowest value from the attr Ex: MIN(sold) from FoodCart. -> 306.

Thanks .