SlideShare a Scribd company logo
Structured Query Language
SQL is an ANSI (American National Standards Institute)
standard computer language for accessing and
manipulating database systems. SQL statements are used
to retrieve and update data in a database. SQL works with
database programs like MS Access, DB2, Informix, MS SQL
Server, Oracle, Sybase, etc.
Unfortunately, there are many different versions of the
SQL language, but to be in compliance with the ANSI
standard, they must support the same major keywords in
a similar manner (such as SELECT, UPDATE, DELETE,
INSERT, WHERE, and others).
Note: Most of the SQL database programs also have their
own proprietary extensions in addition to the SQL
standard!
SQL is a Standard - BUT....
SQL Database Tables
A database most often contains one or more tables. Each table is
identified by a name (e.g. "Customers" or "Orders"). Tables contain
records (rows) with data.
Below is an example of a table called "Persons":
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger
With SQL, we can query a database and have a result set returned.
A query like this:
SELECT LastName FROM Persons
Gives a result set like this:
SQL Queries
LastName
Hansen
Svendson
Pettersen
Difference between SQL server
2005 and 2008
SQL Server 2005 SQL Server 2008
XML data type is introduced.
XML data type is used.
Can not encrypt the entire
database.
Can encrypt the entire database
introduced in 2008.
Date time is used for both date
and time.
Date and time are separately
used for date and time
No table data type is included. Table data type introduced.
SSIS is started using. SSIS avails in this version.
CMS is not available. Central Management Server
(CMS) is Introduced.
PBM is not available Policy based management(PBM)
server is Introduced.
Data Types in SQL
 Characters:
 CHAR(20) -- fixed length
 VARCHAR(40) -- variable length
 Numbers:
 BIGINT, INT, SMALLINT, TINYINT
 REAL, FLOAT -- differ in precision
 MONEY
 Times and dates:
 DATE
 DATETIME -- SQL Server
 Others... All are simple
