SlideShare uma empresa Scribd logo
1 de 37
Baixar para ler offline
SQL Programming Overview




                  January 23, 2009
Goals/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
Agenda
 History of SQL
 SQL Fundamentals
 Data Definition
 Data Modifications
 Single Table SELECT Statements
 Joins
 Set Operators
 Aggregate Functions
 Subqueries
 Views
 Execution Plans
 Resources
History 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, Oracle V2
 (Version2) for VAX computers. Oracle V2 beat IBM's release of
 the System/38 RDBMS to market by a few weeks.
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 quot;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.
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
SQL Fundamentals
 SQL is the only way to build, manipulate and access a relational
 database
 Table
 ◦ Columns and Rows
 Relationships
 ◦ 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
SQL 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)
Data 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 Tables
 ◦ Defines the structure of the table
 CREATE TABLE Divisions
    (DivisionID Numeric(5) NOT NULL
     , DivisionName Varchar(40) NOT NULL);

 Alter Tables
 ◦ Modifies the structure of the table
 ALTER TABLE Divisions
    ADD DivisionCity Varchar(40) NOT NULL;
   or ALTER COLUMN DivisionName Varchar(80) NOT NULL;
   or DROP COLUMN DivisionCity Varchar(40) NOT NULL;
Data Definition (cont’d)
 DROP Tables
 ◦ DROP TABLE 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)
 ◦ 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
Data Modification
 INSERT
  ◦ Adds new rows to a table
    INSERT INTO Departments
    (DivisionID, DepartmentID, DepartmentName)
    VALUES (1, 100, ‘Accounting’);

 UPDATE
 ◦ 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;
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)

 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;
Single 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)

[ 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)
Single Table SELECT Statements (cont’d)
  The WHERE clause specifies a filter condition

SELECT EmployeeID, FirstName, LastName
   ,CurrentSalary*12 AS YearlySalary
FROM Employees
WHERE EmployeeID = 3;
                                      SELECT EmployeeID, LastName
                                      FROM Employees
  Conditional Operators               WHERE LastName LIKE 'D%'
  ◦ = <> > < >= <=                    AND FirstName LIKE '_a%‘;
  ◦ 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
Single Table SELECT Statements (cont’d)
  The ORDER BY statement defines the sort order of the rows


SELECT LastName
   ,FirstName
   ,CurrentSalary
FROM Employees
ORDER BY CurrentSalary DESC
    ,LastName       ASC
    ,FirstName      ASC;
Single Table SELECT Statements (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 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
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)
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)
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
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
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 department

    A       1        A    1
            2        A    2
    B
            3        A    3
                     B    1
                     B    2
                     B    3
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 included


SELECT column_name(s)
FROM table_name1
LEFT OUTER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Set Operators
  UNION, INTERSECT and EXCEPT




  UNION
SELECT zip FROM hotel.customer WHERE zip > '90000'
 UNION
SELECT zip FROM hotel.hotel WHERE zip > '90000‘

  Creates one table with rows from both SELECTs
  Suppresses duplicate rows
Set Operators
  UNION, INTERSECT and EXCEPT




  INTERSECT
SELECT zip FROM hotel.customer WHERE zip < '30000'
 INTERSECT
SELECT zip FROM hotel.hotel WHERE zip < '30000'
  Returns the rows that occur in both queries

  EXCEPT
SELECT zip FROM hotel.hotel WHERE zip < '30000'
 EXCEPT
SELECT zip FROM hotel.customer WHERE zip < '30000‘
  Returns the rows from one query except those that occur in the other
  -basically a minus
Row Functions
 Row functions take input parameters and return a value
 ◦ Math Functions
 ◦ String Functions
 ◦ Date and Time Functions
 ◦ Data Type Conversions
 ◦ CASE Statements
 ◦ NULL Functions
Row Functions - Math
  ABS                     LOG
  DEGREES                 SIN
  RAND                    ATN2
  ACOS
                          LOG10
  EXP
                          SQRT
  ROUND
  ASIN                    CEILING
  FLOOR                   PI
  SIGN                    SQUARE
  ATAN
                          COS
                          POWER
SELECT ROUND(123.9994,
  3)                      TAN
Here is the result set.   COT
123.9990                  RADIANS
Row Functions - String
  ASCII                    DIFFERENCE
  NCHAR
                           REPLACE
  SOUNDEX
                           STUFF
  CHAR
                           LEFT
  PATINDEX
  SPACE                    REPLICATE
  CHARINDEX                SUBSTRING
  QUOTENAME
                           LEN
  STR
                           REVERSE
                           UNICODE
