SQL
Structured Query Language
Rita Sinha
IUCAA
June 2007 1
SQL
Simple Query Language
A standard computer language for
accessing and manipulating database systems.
Rita Sinha
IUCAA
June 2007 2
Outline
SQL Ingredients
Syntax, Key words
DATABASES…
Example queries
Link to web tutorials on SQL
MySQL - demo
3
October 2007
Database
Database is a structure that can house information about
many different type of objects as well as the relationships
among those objects.
A tool is required to easily manipulate such information. This
is called a database management system or DBMS.
Most popular approach for manipulating data in a relational
DBMS is SQL
4
October 2007
Structure of the database
Organized collection of data (Tables)
Entries in the Table are single-valued
Each column in the Table should have an unique
name (called attribute name)
All values in a column are values of the same
attribute
Each row is distinct
Order of columns and rows is flexible
5
October 2007
Terminology
Relation Table File
Tuple Row Record
Attribute Column Field
6
October 2007
Data Types
Integer(size), int(size), smallint(size), tinyint(size)
Holds integers only. The maximum number of digits specified in
parenthesis.
decimal(size,d), numeric(size,d)
Holds numbers with fractions. The maximum number of digits are
specified in "size". The maximum number of digits to the right of the
decimal is specified in "d".
CHAR(size)
Holds a fixed length string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis.
varchar(size)
Holds a variable length string (can contain letters, numbers, and
special characters). The maximum size is specified in parenthesis.
DATEdate(yyyymmdd) Holds a date
TIME Holds time
7
October 2007
What is SQL ?
An ANSI standard computer language
Allows you to access a database
Execute queries against a database
Retrieve data from a database
Insert new records in a database
Delete records from a database
Update records in a database
Querying Language for database programs like
MySQL, MS SQL Server, ADQL, MS Access, DB2,
Informix, Oracle, Sybase, etc.
Easy
Note: Some database systems require a semicolon at the end of the SQL statement
8
October 2007
Ingredients
SQL Data Manipulation Language (DML)
It includes syntax to update, insert and delete records.
SQL Data Definition Language (DDL)
It permits database tables to be created or deleted, define
indexes (keys), specify links between tables and impose
constraints between database tables.
9
October 2007
Data Manipulation Language (DML) :
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
Data Definition Language (DDL) :
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
WHERE – impose constraints
10
October 2007
Basic Syntax
Select - Attributes, column name
From - Table name
Where - Restrictions, constraints
[Note: To query data on an existing database which you are not allowed to change]
For example: SALARY Name Rank Amount Years
Select name, rank, amount Select *
from salary from Salary
where amount = 10000 where amount > 10000
Note: SQL statements are not case sensitive.
11
October 2007
Select …
Alias – column name alias
Select Z as Redshift or Select psfmag_u as u
Operations are permitted in ‘select’ clause
Select cos(angle) from Triangles or
Select (income-expenditure) as Savings
12
October 2007
Select …
DISTINCT
Outputs only one entry/row of data for every group of rows/entries
that is identical.
ORDERS
OrderNumber Time Name Items Amount
400 1300 Mr. R. Sharma TomatoSoup 45
401 1310 Mr. S. Pal Fried rice 80
402 1315 Mr. R. Sharma Pasta 75
Select DISTINCT name
FROM Orders
13
October 2007
From …
Alias – table name alias
From Phototable as P or From Spectable as S
14
October 2007
Where …
The following operators can be used with the WHERE clause:
Operator Description
= Equal
<> or != Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
15
October 2007
Where …
AND and OR join two or more conditions in a WHERE clause.
The AND operator displays a row if ALL conditions listed are true.
The OR operator displays a row if ANY of the conditions listed are true.
For example: SALARY Name Rank Amount Years
Select name, rank From Salary
Where amount >25000 and years > 5
Select name, rank From Salary
Where amount > 25000 or years > 5
16
October 2007
Where …
Using Quotes
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:
SELECT *
FROM Persons
WHERE Surname=‘Sharma’
17
October 2007
Where …
LIKE condition- used to specify a search for a pattern in a column.
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.
For example:
The following SQL statement will return persons with first names that start
with an 'R':
SELECT * FROM Persons
WHERE FirstName LIKE ‘R%’
The following SQL statement will return persons with first names that end
with an 'a':
SELECT * FROM Persons
WHERE FirstName LIKE ‘%a’
18
October 2007
Duplication of attributes ?
When two tables have a common attribute or
column name then we write both the table name
and the column name, separated by a period. By
this we qualify the names.
Making Life Easier…
19
October 2007
Duplication of attributes ?
When two tables have a common attribute or column name
then we write both the table name and the column name,
separated by a period. By this we qualify the names.
For example- Consider a movies database
Table: 1980s Table: 1990s
Title Star Director Storage Title Star Director Storage
Select 1980s.title, 1980s.star, 1990s.title,1990s.star
or
Select o.title, o.star, n.title, n.star
from 1980s as o, 1990s as n
20
October 2007
Where …
Join
Selects data from two or more tables to make the result complete or to bind
data together across tables, without repeating all of the data in every table.
Tables in a database can be related to each other with keys called
primary key. Each primary key value must be unique within the
table.
For example: SALARY EmployeeID Name Amount
RANK EmployeeID Position Years
SELECT Salary.EmployeeID, Salary.Name, Rank.Position,
Rank.Years
FROM Salary, Rank
WHERE Salary.EmployeeID=Rank.EmployeeID
21
October 2007
Join …
To select data from two tables with the JOIN keyword.
The INNER JOIN returns all rows from both tables where there is a match.
For example: SALARY EmployeeID Name Amount
RANK EmployeeID Position Years
SELECT Salary.EmployeeID, Salary.Name, Rank.Position
FROM Salary
INNER JOIN Rank
ON Salary.EmployeeID=Rank.EmployeeID
22
October 2007
Order by
The ORDER BY clause is used to sort the rows.
To display the names in alphabetical order:
SELECT Name, Marks FROM Marksheet
ORDER BY Name
To display the company names in numerical order:
SELECT Marks FROM Marksheet
ORDER BY Marks
To display the names in reverse alphabetical order:
SELECT Name, Marks FROM Marksheet
ORDER BY Name DESC
23
October 2007
Group by
GROUP BY...
possible to find the aggregate functions like (SUM) for each individual
group of column values.
For example, consider
Table containing expenditure by persons employed under a research project
DST2006
Date Name Item Amount
To find the total expenditure under each person:
SELECT Name, SUM(Amount) FROM DST2006
GROUP BY Name
In place of where we use HAVING to specify conditions
HAVING SUM(amount) > 5000
24
October 2007
Functions
SQL has a lot of built-in functions for counting and other calculations-
SELECT function(column) FROM table
Types of Functions
The basic types of functions are:
Aggregate Functions: operate against a collection of values, but
return a single value.
AVG(column), COUNT(column), MAX(column),
MIN(column), STDEV(column), SUM(column)
Scalar functions: operate against a single value, and return a single
value based on the input value.
MOD(x,y), ABS(x), ROUND(c,decimals)
25
October 2007
Summary Select … from ….. where
Select ….
AS (alias for column)
DISTINCT
COUNT
From …
AS (alias for table)
Where …
AND/OR
BETWEEN
JOIN
GROUP BY
ORDER BY
26
October 2007
Links
http://www.w3schools.com/sql/sql_quickref.asp
http://cas.sdss.org/astro/en/help/howto/search
27
October 2007
MySQL
Runs on all platforms: Unix/Linux, Windows
Runs as a daemon under Unix/Linux and service under
windows
Latest binary and source code distributions at:
http://www.mysql.com
28
October 2007