7
Types of SQL Commands
SQL Data Manipulation Language
(DML)
SQL (Structured Query Language) is a syntax for executing
queries. But the SQL language also includes a syntax to
update, insert, and delete records.
These query and update commands together form the Data
Manipulation Language (DML) part of SQL:
•SELECT - extracts data from a database table
•UPDATE - updates data in a database table
•DELETE - deletes data from a database table
•INSERT INTO - inserts new data into a database table
SQL Data Definition Language (DDL)
The Data Definition Language (DDL) part of SQL permits
database tables to be created or deleted. We can also define
indexes (keys), specify links between tables, and impose
constraints between database tables.
The most important DDL statements in SQL are:
•CREATE TABLE - creates a new database table
•ALTER TABLE - alters (changes) a database table
•DROP TABLE - deletes a database table
•CREATE INDEX - creates an index (search key)
•DROP INDEX - deletes an index
SQL The SELECT Statement
The SELECT statement is used to select data from a table. The
tabular result is stored in a result table (called the result-set).
Syntax
SELECT column_name(s)
FROM table_name
To select the columns named "LastName" and "FirstName", use a SELECT
statement like this:
SELECT LastName, FirstName FROM Persons
Persons
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger
výsledok
LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari
To select all columns from the "Persons" table, use a * symbol instead of
column names, like this:
SELECT * FROM Persons
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger
Select All Columns
The result from a SQL query is stored in a result-set. Most database software systems
allow navigation of the result set with programming functions, like: Move-To-First-
Record, Get-Record-Content, Move-To-Next-Record, etc.
Programming functions like these are not a part of this tutorial. To learn about
accessing data with function calls, please visit our ADO tutorial.
The Result Set
Eliminating Duplicates
15
SELECT DISTINCT category
FROM Product
Compare to:
SELECT category
FROM Product
Category
Gadgets
Gadgets
Photography
Household
Category
Gadgets
Photography
Household
The DISTINCT keyword is used to return only distinct (different) values.
The SELECT statement returns information from table columns. But what if we
only want to select distinct elements?
With SQL, all we need to do is to add a DISTINCT keyword to the SELECT
statement:
Syntax
SELECT DISTINCT column_name(s)
FROM table_name
The SELECT DISTINCT Statement
To select ALL values from the column named "Company" we use a SELECT
statement like this:
SELECT Company FROM Orders
Orders
Company OrderNumber
Sega 3412
W3Schools 2312
Trio 4678
W3Schools 6798
Company
Sega
W3Schools
Trio
W3Schools
Using the DISTINCT keyword
Note that "W3Schools" is listed twice in the result-set.
To select only DIFFERENT values from the column named "Company" we use a
SELECT DISTINCT statement like this:
SELECT DISTINCT Company FROM Orders
Company
Sega
W3Schools
Trio
Orders
Company OrderNumber
Sega 3412
W3Schools 2312
Trio 4678
W3Schools 6798
Select All Columns
The WHERE clause is used to specify a selection criterion.
The WHERE Clause
To conditionally select data from a table, a WHERE clause can be added to the
SELECT statement.
Syntax
SELECT column FROM table
WHERE column operator value
With the WHERE clause, the following operators can be used:
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
Note: In some versions of SQL the <> operator may be written as !=
Using the WHERE Clause
To select only the persons living in the city "Sandnes", we add a WHERE clause to
the SELECT statement:
SELECT * FROM Persons
WHERE City='Sandnes'
LastName FirstName Address City Year
Hansen Ola Timoteivn 10 Sandnes 1951
Svendson Tove Borgvn 23 Sandnes 1978
Svendson Stale Kaivn 18 Sandnes 1980
Pettersen Kari Storgt 20 Stavanger 1960
LastName FirstName Address City Year
Hansen Ola Timoteivn 10 Sandnes 1951
Svendson Tove Borgvn 23 Sandnes 1978
Svendson Stale Kaivn 18 Sandnes 1980
Ordering the Results
22
SELECT pname, price, manufacturer
FROM Product
WHERE category=‘gizmo’ AND price > 50
ORDER BY price, pname
Ordering is ascending, unless you specify the DESC keyword.
Ties are broken by the second attribute on the ORDER BY list, etc.
Ordering the Results
23
SELECT category
FROM Product
ORDER BY pname
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
?
Ordering the Results
24
SELECT DISTINCT category
FROM Product
ORDER BY category
Compare to:
Category
Gadgets
Household
Photography
SELECT category
FROM Product
ORDER BY pname ?
Joins in SQL
 Connect two or more tables:
25
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Company Cname StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
What is
the connection
between
them ?
Joins
26
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all products under $200 manufactured in Japan;
return their names and prices.
SELECT pname, price
FROM Product, Company
WHERE manufacturer=cname AND country=‘Japan’
AND price <= 200
Join
between Product
and Company
Joins in SQL
27
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Company
Cname StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
PName Price
SingleTouch $149.99
SELECT pname, price
FROM Product, Company
WHERE manufacturer=cname AND country=‘Japan’
AND price <= 200
Joins
28
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all countries that manufacture some product in the ‘Gadgets’
category.
SELECT country
FROM Product, Company
WHERE manufacturer=cname AND category=‘Gadgets’
Joins in SQL
29
Name Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Company
Cname StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
SELECT country
FROM Product, Company
WHERE manufacturer=cname AND category=‘Gadgets’
Country
??
??
What is
the problem ?
What’s the
solution ?
Joins
30
Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product)
Person(persname, phoneNumber, city)
Find names of people living in Seattle that bought some product in the
‘Gadgets’ category, and the names of the stores they bought such
product from
SELECT DISTINCT persname, store
FROM Person, Purchase, Product
WHERE persname=buyer AND product = pname AND
city=‘Seattle’ AND category=‘Gadgets’
Joins in SQL
31
Name Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Company
Cname StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
SELECT country
FROM Product, Company
WHERE manufacturer=cname AND category=‘Gadgets’
Country
??
??
What is
the problem ?
What’s the
solution ?
Joins
32
Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product)
Person(persname, phoneNumber, city)
Find names of people living in Seattle that bought some product in the
‘Gadgets’ category, and the names of the stores they bought such
product from
SELECT DISTINCT persname, store
FROM Person, Purchase, Product
WHERE persname=buyer AND product = pname AND
city=‘Seattle’ AND category=‘Gadgets’
When are two tables related?
 You guess they are
 I tell you so
 Foreign keys are a method for schema designers to