SELECT LEFT('abcdefg',2)
Here is the result set.    LOWER
ab                         RIGHT
                           UPPER
                           LTRIM
                           RTRIM
Row Functions – Date & Time
  DATEADD
  DATEDIFF
  DATENAME
  DATEPART
  DAY
  GETDATE
  GETUTCDATE
  MONTH
  YEAR

SELECT GETDATE()
Here is the result set:
July 29 1998 2:50 PM
Row Functions – Data Type
 datetime2       bigint             Image
 smalldatetime   numeric            cursor
 datetime        bit                timestamp
                 smallint
 time                               hierarchyid
                 decimal
 Character                          uniqueidentifier
                 smallmoney
 Strings                            sql_variant
                 int
 char                               xml
                 tinyint
 varchar                            Table
                 Money
 Text
                 float            SELECT
 nchar
                 real               CAST(myval AS
 nvarchar
                 Date and Time      decimal(10,5))
 Ntext
                 date
 binary
                 datetimeoffset
 varbinary
Row Functions - Case
The CASE expression enables many forms of conditional processing to be
placed into a SQL statement.


SELECT title, price,
     Budget = CASE price
      WHEN price > 20.00 THEN 'Expensive‘
      WHEN price BETWEEN 10.00 AND 19.99 THEN 'Moderate'
      WHEN price < 10.00 THEN 'Inexpensive'
       ELSE 'Unknown'
     END,
FROM titles
Row Functions - Null
  A null value in an expression causes the result of the expression to be
  null


  Testing for NULL in a WHERE clause


SELECT Name, Weight
FROM Production.Product
WHERE Weight IS NULL;
Aggregate Functions
  SUM AVG MAX MIN COUNT

SELECT AVG(UnitPrice * Quantity) As AveragePrice
FROM WidgetOrders
WHERE Continent = “North America”

SELECT COUNT(*) AS 'Number of Large Orders'
FROM WidgetOrders
WHERE Quantity > 100

SELECT MAX(Quantity * UnitPrice)As 'Largest Order'
FROM WidgetOrders
Aggregate Functions – GROUP 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)
FROM Orders
GROUP BY Customer

  Customer                   SUM(OrderPrice)
  Hansen                     2000
  Nilsen                     1700
  Jensen                     2000
Aggregate Functions – HAVING
  The HAVING clause was added to SQL because the WHERE keyword
  could not be used with aggregate functions.


SELECT Customer,SUM(OrderPrice)
FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000


  Customer                 SUM(OrderPrice)
  Nilsen                   1700
Subqueries
  A SELECT statement embedded into another statement is called a
  subquery


SELECT SUM(Sales) FROM Store_Information
WHERE 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
Correlated Subqueries
  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 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) ;
Views - Inline
  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 = :b1
     ORDER BY id DESC, acc_date DESC, height DESC)
WHERE ROWNUM = 1;
Views - Stored
  A view is a virtual table based on the result-set of an SQL statement

