SQL Programming Overview
January 23, 2009
Goals/ObjectivesGoals/Objectives
Gain an understanding of:
◦ SQL Programming including database structures,
manipulation o...
AgendaAgenda
History of SQL
SQL Fundamentals
Data Definition
Data Modifications
SingleTable SELECT StatementsSingleTable S...
History of SQLHistory of SQL
During the 1970s, a group at IBM San Jose Research Laboratory
developed the System R relation...
History of SQL (cont’d)History of SQL (cont’d)
SQL was adopted as a standard by ANSI in 1986 and ISO in 1987. In the origi...
SQL FundamentalsSQL Fundamentals
SQL is the only way to build, manipulate and access a relational
database
Table
◦ Columns...
SQL Server BasicsSQL Server Basics
Keywords are not case sensitive
Table and column names are stored as they are entered a...
Data DefinitionData Definition
Data Types
◦ Each database column has to have a valid data type
◦ Data types are only parti...
Data Definition (cont’d)Data Definition (cont’d)
DROPTables
◦ DROPTABLE Divisions;
Constraints are used to enforce valid d...
Data ModificationData Modification
INSERT
◦ Adds new rows to a table
INSERT INTO Departments
(DivisionID, DepartmentID, De...
Data Modification (cont’d)Data Modification (cont’d)
TRANSACTIONS
◦ A set of INSERT/UPDATE/DELETE operations that belong
t...
Single Table SELECT StatementsSingle Table SELECT Statements
The SELECT statement retrieves data from database tables
SELE...
Single Table SELECT StatementsSingle Table SELECT Statements (cont’d)(cont’d)
TheWHERE clause specifies a filter condition...
Single Table SELECT StatementsSingle Table SELECT Statements (cont’d)(cont’d)
The ORDER BY statement defines the sort orde...
Single Table SELECT StatementsSingle Table SELECT Statements (cont’d)(cont’d)
NULL means unknown or missing value
◦ NULL i...
Joins (INNER)Joins (INNER)
Joins are used to combine information from multiple tables
Basic Syntax of an INNER Join (exclu...
Joins (INNER)Joins (INNER)
SELECT column_name(s)
FROM table_name1 JOIN table_name2
ON table_name1.column_name=table_name2....
Joins (OUTER)Joins (OUTER)
Joins are used to combine information from multiple tables
Basic Syntax of an OUTER Join (inclu...
Joins (CROSS)Joins (CROSS)
Each row in one table is paired to every row in the other table
A cross join is also called a c...
Joins (OUTER)Joins (OUTER)
table1 LEFT OUTER JOIN table2 – all rows from table 1 will be included
table1 RIGHT OUTER JOIN ...
Set OperatorsSet Operators
UNION, INTERSECT and EXCEPT
UNIONUNION
SELECT zip FROM hotel.customerWHERE zip > '90000'
UNION
...
Set OperatorsSet Operators
UNION, INTERSECT and EXCEPT
INTERSECT
SELECT zip FROM hotel.customerWHERE zip < '30000'SELECT z...
Row FunctionsRow Functions
Row functions take input parameters and return a value
◦ Math Functions
◦ String Functions
◦ Da...
Row FunctionsRow Functions -- MathMath
ABS
DEGREES
RAND
ACOS
EXP
ROUND
ASIN
LOG
SIN
ATN2
LOG10
SQRT
CEILINGASIN
FLOOR
SIGN...
Row FunctionsRow Functions -- StringString
ASCII
NCHAR
SOUNDEX
CHAR
PATINDEX
SPACE
CHARINDEX
DIFFERENCE
REPLACE
STUFF
LEFT...
Row FunctionsRow Functions –– Date & TimeDate & Time
DATEADD
DATEDIFF
DATENAME
DATEPART
DAY
GETDATEGETDATE
GETUTCDATE
MONT...
bigint
numeric
bit
smallint
decimal
smallmoney
Row FunctionsRow Functions –– Data TypeData Type
datetime2
smalldatetime
da...
Row FunctionsRow Functions -- CaseCase
The CASE expression enables many forms of conditional processing to be
placed into ...
Row FunctionsRow Functions -- NullNull
A null value in an expression causes the result of the expression to be
null
Testin...
Aggregate FunctionsAggregate Functions
SUM AVG MAX MIN COUNT
SELECT AVG(UnitPrice * Quantity) As AveragePrice
FROMWidgetOr...
Aggregate FunctionsAggregate Functions –– GROUP BYGROUP BY
The GROUP BY statement is used in conjunction with the aggregat...
Aggregate FunctionsAggregate Functions –– HAVINGHAVING
The HAVING clause was added to SQL because theWHERE keyword
could n...
SubqueriesSubqueries
A SELECT statement embedded into another statement is called a
subquery
SELECT SUM(Sales) FROM Store_...
CorrelatedCorrelated SubqueriesSubqueries
If a subquery may reference columns from the main query table, this is
called a ...
ViewsViews -- InlineInline
A view is a virtual table based on the result-set of an SQL statement
An inline view is a table...
ViewsViews -- StoredStored
A view is a virtual table based on the result-set of an SQL statement
CREATEVIEW [Current Produ...
ResourcesResources
BOOKS:
SQL in a Nutshell (English)
(A Desktop Quick Reference - ISBN: 9781565927445)
Publisher: Oreilly...
Upcoming SlideShare
Loading in …5
×

Sql overview-1232931296681161-1

404 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
404
On SlideShare
0
From Embeds
0
Number of Embeds
107
Actions
Shares
0
Downloads
16
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Sql overview-1232931296681161-1

  1. 1. SQL Programming Overview January 23, 2009
  2. 2. Goals/ObjectivesGoals/Objectives Gain an understanding of: ◦ SQL Programming including database structures, manipulation of database contents and retrieval of contents ◦ How it relates to FeaturePlan Be able to … speak confidently about SQL and provide efficient solutions for the reporting needs of our customers. 2
  3. 3. AgendaAgenda History of SQL SQL Fundamentals Data Definition Data Modifications SingleTable SELECT StatementsSingleTable SELECT Statements Joins Set Operators Aggregate Functions Subqueries Views Execution Plans Resources
  4. 4. History of SQLHistory of SQL During the 1970s, a group at IBM San Jose Research Laboratory developed the System R relational database management system Donald D. Chamberlin and Raymond F. Boyce of IBM subsequently created the Structured English Query Language (SEQUEL) to manipulate and manage data stored in System R. The first non-commercial non-SQL RDBMS, Ingres, was developed in 1974 at the U.C. Berkeley. In the late 1970s, Relational Software, Inc. (now Oracle Corporation) developed their own SQL-based RDBMS In the summer of 1979, Relational Software, Inc. introduced the first commercially available implementation of SQL, OracleV2 (Version2) forVAX computers. OracleV2 beat IBM's release of the System/38 RDBMS to market by a few weeks.
  5. 5. History of SQL (cont’d)History of SQL (cont’d) SQL was adopted as a standard by ANSI in 1986 and ISO in 1987. In the original SQL standard,ANSI declared that the official pronunciation for SQL is "es queue el“. The SQL standard has gone through a number of revisions: Year Name Comments 1986 SQL-86 First published by ANSI. Ratified by ISO in 1987. 1989 SQL-89 Minor revision, adopted as FIPS 127-1.1989 SQL-89 Minor revision, adopted as FIPS 127-1. 1992 SQL-92 Major revision (ISO 9075), Entry Level SQL-92 adopted as FIPS 127-2. 1999 SQL:1999 Added regular expression matching, recursive queries, triggers, support for procedural and control-of-flow statements, non-scalar types, and some object- oriented features. 2003 SQL:2003 Introduced XML-related features, window functions, standardized sequences, and columns with auto-generated values (including identity-columns). 2006 SQL:2006 ISO/IEC 9075-14:2006 defines ways in which SQL can be used in conjunction with XML. It defines ways of importing and storing XML data in an SQL database, manipulating it within the database and publishing both XML and conventional SQL-data in XML form. 2008 SQL:2008 Defines more flexible windowing functions
  6. 6. SQL FundamentalsSQL Fundamentals SQL is the only way to build, manipulate and access a relational database Table ◦ Columns and Rows RelationshipsRelationships ◦ Primary keys (unique column or combination of columns) ◦ Foreign keys (a column that references primary key of another table) Normalization ◦ Each table describes one thing only
  7. 7. SQL Server BasicsSQL Server Basics Keywords are not case sensitive Table and column names are stored as they are entered and SQL Server can be either case sensitive or insensitive Elements are comma separated Comments are enclosed between /* and */ or preceded by – Generally SQL statements are terminated by semi-colon (SQL Server does not require it)
  8. 8. Data DefinitionData Definition Data Types ◦ Each database column has to have a valid data type ◦ Data types are only partially standardized SQL Server: TINYINT, INT, Numeric, Decimal, Float, Real, Char,Varchar, Text, Datetime, Binary, Image Create TablesCreate Tables ◦ Defines the structure of the table CREATETABLE Divisions (DivisionID Numeric(5) NOT NULL , DivisionNameVarchar(40) NOT NULL); Alter Tables ◦ Modifies the structure of the table ALTERTABLE Divisions ADD DivisionCityVarchar(40) NOT NULL; or ALTER COLUMN DivisionNameVarchar(80) NOT NULL; or DROP COLUMN DivisionCityVarchar(40) NOT NULL;
  9. 9. Data Definition (cont’d)Data Definition (cont’d) DROPTables ◦ DROPTABLE Divisions; Constraints are used to enforce valid data in columns ◦ NOT NULL (the column will not allow null values) ◦ CHECK (value is checked against constants or other columns) ◦ PRIMARY KEY (enforces uniqueness of primary key)◦ PRIMARY KEY (enforces uniqueness of primary key) ◦ UNIQUE (enforces uniqueness of alternate keys) ◦ FOREIGN KEY (specifies a relationship between tables) Indexes (like a virtual table with pointers to physical table) ◦ In general, rows are unsorted ◦ Indexes are sorted on the indexed value ◦ Indexes are created on a single column or combination of columns NOTE: Null means unknown or missing value, not blank or zero
  10. 10. Data ModificationData Modification INSERT ◦ Adds new rows to a table INSERT INTO Departments (DivisionID, DepartmentID, DepartmentName) VALUES (1, 100,‘Accounting’); UPDATEUPDATE ◦ Modifies the column values in existing rows UPDATE Employee SET CurrentSalary = CurrentSalary + 100 WHERE Employee = 4; DELETE ◦ Removes rows from a table DELETE FROM Employees WHERE Employee = 7;
  11. 11. Data Modification (cont’d)Data Modification (cont’d) TRANSACTIONS ◦ A set of INSERT/UPDATE/DELETE operations that belong together as a logical unit of work ◦ COMMIT (ends the transaction with success and makes updates permanent) ◦ ROLLBACK (ends the transaction with failure and undoes the updates)updates) INSERT INTO ConferenceRooms(RoomID,Name,Capacity) VALUES(101,'Auditorium',250); INSERT INTO ConferenceRooms(RoomID,Name,Capacity) VALUES(300,'3rd Floor Small room',10); INSERT INTO ConferenceRooms(RoomID,Name,Capacity) VALUES(310,'3rd Floor Tiny room',6); INSERT INTO ConferenceRooms(RoomID,Name,Capacity) VALUES(400,'Attic Closet',3); COMMIT;
  12. 12. Single Table SELECT StatementsSingle Table SELECT Statements The SELECT statement retrieves data from database tables SELECT select_list (describes the columns of the result set.) [ INTO new_table_name ] (specifies that the result set is used to create a new table) FROM table_list (Contains a list of the tables from which the result set data is retrieved)FROM table_list (Contains a list of the tables from which the result set data is retrieved) [WHERE search_conditions ] (filter that defines the conditions each row in the source tables must meet) [ GROUP BY group_by_list ] (partitions the result set into groups based on the values) [ HAVING search_conditions ] (an additional filter that is applied to the result set) [ ORDER BY order_list [ ASC | DESC ] ] (defines the order in which the rows in the result set are sorted)
  13. 13. Single Table SELECT StatementsSingle Table SELECT Statements (cont’d)(cont’d) TheWHERE clause specifies a filter condition SELECT EmployeeID, FirstName, LastName ,CurrentSalary*12 ASYearlySalary FROM Employees WHERE EmployeeID = 3; SELECT EmployeeID, LastName FROM Employees Conditional Operators ◦ = <> > < >= <= ◦ IN , NOT IN (test for several values) ◦ BETWEEN, NOT BETWEEN (intervals) ◦ IS NULL, IS NOT NULL ◦ LIKE, NOT LIKE ( % or _ ) ◦ EXISTS, NOT EXISTS (sub queries) Conditions can be combined with NOT AND OR FROM Employees WHERE LastName LIKE 'D%' AND FirstName LIKE '_a%‘;
  14. 14. Single Table SELECT StatementsSingle Table SELECT Statements (cont’d)(cont’d) The ORDER BY statement defines the sort order of the rows SELECT LastName ,FirstName ,CurrentSalary,CurrentSalary FROM Employees ORDER BY CurrentSalary DESC ,LastName ASC ,FirstName ASC;
  15. 15. Single Table SELECT StatementsSingle Table SELECT Statements (cont’d)(cont’d) NULL means unknown or missing value ◦ NULL is not the same as blank ◦ NULL is not the same as zero ◦ NULL is not the same as the text ‘NULL’ ◦ NULL is not equal to any value◦ NULL is not equal to any value ◦ NULL is not different to any value ◦ NULL is not equal to NULL ◦ In SQL Server, NULL sorts as the lowest value DISTINCT can be used to suppress duplicates
  16. 16. Joins (INNER)Joins (INNER) Joins are used to combine information from multiple tables Basic Syntax of an INNER Join (excludes data that does NOT satisfy the join)
  17. 17. Joins (INNER)Joins (INNER) SELECT column_name(s) FROM table_name1 JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s)SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name Inner joins are default, so the word Inner can be omitted
  18. 18. Joins (OUTER)Joins (OUTER) Joins are used to combine information from multiple tables Basic Syntax of an OUTER Join (include rows from one table that have no matching row) LEFT OUTER JOIN
  19. 19. Joins (CROSS)Joins (CROSS) Each row in one table is paired to every row in the other table A cross join is also called a cartesian product SELECT * FROM employee CROSS JOIN departmentFROM employee CROSS JOIN department A B 1 2 3 A 1 A 2 A 3 B 1 B 2 B 3
  20. 20. Joins (OUTER)Joins (OUTER) table1 LEFT OUTER JOIN table2 – all rows from table 1 will be included table1 RIGHT OUTER JOIN table2 – all rows from table 2 will be included table1 FULL OUTER JOIN table2 – all rows from each table will be includedtable1 FULL OUTER JOIN table2 – all rows from each table will be included SELECT column_name(s) FROM table_name1 LEFT OUTER JOIN table_name2 ON table_name1.column_name=table_name2.column_name
  21. 21. Set OperatorsSet Operators UNION, INTERSECT and EXCEPT UNIONUNION SELECT zip FROM hotel.customerWHERE zip > '90000' UNION SELECT zip FROM hotel.hotelWHERE zip > '90000‘ Creates one table with rows from both SELECTs Suppresses duplicate rows
  22. 22. Set OperatorsSet Operators UNION, INTERSECT and EXCEPT INTERSECT SELECT zip FROM hotel.customerWHERE zip < '30000'SELECT zip FROM hotel.customerWHERE zip < '30000' INTERSECT SELECT zip FROM hotel.hotelWHERE zip < '30000' Returns the rows that occur in both queries EXCEPT SELECT zip FROM hotel.hotelWHERE zip < '30000' EXCEPT SELECT zip FROM hotel.customerWHERE zip < '30000‘ Returns the rows from one query except those that occur in the other -basically a minus
  23. 23. Row FunctionsRow Functions Row functions take input parameters and return a value ◦ Math Functions ◦ String Functions ◦ Date and Time Functions ◦ Data Type Conversions◦ Data Type Conversions ◦ CASE Statements ◦ NULL Functions
  24. 24. Row FunctionsRow Functions -- MathMath ABS DEGREES RAND ACOS EXP ROUND ASIN LOG SIN ATN2 LOG10 SQRT CEILINGASIN FLOOR SIGN ATAN SELECT ROUND(123.9994, 3) Here is the result set. 123.9990 CEILING PI SQUARE COS POWER TAN COT RADIANS
  25. 25. Row FunctionsRow Functions -- StringString ASCII NCHAR SOUNDEX CHAR PATINDEX SPACE CHARINDEX DIFFERENCE REPLACE STUFF LEFT REPLICATE SUBSTRINGCHARINDEX QUOTENAME STR SELECT LEFT('abcdefg',2) Here is the result set. ab SUBSTRING LEN REVERSE UNICODE LOWER RIGHT UPPER LTRIM RTRIM
  26. 26. Row FunctionsRow Functions –– Date & TimeDate & Time DATEADD DATEDIFF DATENAME DATEPART DAY GETDATEGETDATE GETUTCDATE MONTH YEAR SELECT GETDATE() Here is the result set: July 29 1998 2:50 PM
  27. 27. bigint numeric bit smallint decimal smallmoney Row FunctionsRow Functions –– Data TypeData Type datetime2 smalldatetime datetime time Character Strings Image cursor timestamp hierarchyid uniqueidentifier sql_variantsmallmoney int tinyint Money float real Date and Time date datetimeoffset Strings char varchar Text nchar nvarchar Ntext binary varbinary sql_variant xml Table SELECT CAST(myval AS decimal(10,5))
  28. 28. Row FunctionsRow Functions -- CaseCase The CASE expression enables many forms of conditional processing to be placed into a SQL statement. SELECT title, price, Budget = CASE priceBudget = CASE price WHEN price > 20.00THEN 'Expensive‘ WHEN price BETWEEN 10.00 AND 19.99THEN 'Moderate' WHEN price < 10.00THEN 'Inexpensive' ELSE 'Unknown' END, FROM titles
  29. 29. Row FunctionsRow Functions -- NullNull A null value in an expression causes the result of the expression to be null Testing for NULL in aWHERE clause SELECT Name,Weight FROM Production.Product WHEREWeight IS NULL;
  30. 30. Aggregate FunctionsAggregate Functions SUM AVG MAX MIN COUNT SELECT AVG(UnitPrice * Quantity) As AveragePrice FROMWidgetOrders WHERE Continent = “North America” SELECT COUNT(*) AS 'Number of Large Orders' FROMWidgetOrders WHERE Quantity > 100 SELECT MAX(Quantity * UnitPrice)As 'Largest Order' FROMWidgetOrders
  31. 31. Aggregate FunctionsAggregate Functions –– GROUP BYGROUP BY The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns. SELECT Customer,SUM(OrderPrice)SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer Customer SUM(OrderPrice) Hansen 2000 Nilsen 1700 Jensen 2000
  32. 32. Aggregate FunctionsAggregate Functions –– HAVINGHAVING The HAVING clause was added to SQL because theWHERE keyword could not be used with aggregate functions. SELECT Customer,SUM(OrderPrice) FROM OrdersFROM Orders GROUP BY Customer HAVING SUM(OrderPrice)<2000 Customer SUM(OrderPrice) Nilsen 1700
  33. 33. SubqueriesSubqueries A SELECT statement embedded into another statement is called a subquery SELECT SUM(Sales) FROM Store_Information WHERE Store_name INWHERE Store_name IN (SELECT store_name FROM Geography WHERE region_name = 'West') IN or NOT IN will handle extra lists returned by the sub query Operators (>, <, =, etc.) can be used when single values are returned
  34. 34. CorrelatedCorrelated SubqueriesSubqueries If a subquery may reference columns from the main query table, this is called a correlated SELECT DISTINCT c.LastName, c.FirstName FROM Person.Contact cFROM Person.Contact c JOIN HumanResources.Employee e ON e.ContactID = c.ContactID WHERE 5000.00 IN (SELECT Bonus FROM Sales.SalesPerson sp WHERE e.EmployeeID = sp.SalesPersonID) ;
  35. 35. ViewsViews -- InlineInline A view is a virtual table based on the result-set of an SQL statement An inline view is a table within the SELECT height FROM (SELECT height FROM test WHERE id = :b1FROM (SELECT height FROM test WHERE id = :b1 ORDER BY id DESC, acc_date DESC, height DESC) WHERE ROWNUM = 1;
  36. 36. ViewsViews -- StoredStored A view is a virtual table based on the result-set of an SQL statement CREATEVIEW [Current Product List] AS SELECT ProductID,ProductName FROM Products WHERE Discontinued=No A view does not store data If you do insert, update, delete on a view the data values in the underlying tables will be updated ◦ This is not possible on all views ◦ Computed columns cannot be updated ◦ Not permitted on aggregate views or views with set operators ◦ Join views may or may not be updateable
  37. 37. ResourcesResources BOOKS: SQL in a Nutshell (English) (A Desktop Quick Reference - ISBN: 9781565927445) Publisher: Oreilly & Associates Inc WEBSITES: W3Schools SQLTutorial http://www.w3schools.com/sql/default.asp

×