tell you so (7.1)
 A foreign key states that a column is a reference to the
key of another table
ex: Product.manufacturer is foreign key of Company
 Gives information and enforces constraint
33
Disambiguating Attributes
 Sometimes two relations have the same attr:
Person(pname, address, worksfor)
Company(cname, address)
34
SELECT DISTINCT pname, address
FROM Person, Company
WHERE worksfor = cname
SELECT DISTINCT Person.pname, Company.address
FROM Person, Company
WHERE Person.worksfor = Company.cname
Which
address ?
Tuple Variables
35
SELECT DISTINCT x.store
FROM Purchase AS x, Purchase AS y
WHERE x.product = y.product AND y.store = ‘BestBuy’
Find all stores that sold at least one product that the store
‘BestBuy’ also sold:
Answer (store)
Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product)
Person(persname, phoneNumber, city)
Tuple Variables
36
General rule:
tuple variables introduced automatically by the system:
Product (name, price, category, manufacturer)
Becomes:
Doesn’t work when Product occurs more than once:
In that case the user needs to define variables explicitly.
SELECT name
FROM Product
WHERE price > 100
SELECT Product.name
FROM Product AS Product
WHERE Product.price > 100
Using Quotes
Note that we have used single quotes around the conditional values in the
examples.
SQL uses single quotes around text values (most database systems will also
accept double quotes). Numeric values should not be enclosed in quotes.
For text values:
This is correct:
SELECT * FROM Persons WHERE FirstName='Tove'
This is wrong:
SELECT * FROM Persons WHERE FirstName=Tove
The LIKE Condition
The LIKE condition is used to specify a search for a pattern in a column.
Syntax
SELECT column FROM table
WHERE column LIKE pattern
A "%" sign can be used to define wildcards (missing letters in the pattern)
both before and after the pattern.
Using LIKE
The following SQL statement will return persons with first names that start with
an 'O':
SELECT * FROM Persons
WHERE FirstName LIKE 'O%'
The following SQL statement will return persons with first names that end with
an 'a':
SELECT * FROM Persons
WHERE FirstName LIKE '%a'
Using LIKE 2
The following SQL statement will return persons with first names that contain the
pattern 'la':
SELECT * FROM Persons
WHERE FirstName LIKE '%la%'
SQL The INSERT INTO Statement
The INSERT INTO Statement
The INSERT INTO statement is used to insert new rows into a table.
Syntax
INSERT INTO table_name
VALUES (value1, value2,....)
You can also specify the columns for which you want to insert data:
INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)
Insert a New Row
LastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger
And this SQL statement:
INSERT INTO Persons
VALUES ('Hetland', 'Camilla', 'Hagabakka 24', 'Sandnes')
LastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes
Insert Data in Specified ColumnsLastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes
And This SQL statement:
INSERT INTO Persons (LastName, Address)
VALUES ('Rasmussen', 'Storgt 67')
LastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes
Rasmussen Storgt 67
SQL The UPDATE Statement
The Update Statement
The UPDATE statement is used to modify the data in a table.
Syntax
UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value
Update one Column in a Row
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Storgt 67
We want to add a first name to the person with a last name of "Rasmussen":
UPDATE Person SET FirstName = 'Nina'
WHERE LastName = 'Rasmussen'
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Storgt 67
Update several Columns in a Row
We want to change the address and add the name of the city:
UPDATE Person
SET Address = 'Stien 12', City = 'Stavanger'
WHERE LastName = 'Rasmussen'
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Storgt 67
SQL The Delete Statement
The Delete Statement
The DELETE statement is used to delete rows in a table.
Syntax
DELETE FROM table_name
WHERE column_name = some_value
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger
Delete a RowLastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger
"Nina Rasmussen" is going to be deleted:
DELETE FROM Person WHERE LastName = 'Rasmussen'
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Delete All RowsIt is possible to delete all rows in a table without deleting the table. This means
that the table structure, attributes, and indexes will be intact:
DELETE FROM table_name
Or
DELETE * FROM table_name
Exercises
54
Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product)
Company (cname, stock price, country)
Person(per-name, phone number, city)
Ex #1: Find people who bought telephony products.
Ex #2: Find names of people who bought American products
Ex #3: Find names of people who bought American products and they
live in Seattle.
Ex #4: Find people who have both bought and sold something.
Ex #5: Find people who bought stuff from Joe or bought products
from a company whose stock prices is more than $50.