CREATE VIEW [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
Resources
BOOKS:
 SQL in a Nutshell (English)
 (A Desktop Quick Reference - ISBN: 9781565927445)
 Publisher: Oreilly & Associates Inc


WEBSITES:
 W3Schools SQL Tutorial
 http://www.w3schools.com/sql/default.asp

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
SQL
SQLSQL
SQL
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
Sql and Sql commands
Sql and Sql commandsSql and Sql commands
Sql and Sql commands
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
SQL
SQLSQL
SQL
 
SQL Constraints
SQL ConstraintsSQL Constraints
SQL Constraints
 
Structured query language(sql)ppt
Structured query language(sql)pptStructured query language(sql)ppt
Structured query language(sql)ppt
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
 
SQL commands
SQL commandsSQL commands
SQL commands
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
Structured Query Language (SQL)
Structured Query Language (SQL)Structured Query Language (SQL)
Structured Query Language (SQL)
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Introduction to sql
Introduction to sqlIntroduction to sql
Introduction to sql
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 

Destaque

SQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQLSQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQL
Jerry Yang
 
DOAG: Visual SQL Tuning
DOAG: Visual SQL TuningDOAG: Visual SQL Tuning
DOAG: Visual SQL Tuning
Kyle Hailey
 
Database Design Slide 1
Database Design Slide 1Database Design Slide 1
Database Design Slide 1
ahfiki
 

Destaque (17)

Stored procedure in sql server
Stored procedure in sql serverStored procedure in sql server
Stored procedure in sql server
 
SQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQLSQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQL
 
Common SQL Programming Mistakes
Common SQL Programming MistakesCommon SQL Programming Mistakes
Common SQL Programming Mistakes
 
15 questions sql advance
15 questions sql   advance15 questions sql   advance
15 questions sql advance
 
DOAG: Visual SQL Tuning
DOAG: Visual SQL TuningDOAG: Visual SQL Tuning
DOAG: Visual SQL Tuning
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Sql interview questions and answers
Sql interview questions and  answersSql interview questions and  answers
Sql interview questions and answers
 
Sql server basics
Sql server basicsSql server basics
Sql server basics
 
Sql Server Basics
Sql Server BasicsSql Server Basics
Sql Server Basics
 
MYSQL.ppt
MYSQL.pptMYSQL.ppt
MYSQL.ppt
 
Introduction to MySQL
Introduction to MySQLIntroduction to MySQL
Introduction to MySQL
 
Database Design Slide 1
Database Design Slide 1Database Design Slide 1
Database Design Slide 1
 
Introduction to Mysql
Introduction to MysqlIntroduction to Mysql
Introduction to Mysql
 
Introduction to database
Introduction to databaseIntroduction to database
Introduction to database
 
MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
 
Top 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and AnswersTop 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and Answers
 
Step by Step Installation of Microsoft SQL Server 2012
Step by Step Installation of Microsoft SQL Server 2012 Step by Step Installation of Microsoft SQL Server 2012
Step by Step Installation of Microsoft SQL Server 2012
 

Semelhante a SQL Overview

Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1
sagaroceanic11
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
PavithSingh
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
DraguClaudiu
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
SANTOSH RATH
 

Semelhante a SQL Overview (20)

Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1
 
SQL Query
SQL QuerySQL Query
SQL Query
 
SQL
SQLSQL
SQL
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
Chapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfChapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdf
 
Assignment#02
Assignment#02Assignment#02
Assignment#02
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptx
 
Lab
LabLab
Lab
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
 
Query
QueryQuery
Query
 
Hira
HiraHira
Hira
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
SQL Tutorial for BCA-2
SQL Tutorial for BCA-2SQL Tutorial for BCA-2
SQL Tutorial for BCA-2
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

SQL Overview

  • 1. SQL Programming Overview January 23, 2009
  • 2. Goals/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. Agenda History of SQL SQL Fundamentals Data Definition Data Modifications Single Table SELECT Statements Joins Set Operators Aggregate Functions Subqueries Views Execution Plans Resources
  • 4. History 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, Oracle V2 (Version2) for VAX computers. Oracle V2 beat IBM's release of the System/38 RDBMS to market by a few weeks.
  • 5. 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 quot;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. 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. SQL Fundamentals SQL is the only way to build, manipulate and access a relational database Table ◦ Columns and Rows Relationships ◦ 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. SQL 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. Data 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 Tables ◦ Defines the structure of the table CREATE TABLE Divisions (DivisionID Numeric(5) NOT NULL , DivisionName Varchar(40) NOT NULL); Alter Tables ◦ Modifies the structure of the table ALTER TABLE Divisions ADD DivisionCity Varchar(40) NOT NULL; or ALTER COLUMN DivisionName Varchar(80) NOT NULL; or DROP COLUMN DivisionCity Varchar(40) NOT NULL;
  • 9. Data Definition (cont’d) DROP Tables ◦ DROP TABLE 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) ◦ 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. Data Modification INSERT ◦ Adds new rows to a table INSERT INTO Departments (DivisionID, DepartmentID, DepartmentName) VALUES (1, 100, ‘Accounting’); UPDATE ◦ 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. 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) 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. Single 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) [ 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. Single Table SELECT Statements (cont’d) The WHERE clause specifies a filter condition SELECT EmployeeID, FirstName, LastName ,CurrentSalary*12 AS YearlySalary FROM Employees WHERE EmployeeID = 3; SELECT EmployeeID, LastName FROM Employees Conditional Operators WHERE LastName LIKE 'D%' ◦ = <> > < >= <= AND FirstName LIKE '_a%‘; ◦ 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
  • 14. Single Table SELECT Statements (cont’d) The ORDER BY statement defines the sort order of the rows SELECT LastName ,FirstName ,CurrentSalary FROM Employees ORDER BY CurrentSalary DESC ,LastName ASC ,FirstName ASC;
  • 15. Single Table SELECT Statements (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 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. 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. 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) 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. 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. 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 department A 1 A 1 2 A 2 B 3 A 3 B 1 B 2 B 3
  • 20. 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 included SELECT column_name(s) FROM table_name1 LEFT OUTER JOIN table_name2 ON table_name1.column_name=table_name2.column_name
  • 21. Set Operators UNION, INTERSECT and EXCEPT UNION SELECT zip FROM hotel.customer WHERE zip > '90000' UNION SELECT zip FROM hotel.hotel WHERE zip > '90000‘ Creates one table with rows from both SELECTs Suppresses duplicate rows
  • 22. Set Operators UNION, INTERSECT and EXCEPT INTERSECT SELECT zip FROM hotel.customer WHERE zip < '30000' INTERSECT SELECT zip FROM hotel.hotel WHERE zip < '30000' Returns the rows that occur in both queries EXCEPT SELECT zip FROM hotel.hotel WHERE zip < '30000' EXCEPT SELECT zip FROM hotel.customer WHERE zip < '30000‘ Returns the rows from one query except those that occur in the other -basically a minus
  • 23. Row Functions Row functions take input parameters and return a value ◦ Math Functions ◦ String Functions ◦ Date and Time Functions ◦ Data Type Conversions ◦ CASE Statements ◦ NULL Functions
  • 24. Row Functions - Math ABS LOG DEGREES SIN RAND ATN2 ACOS LOG10 EXP SQRT ROUND ASIN CEILING FLOOR PI SIGN SQUARE ATAN COS POWER SELECT ROUND(123.9994, 3) TAN Here is the result set. COT 123.9990 RADIANS
  • 25. Row Functions - String ASCII DIFFERENCE NCHAR REPLACE SOUNDEX STUFF CHAR LEFT PATINDEX SPACE REPLICATE CHARINDEX SUBSTRING QUOTENAME LEN STR REVERSE UNICODE SELECT LEFT('abcdefg',2) Here is the result set. LOWER ab RIGHT UPPER LTRIM RTRIM
  • 26. Row Functions – Date & Time DATEADD DATEDIFF DATENAME DATEPART DAY GETDATE GETUTCDATE MONTH YEAR SELECT GETDATE() Here is the result set: July 29 1998 2:50 PM
  • 27. Row Functions – Data Type datetime2 bigint Image smalldatetime numeric cursor datetime bit timestamp smallint time hierarchyid decimal Character uniqueidentifier smallmoney Strings sql_variant int char xml tinyint varchar Table Money Text float SELECT nchar real CAST(myval AS nvarchar Date and Time decimal(10,5)) Ntext date binary datetimeoffset varbinary
  • 28. Row Functions - Case The CASE expression enables many forms of conditional processing to be placed into a SQL statement. SELECT title, price, Budget = CASE price WHEN price > 20.00 THEN 'Expensive‘ WHEN price BETWEEN 10.00 AND 19.99 THEN 'Moderate' WHEN price < 10.00 THEN 'Inexpensive' ELSE 'Unknown' END, FROM titles
  • 29. Row Functions - Null A null value in an expression causes the result of the expression to be null Testing for NULL in a WHERE clause SELECT Name, Weight FROM Production.Product WHERE Weight IS NULL;
  • 30. Aggregate Functions SUM AVG MAX MIN COUNT SELECT AVG(UnitPrice * Quantity) As AveragePrice FROM WidgetOrders WHERE Continent = “North America” SELECT COUNT(*) AS 'Number of Large Orders' FROM WidgetOrders WHERE Quantity > 100 SELECT MAX(Quantity * UnitPrice)As 'Largest Order' FROM WidgetOrders
  • 31. Aggregate Functions – GROUP 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) FROM Orders GROUP BY Customer Customer SUM(OrderPrice) Hansen 2000 Nilsen 1700 Jensen 2000
  • 32. Aggregate Functions – HAVING The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions. SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer HAVING SUM(OrderPrice)<2000 Customer SUM(OrderPrice) Nilsen 1700
  • 33. Subqueries A SELECT statement embedded into another statement is called a subquery SELECT SUM(Sales) FROM Store_Information WHERE 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. Correlated Subqueries 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 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. Views - Inline 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 = :b1 ORDER BY id DESC, acc_date DESC, height DESC) WHERE ROWNUM = 1;
  • 36. Views - Stored A view is a virtual table based on the result-set of an SQL statement CREATE VIEW [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. Resources BOOKS: SQL in a Nutshell (English) (A Desktop Quick Reference - ISBN: 9781565927445) Publisher: Oreilly & Associates Inc WEBSITES: W3Schools SQL Tutorial http://www.w3schools.com/sql/default.asp