More Related Content

What's hot (18)

PDF
Sql
satu2412
 
DOCX
Learning sql from w3schools
farhan516
 
PPTX
Introduction to SQL (for Chicago Booth MBA technology club)
Jennifer Berk
 
PPTX
Introduction to SQL
Amin Choroomi
 
PPTX
DDL(Data defination Language ) Using Oracle
Farhan Aslam
 
PPT
Introduction to structured query language (sql)
Sabana Maharjan
 
PPT
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
Dan D'Urso
 
PPT
Sql Server 2000
Om Vikram Thapa
 
PPT
Introduction to-sql
BG Java EE Course
 
ODP
BIS05 Introduction to SQL
Prithwis Mukerjee
 
PDF
SQL Overview
Stewart Rogers
 
PDF
Sql
Kikuvi John
 
PPT
Mysql rab2-student
santosh mishra
 
PPTX
Sql basics
Genesis Omo
 
PDF
Sql tutorial
Rumman Ansari
 
PPT
Sql server T-sql basics ppt-3
Vibrant Technologies & Computers
 
DOC
Dbms lab Manual
Vivek Kumar Sinha
 
PPT
Sql
Hitesh Sahoo
 
Learning sql from w3schools
farhan516
 
Introduction to SQL (for Chicago Booth MBA technology club)
Jennifer Berk
 
Introduction to SQL
Amin Choroomi
 
DDL(Data defination Language ) Using Oracle
Farhan Aslam
 
Introduction to structured query language (sql)
Sabana Maharjan
 
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
Dan D'Urso
 
Sql Server 2000
Om Vikram Thapa
 
Introduction to-sql
BG Java EE Course
 
BIS05 Introduction to SQL
Prithwis Mukerjee
 
SQL Overview
Stewart Rogers
 
Mysql rab2-student
santosh mishra
 
Sql basics
Genesis Omo
 
Sql tutorial
Rumman Ansari
 
Sql server T-sql basics ppt-3
Vibrant Technologies & Computers
 
Dbms lab Manual
Vivek Kumar Sinha
 

Similar to Sql for biggner (20)

PPTX
Database Management System - SQL beginner Training
Moutasm Tamimi
 
PPT
Sql 2006
Cathie101
 
PPT
CE 279 - WRITING SQL QUERIES umat edition.ppt
minusahsaaka
 
DOCX
Sql
navsissuk
 
PDF
SQL_BASIC AND ADVANCED.pdf
fayoyiwababajide
 
PDF
SQL Basics and Advanced for analytics.pdf
trg4294
 
PDF
Chapter – 6 SQL Lab Tutorial.pdf
TamiratDejene1
 
DOC
A must Sql notes for beginners
Ram Sagar Mourya
 
PPTX
Advanced Database Systems - Presentation 2.pptx
EllenGracePorras
 
PPTX
Lab
neelam_rawat
 
PPTX
Sql intro
glubox
 
PPT
MDI Training DB2 Course
Marcus Davage
 
PDF
SQL.......................................pdf
rajeswaria21
 
PPTX
Chapter 2: Ms SQL Server
Ngeam Soly
 
PDF
Dbms
Sachin Yadav
 
DOCX
DBMS Practical file 2019 BCAS301P (1).docx
ParasRajput26
 
PDF
Database Architecture and Basic Concepts
Tony Wong
 
PPT
lecture-SQL_Working.ppt
LaviKushwaha
 
PPTX
unit 1 ppt.pptx
VillainMass
 
Database Management System - SQL beginner Training
Moutasm Tamimi
 
Sql 2006
Cathie101
 
CE 279 - WRITING SQL QUERIES umat edition.ppt
minusahsaaka
 
SQL_BASIC AND ADVANCED.pdf
fayoyiwababajide
 
SQL Basics and Advanced for analytics.pdf
trg4294
 
Chapter – 6 SQL Lab Tutorial.pdf
TamiratDejene1
 
A must Sql notes for beginners
Ram Sagar Mourya
 
Advanced Database Systems - Presentation 2.pptx
EllenGracePorras
 
Sql intro
glubox
 
MDI Training DB2 Course
Marcus Davage
 
SQL.......................................pdf
rajeswaria21
 
Chapter 2: Ms SQL Server
Ngeam Soly
 
DBMS Practical file 2019 BCAS301P (1).docx
ParasRajput26
 
Database Architecture and Basic Concepts
Tony Wong
 
lecture-SQL_Working.ppt
LaviKushwaha
 
unit 1 ppt.pptx
VillainMass
 
Ad

Recently uploaded (20)

PDF
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PDF
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
PDF
AI Image Enhancer: Revolutionizing Visual Quality”
docmasoom
 
PDF
Step-by-Step Guide to Install SAP HANA Studio | Complete Installation Tutoria...
SAP Vista, an A L T Z E N Company
 
PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
PDF
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
PDF
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
PDF
Why Are More Businesses Choosing Partners Over Freelancers for Salesforce.pdf
Cymetrix Software
 
PDF
Infrastructure planning and resilience - Keith Hastings.pptx.pdf
Safe Software
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PDF
How to Download and Install ADT (ABAP Development Tools) for Eclipse IDE | SA...
SAP Vista, an A L T Z E N Company
 
PDF
SAP GUI Installation Guide for Windows | Step-by-Step Setup for SAP Access
SAP Vista, an A L T Z E N Company
 
PDF
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
PDF
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
PDF
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
PDF
Troubleshooting Virtual Threads in Java!
Tier1 app
 
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
AI Image Enhancer: Revolutionizing Visual Quality”
docmasoom
 
Step-by-Step Guide to Install SAP HANA Studio | Complete Installation Tutoria...
SAP Vista, an A L T Z E N Company
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
Why Are More Businesses Choosing Partners Over Freelancers for Salesforce.pdf
Cymetrix Software
 
Infrastructure planning and resilience - Keith Hastings.pptx.pdf
Safe Software
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
How to Download and Install ADT (ABAP Development Tools) for Eclipse IDE | SA...
SAP Vista, an A L T Z E N Company
 
SAP GUI Installation Guide for Windows | Step-by-Step Setup for SAP Access
SAP Vista, an A L T Z E N Company
 
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
Troubleshooting Virtual Threads in Java!
Tier1 app
 
Ad

Sql for biggner

  • 2. SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database systems. SQL statements are used to retrieve and update data in a database. SQL works with database programs like MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, etc. Unfortunately, there are many different versions of the SQL language, but to be in compliance with the ANSI standard, they must support the same major keywords in a similar manner (such as SELECT, UPDATE, DELETE, INSERT, WHERE, and others). Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard! SQL is a Standard - BUT....
  • 3. SQL Database Tables A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. Below is an example of a table called "Persons": LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes Svendson Tove Borgvn 23 Sandnes Pettersen Kari Storgt 20 Stavanger
  • 4. With SQL, we can query a database and have a result set returned. A query like this: SELECT LastName FROM Persons Gives a result set like this: SQL Queries LastName Hansen Svendson Pettersen
  • 5. Difference between SQL server 2005 and 2008
  • 6. SQL Server 2005 SQL Server 2008 XML data type is introduced. XML data type is used. Can not encrypt the entire database. Can encrypt the entire database introduced in 2008. Date time is used for both date and time. Date and time are separately used for date and time No table data type is included. Table data type introduced. SSIS is started using. SSIS avails in this version. CMS is not available. Central Management Server (CMS) is Introduced. PBM is not available Policy based management(PBM) server is Introduced.
  • 7. Data Types in SQL  Characters:  CHAR(20) -- fixed length  VARCHAR(40) -- variable length  Numbers:  BIGINT, INT, SMALLINT, TINYINT  REAL, FLOAT -- differ in precision  MONEY  Times and dates:  DATE  DATETIME -- SQL Server  Others... All are simple 7
  • 8. Types of SQL Commands
  • 9. SQL Data Manipulation Language (DML) SQL (Structured Query Language) is a syntax for executing queries. But the SQL language also includes a syntax to update, insert, and delete records. These query and update commands together form the Data Manipulation Language (DML) part of SQL: •SELECT - extracts data from a database table •UPDATE - updates data in a database table •DELETE - deletes data from a database table •INSERT INTO - inserts new data into a database table
  • 10. SQL Data Definition Language (DDL) The Data Definition Language (DDL) part of SQL permits database tables to be created or deleted. We can also define indexes (keys), specify links between tables, and impose constraints between database tables. The most important DDL statements in SQL are: •CREATE TABLE - creates a new database table •ALTER TABLE - alters (changes) a database table •DROP TABLE - deletes a database table •CREATE INDEX - creates an index (search key) •DROP INDEX - deletes an index
  • 11. SQL The SELECT Statement The SELECT statement is used to select data from a table. The tabular result is stored in a result table (called the result-set). Syntax SELECT column_name(s) FROM table_name
  • 12. To select the columns named "LastName" and "FirstName", use a SELECT statement like this: SELECT LastName, FirstName FROM Persons Persons LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes Svendson Tove Borgvn 23 Sandnes Pettersen Kari Storgt 20 Stavanger výsledok LastName FirstName Hansen Ola Svendson Tove Pettersen Kari
  • 13. To select all columns from the "Persons" table, use a * symbol instead of column names, like this: SELECT * FROM Persons LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes Svendson Tove Borgvn 23 Sandnes Pettersen Kari Storgt 20 Stavanger Select All Columns
  • 14. The result from a SQL query is stored in a result-set. Most database software systems allow navigation of the result set with programming functions, like: Move-To-First- Record, Get-Record-Content, Move-To-Next-Record, etc. Programming functions like these are not a part of this tutorial. To learn about accessing data with function calls, please visit our ADO tutorial. The Result Set
  • 15. Eliminating Duplicates 15 SELECT DISTINCT category FROM Product Compare to: SELECT category FROM Product Category Gadgets Gadgets Photography Household Category Gadgets Photography Household
  • 16. The DISTINCT keyword is used to return only distinct (different) values. The SELECT statement returns information from table columns. But what if we only want to select distinct elements? With SQL, all we need to do is to add a DISTINCT keyword to the SELECT statement: Syntax SELECT DISTINCT column_name(s) FROM table_name The SELECT DISTINCT Statement
  • 17. To select ALL values from the column named "Company" we use a SELECT statement like this: SELECT Company FROM Orders Orders Company OrderNumber Sega 3412 W3Schools 2312 Trio 4678 W3Schools 6798 Company Sega W3Schools Trio W3Schools Using the DISTINCT keyword
  • 18. Note that "W3Schools" is listed twice in the result-set. To select only DIFFERENT values from the column named "Company" we use a SELECT DISTINCT statement like this: SELECT DISTINCT Company FROM Orders Company Sega W3Schools Trio Orders Company OrderNumber Sega 3412 W3Schools 2312 Trio 4678 W3Schools 6798
  • 19. Select All Columns The WHERE clause is used to specify a selection criterion. The WHERE Clause To conditionally select data from a table, a WHERE clause can be added to the SELECT statement. Syntax SELECT column FROM table WHERE column operator value
  • 20. With the WHERE clause, the following operators can be used: Operator Description = Equal <> Not equal > Greater than < Less than >= Greater than or equal <= Less than or equal BETWEEN Between an inclusive range LIKE Search for a pattern Note: In some versions of SQL the <> operator may be written as !=
  • 21. Using the WHERE Clause To select only the persons living in the city "Sandnes", we add a WHERE clause to the SELECT statement: SELECT * FROM Persons WHERE City='Sandnes' LastName FirstName Address City Year Hansen Ola Timoteivn 10 Sandnes 1951 Svendson Tove Borgvn 23 Sandnes 1978 Svendson Stale Kaivn 18 Sandnes 1980 Pettersen Kari Storgt 20 Stavanger 1960 LastName FirstName Address City Year Hansen Ola Timoteivn 10 Sandnes 1951 Svendson Tove Borgvn 23 Sandnes 1978 Svendson Stale Kaivn 18 Sandnes 1980
  • 22. Ordering the Results 22 SELECT pname, price, manufacturer FROM Product WHERE category=‘gizmo’ AND price > 50 ORDER BY price, pname Ordering is ascending, unless you specify the DESC keyword. Ties are broken by the second attribute on the ORDER BY list, etc.
  • 23. Ordering the Results 23 SELECT category FROM Product ORDER BY pname PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi ?
  • 24. Ordering the Results 24 SELECT DISTINCT category FROM Product ORDER BY category Compare to: Category Gadgets Household Photography SELECT category FROM Product ORDER BY pname ?
  • 25. Joins in SQL  Connect two or more tables: 25 PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan What is the connection between them ?
  • 26. Joins 26 Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all products under $200 manufactured in Japan; return their names and prices. SELECT pname, price FROM Product, Company WHERE manufacturer=cname AND country=‘Japan’ AND price <= 200 Join between Product and Company
  • 27. Joins in SQL 27 PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan PName Price SingleTouch $149.99 SELECT pname, price FROM Product, Company WHERE manufacturer=cname AND country=‘Japan’ AND price <= 200
  • 28. Joins 28 Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all countries that manufacture some product in the ‘Gadgets’ category. SELECT country FROM Product, Company WHERE manufacturer=cname AND category=‘Gadgets’
  • 29. Joins in SQL 29 Name Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan SELECT country FROM Product, Company WHERE manufacturer=cname AND category=‘Gadgets’ Country ?? ?? What is the problem ? What’s the solution ?
  • 30. Joins 30 Product (pname, price, category, manufacturer) Purchase (buyer, seller, store, product) Person(persname, phoneNumber, city) Find names of people living in Seattle that bought some product in the ‘Gadgets’ category, and the names of the stores they bought such product from SELECT DISTINCT persname, store FROM Person, Purchase, Product WHERE persname=buyer AND product = pname AND city=‘Seattle’ AND category=‘Gadgets’
  • 31. Joins in SQL 31 Name Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan SELECT country FROM Product, Company WHERE manufacturer=cname AND category=‘Gadgets’ Country ?? ?? What is the problem ? What’s the solution ?
  • 32. Joins 32 Product (pname, price, category, manufacturer) Purchase (buyer, seller, store, product) Person(persname, phoneNumber, city) Find names of people living in Seattle that bought some product in the ‘Gadgets’ category, and the names of the stores they bought such product from SELECT DISTINCT persname, store FROM Person, Purchase, Product WHERE persname=buyer AND product = pname AND city=‘Seattle’ AND category=‘Gadgets’
  • 33. When are two tables related?  You guess they are  I tell you so  Foreign keys are a method for schema designers to tell you so (7.1)  A foreign key states that a column is a reference to the key of another table ex: Product.manufacturer is foreign key of Company  Gives information and enforces constraint 33
  • 34. Disambiguating Attributes  Sometimes two relations have the same attr: Person(pname, address, worksfor) Company(cname, address) 34 SELECT DISTINCT pname, address FROM Person, Company WHERE worksfor = cname SELECT DISTINCT Person.pname, Company.address FROM Person, Company WHERE Person.worksfor = Company.cname Which address ?
  • 35. Tuple Variables 35 SELECT DISTINCT x.store FROM Purchase AS x, Purchase AS y WHERE x.product = y.product AND y.store = ‘BestBuy’ Find all stores that sold at least one product that the store ‘BestBuy’ also sold: Answer (store) Product (pname, price, category, manufacturer) Purchase (buyer, seller, store, product) Person(persname, phoneNumber, city)
  • 36. Tuple Variables 36 General rule: tuple variables introduced automatically by the system: Product (name, price, category, manufacturer) Becomes: Doesn’t work when Product occurs more than once: In that case the user needs to define variables explicitly. SELECT name FROM Product WHERE price > 100 SELECT Product.name FROM Product AS Product WHERE Product.price > 100
  • 37. Using Quotes Note that we have used single quotes around the conditional values in the examples. SQL uses single quotes around text values (most database systems will also accept double quotes). Numeric values should not be enclosed in quotes. For text values: This is correct: SELECT * FROM Persons WHERE FirstName='Tove' This is wrong: SELECT * FROM Persons WHERE FirstName=Tove
  • 38. The LIKE Condition The LIKE condition is used to specify a search for a pattern in a column. Syntax SELECT column FROM table WHERE column LIKE pattern A "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.
  • 39. Using LIKE The following SQL statement will return persons with first names that start with an 'O': SELECT * FROM Persons WHERE FirstName LIKE 'O%' The following SQL statement will return persons with first names that end with an 'a': SELECT * FROM Persons WHERE FirstName LIKE '%a'
  • 40. Using LIKE 2 The following SQL statement will return persons with first names that contain the pattern 'la': SELECT * FROM Persons WHERE FirstName LIKE '%la%'
  • 41. SQL The INSERT INTO Statement
  • 42. The INSERT INTO Statement The INSERT INTO statement is used to insert new rows into a table. Syntax INSERT INTO table_name VALUES (value1, value2,....) You can also specify the columns for which you want to insert data: INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)
  • 43. Insert a New Row LastName FirstName Address City Pettersen Kari Storgt 20 Stavanger And this SQL statement: INSERT INTO Persons VALUES ('Hetland', 'Camilla', 'Hagabakka 24', 'Sandnes') LastName FirstName Address City Pettersen Kari Storgt 20 Stavanger Hetland Camilla Hagabakka 24 Sandnes
  • 44. Insert Data in Specified ColumnsLastName FirstName Address City Pettersen Kari Storgt 20 Stavanger Hetland Camilla Hagabakka 24 Sandnes And This SQL statement: INSERT INTO Persons (LastName, Address) VALUES ('Rasmussen', 'Storgt 67') LastName FirstName Address City Pettersen Kari Storgt 20 Stavanger Hetland Camilla Hagabakka 24 Sandnes Rasmussen Storgt 67
  • 45. SQL The UPDATE Statement
  • 46. The Update Statement The UPDATE statement is used to modify the data in a table. Syntax UPDATE table_name SET column_name = new_value WHERE column_name = some_value
  • 47. Update one Column in a Row LastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger Rasmussen Storgt 67 We want to add a first name to the person with a last name of "Rasmussen": UPDATE Person SET FirstName = 'Nina' WHERE LastName = 'Rasmussen' LastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger Rasmussen Nina Storgt 67
  • 48. Update several Columns in a Row We want to change the address and add the name of the city: UPDATE Person SET Address = 'Stien 12', City = 'Stavanger' WHERE LastName = 'Rasmussen' LastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger Rasmussen Nina Stien 12 Stavanger LastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger Rasmussen Storgt 67
  • 49. SQL The Delete Statement
  • 50. The Delete Statement The DELETE statement is used to delete rows in a table. Syntax DELETE FROM table_name WHERE column_name = some_value
  • 51. LastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger Rasmussen Nina Stien 12 Stavanger
  • 52. Delete a RowLastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger Rasmussen Nina Stien 12 Stavanger "Nina Rasmussen" is going to be deleted: DELETE FROM Person WHERE LastName = 'Rasmussen' LastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger
  • 53. Delete All RowsIt is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact: DELETE FROM table_name Or DELETE * FROM table_name
  • 54. Exercises 54 Product (pname, price, category, manufacturer) Purchase (buyer, seller, store, product) Company (cname, stock price, country) Person(per-name, phone number, city) Ex #1: Find people who bought telephony products. Ex #2: Find names of people who bought American products Ex #3: Find names of people who bought American products and they live in Seattle. Ex #4: Find people who have both bought and sold something. Ex #5: Find people who bought stuff from Joe or bought products from a company whose stock prices is more than $50.