SQL
Introduction to SQL
Atul Pant
Table of Contents
SQL Intro .......................................................................................................................................................3
SQL Select .....................................................................................................................................................4
SQL Select Distinct ........................................................................................................................................4
SQL Where.....................................................................................................................................................4
SQL And & Or ...............................................................................................................................................5
SQL Order By ................................................................................................................................................5
SQL Insert Into ...............................................................................................................................................5
SQL Update ....................................................................................................................................................6
SQL Delete .....................................................................................................................................................6
SQL Select Top ..............................................................................................................................................6
SQL Select Top ..............................................................................................................................................7
SQL Like ........................................................................................................................................................7
SQL Wildcards ...............................................................................................................................................7
SQL IN ...........................................................................................................................................................8
SQL Between .................................................................................................................................................8
SQL Join ........................................................................................................................................................8
SQL Inner Join ...............................................................................................................................................9
SQL Left Join .................................................................................................................................................9
SQL Right Join...............................................................................................................................................9
SQL Full Join ...............................................................................................................................................10
SQL Union ...................................................................................................................................................10
SQL Select Into ............................................................................................................................................10
SQL Insert Into Select ..................................................................................................................................11
SQL Create Database ...................................................................................................................................11
SQL Create Table .........................................................................................................................................11
SQL Constraints ...........................................................................................................................................12
SQL Not Null ...............................................................................................................................................12
SQL Unique .................................................................................................................................................13
SQL Primary Key.........................................................................................................................................13
SQL Foreign Key .........................................................................................................................................14
SQL Check ...................................................................................................................................................14
SQL Default .................................................................................................................................................14
SQL Create Index .........................................................................................................................................15
SQL Drop .....................................................................................................................................................15
SQL Alter .....................................................................................................................................................15
SQL

Page 1
SQL Null ......................................................................................................................................................16
SQL General Data Types .............................................................................................................................17
References ....................................................................................................................................................18

SQL

Page 2
SQL Intro
What is SQL?
 SQL stands for Structured Query Language
 SQL lets you access and manipulate databases
 SQL is an ANSI (American National Standards Institute) standard

What Can SQL do?
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

What is RDBMS?
 RDBMS stands for Relational Database Management System.
 RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server,
IBM DB2, Oracle, MySQL, and Microsoft Access.
 The data in RDBMS is stored in database objects called tables.
 A table is a collection of related data entries and it consists of columns and rows.

SQL

Page 3
SQL Select
Definition

The SELECT statement is used to select data from a database.
The result is stored in a result table, called the result-set.

Syntax

SELECT column_name
FROM table_name;

Example

SELECT City FROM Customers;

SQL Select Distinct
Definition

The SELECT DISTINCT statement is used to return only distinct
(different) values.

Syntax

SELECT DISTINCT column_name,column_name
FROM table_name;

Example

SELECT DISTINCT City FROM Customers;

SQL Where
Definition

The WHERE clause is used to filter records.

Syntax

SELECT column_name, column_name
FROM table_name
WHERE column_name operator value;

Example

SELECT * FROM Customers
WHERE Country='Mexico';

SQL

Page 4
SQL And & Or
The AND operator displays a record if both the first condition AND the
Definition

second condition are true.
The OR operator displays a record if either the first condition OR the
second condition is true.

Syntax

SELECT column_name, FROM table_name
WHERE column_name (AND/OR) column_name;

Example

SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';

SQL Order By
Definition
Syntax
Example

The ORDER BY keyword is used to sort the result-set by one or more
columns.
SELECT column_name, column_name
FROM table_name
ORDER BY column_name, column_name ASC|DESC;
SELECT * FROM Customers
ORDER BY Country DESC;

SQL Insert Into
Definition

Syntax

Example

SQL

The INSERT INTO statement is used to insert new records in a table.
INSERT INTO table_name
VALUES (value1, value2, value3,...);
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...);
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');

Page 5
SQL Update
Definition
Syntax
Example

The UPDATE statement is used to update existing records in a table.
UPDATE table_name
SET column1=value1, column2=value2,...
WHERE some_column=some_value;
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste';

SQL Delete
Definition

The DELETE statement is used to delete rows in a table.

Syntax

DELETE FROM table_name
WHERE some_column=some_value;

Example

DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste' AND
ContactName='Maria Anders';

SQL Select Top
Definition
Syntax
Example

SQL

The SELECT TOP clause is used to specify the number of records to
return.
SELECT TOP number|percent column_name(s)
FROM table_name;
SELECT TOP 2 * FROM Customers;
SELECT TOP 50 PERCENT * FROM Customers;

Page 6
SQL Select Top
Definition
Syntax
Example

The SELECT TOP clause is used to specify the number of records to
return.
SELECT TOP number|percent column_name(s)
FROM table_name;
SELECT TOP 2 * FROM Customers;
SELECT TOP 50 PERCENT * FROM Customers;

SQL Like
Definition

The LIKE operator is used to search for a specified pattern in a column.

Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;

Example

SELECT * FROM Customers
WHERE City LIKE 's%';

SQL Wildcards
Definition

Wildcard characters are used with the SQL LIKE operator. They are used

Syntax

to search for data within a table.
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
SELECT * FROM Customers
WHERE City LIKE 'ber%';

Example

SELECT * FROM Customers
WHERE City LIKE '_erlin';
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';

SQL

Page 7
SQL IN
Definition

The IN operator allows you to specify multiple values in a WHERE clause.

Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);

Example

SELECT * FROM Customers
WHERE City IN ('Paris','London');

SQL Between
Definition

The BETWEEN operator selects values within a range. The values can be

Syntax

numbers, text, or dates.
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

Example

SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/04/1996# AND #07/09/1996#;

SQL Join
Definition

Syntax

Example

SQL

An SQL JOIN clause is used to combine rows from two or more tables,
based on a common field between them.
SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;
SELECT Orders.OrderID, Customers.CustomerName,
Orders.OrderDate
FROM Orders
JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;

Page 8
SQL Inner Join
The INNER JOIN keyword selects all rows from both tables as long as
Definition

Syntax

Example

there is a match between the columns in both tables. INNER JOIN is
the same as JOIN.
SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

SQL Left Join
The LEFT JOIN keyword returns all rows from the left table (table1),
Definition

Syntax

Example

with the matching rows in the right table (table2). The result is NULL
in the right side when there is no match.
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

SQL Right Join
The RIGHT JOIN keyword returns all rows from the right table
Definition

Syntax

Example

SQL

(table2), with the matching rows in the left table (table1). The result
is NULL in the left side when there is no match.
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
SELECT Orders.OrderID, Employees.FirstName
FROM Orders
RIGHT JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY Orders.OrderID;

Page 9
SQL Full Join
Definition

Syntax

Example

The FULL OUTER JOIN keyword returns all rows from the left table
(table1) and from the right table (table2).
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

SQL Union
Definition
Syntax

Example

The SQL UNION operator combines the result of two or more SELECT
statements.
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

SQL Select Into
Definition
Syntax
Example

SQL

The SELECT INTO statement selects data from one table and inserts it
into a new table.
SELECT *
INTO newtable [IN externaldb]
FROM table1;
SELECT *
INTO CustomersBackup2013
FROM Customers;

Page 10
SQL Insert Into Select
Definition

Syntax

Example

The INSERT INTO SELECT statement copies data from one table and
inserts it into an existing table.
INSERT INTO table2
SELECT * FROM table1;
INSERT INTO table2
(column_name(s))
SELECT column_name(s)
FROM table1;
INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers;
INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers
WHERE Country='Germany';

SQL Create Database
Definition

The CREATE DATABASE statement is used to create a database.

Syntax

CREATE DATABASE dbname;

Example

CREATE DATABASE my_db;

SQL Create Table
The CREATE TABLE statement is used to create a table in a database.
Definition

Syntax

SQL

Tables are organized into rows and columns; and each table must have a
name.
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);

Page 11
Example

CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

SQL Constraints
Definition

Syntax

Example

SQL constraints are used to specify rules for the data in a table.
CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);
NOT NULL- Indicates that a column cannot store NULL value.
UNIQUE- Ensures that each row for a column must have a unique
value.
PRIMARY KEY- A combination of a NOT NULL and UNIQUE. Ensures
that a column (or combination of two or more columns) have an
unique identity which helps to find a particular record in a
table more easily and quickly.
FOREIGN KEY- Ensure the referential integrity of the data in
one table to match values in another table
CHECK- Ensures that the value in a column meets a specific
condition.
DEFAULT- Specifies a default value when specified none for
this column.

SQL Not Null
Definition

Example

SQL

The NOT NULL constraint enforces a column to NOT accept NULL
values.
CREATE TABLE Persons NotNull
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

Page 12
SQL Unique
Definition

Example

The UNIQUE constraint uniquely identifies each record in a database
table.
CREATE TABLE Persons Unique
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
)

SQL Primary Key
The PRIMARY KEY constraint uniquely identifies each record in a
database table.

Definition

Primary keys must contain unique values.
A primary key column cannot contain NULL values.
Each table should have a primary key, and each table can have only ONE

Example

SQL

primary key.
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)

Page 13
SQL Foreign Key
Definition

Example

A FOREIGN KEY in one table points to a PRIMARY KEY in another
table.
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)

SQL Check
Definition

Example

The CHECK constraint is used to limit the value range that can be
placed in a column.
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
)

SQL Default
The DEFAULT constraint is used to insert a default value into a column.
Definition

Example

SQL

The default value will be added to all new records, if no other value is
specified.
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
)

Page 14
SQL Create Index
The CREATE INDEX statement is used to create indexes in tables.
Definition

Indexes allow the database application to find data fast; without reading
the whole table.

Syntax

CREATE INDEX index_name
ON table_name (column_name)

Example

CREATE INDEX PIndex
ON Persons (LastName)

SQL Drop
The DROP statement is used to delete a table or database.
Definition

Syntax
Example

TRANCATE statement is when we only want to delete the data inside
the table, and not the table itself.
DROP TABLE table_name
DROP DATABASE database_name
TRUNCATE TABLE table_name
DROP TABLE Person
DROP DATABASE test
Truncate TABLE Person

SQL Alter
Definition

The ALTER TABLE statement is used to add, delete, or modify columns

Syntax

ALTER TABLE table_name
ADD column_name datatype

Example

ALTER TABLE Persons
DROP COLUMN DateOfBirth

SQL

in an existing table.

Page 15
SQL Null
NULL values represent missing unknown data.
Definition

By default, a table column can hold NULL values.
Note: It is not possible to compare NULL and 0; they are not

Syntax

Example

SQL

equivalent.
SELECT column_name FROM table
WHERE column_name IS NULL
SELECT column_name FROM table
WHERE column_name IS NOT NULL
SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NULL
SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NOT NULL

Page 16
SQL General Data Types
Database Type

Description

CHARACTER(n)

Character string. Fixed-length n

VARCHAR(n) or
CHARACTER VARYING(n)
BINARY(n)

Character string. Variable length. Maximum
length n
Binary string. Fixed-length n

BOOLEAN

Stores TRUE or FALSE values

VARBINARY(n) or
BINARY VARYING(n)
INTEGER(p)

Binary string. Variable length. Maximum length
n
Integer numerical (no decimal). Precision p

SMALLINT

Integer numerical (no decimal). Precision 5

INTEGER

Integer numerical (no decimal). Precision 10

BIGINT

Integer numerical (no decimal). Precision 19

DECIMAL(p,s)

REAL

Exact numerical, precision p, scale s. Example:
decimal(5,2) is a number that has 3 digits
before the decimal and 2 digits after the
decimal
Exact numerical, precision p, scale s. (Same as
DECIMAL)
Approximate numerical, mantissa precision p. A
floating number in base 10 exponential
notation. The size argument for this type
consists of a single number specifying the
minimum precision
Approximate numerical, mantissa precision 7

FLOAT

Approximate numerical, mantissa precision 16

DOUBLE PRECISION

Approximate numerical, mantissa precision 16

DATE

Stores year, month, and day values

TIME

Stores hour, minute, and second values

TIMESTAMP

Stores year, month, day, hour, minute, and
second values
Composed of a number of integer fields,
representing a period of time, depending on the
type of interval
A set-length and ordered collection of elements

NUMERIC(p,s)
FLOAT(p)

INTERVAL
ARRAY
MULTISET
XML

SQL

A variable-length and unordered collection of
elements
Stores XML data

Page 17
References
http://www.w3schools.com/sql/

SQL

Page 18

More Related Content

PPTX
DDL(Data defination Language ) Using Oracle
PPT
Sql server T-sql basics ppt-3
DOC
A must Sql notes for beginners
PPTX
DDL,DML,SQL Functions and Joins
PPT
Intro to tsql unit 7
PPT
Internet Environment
PDF
Sql tutorial
PPTX
Database Systems - SQL - DCL Statements (Chapter 3/4)
DDL(Data defination Language ) Using Oracle
Sql server T-sql basics ppt-3
A must Sql notes for beginners
DDL,DML,SQL Functions and Joins
Intro to tsql unit 7
Internet Environment
Sql tutorial
Database Systems - SQL - DCL Statements (Chapter 3/4)

What's hot (19)

PPTX
Introduction to SQL (for Chicago Booth MBA technology club)
PDF
View & index in SQL
PDF
Sql tutorial-Structured query language
PPTX
SQL Commands
PPT
Sql intro & ddl 1
PPTX
PDF
Using T-SQL
PPT
Introduction to structured query language (sql)
PPTX
Sql commands
DOC
Dbms lab Manual
PPTX
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
PPTX
SQL Server Learning Drive
DOCX
PPTX
Introduction to SQL
PPTX
Creating database using sql commands
PPTX
DML using oracle
PDF
Steps towards of sql server developer
PDF
Sql ch 12 - creating database
PPT
Chapter 07 ddl_sql
Introduction to SQL (for Chicago Booth MBA technology club)
View & index in SQL
Sql tutorial-Structured query language
SQL Commands
Sql intro & ddl 1
Using T-SQL
Introduction to structured query language (sql)
Sql commands
Dbms lab Manual
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
SQL Server Learning Drive
Introduction to SQL
Creating database using sql commands
DML using oracle
Steps towards of sql server developer
Sql ch 12 - creating database
Chapter 07 ddl_sql
Ad

Viewers also liked (9)

PDF
Cloud computing
PDF
E commerce Testing
PDF
Performance Requirement Gathering
PDF
Performance Test Plan - Sample 2
DOC
Cloud Computing Documentation Report
PDF
Cloud computing Basics
PPT
Cloud computing simple ppt
PDF
Cloud computing project report
PPTX
Introduction of Cloud computing
Cloud computing
E commerce Testing
Performance Requirement Gathering
Performance Test Plan - Sample 2
Cloud Computing Documentation Report
Cloud computing Basics
Cloud computing simple ppt
Cloud computing project report
Introduction of Cloud computing
Ad

Similar to Sql (20)

DOC
Complete Sql Server querries
PPTX
PDF
PPTX
SQL NAD DB.pptx
PPT
INTRODUCTION TO SQL QUERIES REALTED BRIEF
DOCX
PPTX
Structure Query Language Advance Training
DOC
Introduction to sql
DOCX
Book HH - SQL MATERIAL
PPTX
SQL Query
PDF
SQL_BASIC AND ADVANCED.pdf
PDF
SQL Basics and Advanced for analytics.pdf
PDF
Learning SQL
PDF
Learning SQL
DOCX
SQL report
PPTX
Chapter-9-MySQL.pptxxzrtyryrydfdsfdsfdsrter
PPTX
SQL Assessment Command Statements
PPTX
Sql slid
PDF
kupdf.net_sql-ebook-w3schoolscom.pdf
Complete Sql Server querries
SQL NAD DB.pptx
INTRODUCTION TO SQL QUERIES REALTED BRIEF
Structure Query Language Advance Training
Introduction to sql
Book HH - SQL MATERIAL
SQL Query
SQL_BASIC AND ADVANCED.pdf
SQL Basics and Advanced for analytics.pdf
Learning SQL
Learning SQL
SQL report
Chapter-9-MySQL.pptxxzrtyryrydfdsfdsfdsrter
SQL Assessment Command Statements
Sql slid
kupdf.net_sql-ebook-w3schoolscom.pdf

More from Atul Pant (7)

PDF
Loadrunner vs Jmeter
PDF
LoadRunner Performance Testing
PDF
Performance Test Plan - Sample 1
PDF
Testing check list
PDF
Payment gateway testing
PDF
Jmeter Performance Testing
PDF
Unix command
Loadrunner vs Jmeter
LoadRunner Performance Testing
Performance Test Plan - Sample 1
Testing check list
Payment gateway testing
Jmeter Performance Testing
Unix command

Recently uploaded (20)

PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PDF
Developing a website for English-speaking practice to English as a foreign la...
PDF
WOOl fibre morphology and structure.pdf for textiles
PDF
Unlock new opportunities with location data.pdf
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PDF
Zenith AI: Advanced Artificial Intelligence
PDF
Hindi spoken digit analysis for native and non-native speakers
DOCX
search engine optimization ppt fir known well about this
PDF
Five Habits of High-Impact Board Members
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
The various Industrial Revolutions .pptx
PPTX
Chapter 5: Probability Theory and Statistics
PPT
What is a Computer? Input Devices /output devices
PPTX
Tartificialntelligence_presentation.pptx
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
Getting Started with Data Integration: FME Form 101
PPTX
Modernising the Digital Integration Hub
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
Developing a website for English-speaking practice to English as a foreign la...
WOOl fibre morphology and structure.pdf for textiles
Unlock new opportunities with location data.pdf
O2C Customer Invoices to Receipt V15A.pptx
Zenith AI: Advanced Artificial Intelligence
Hindi spoken digit analysis for native and non-native speakers
search engine optimization ppt fir known well about this
Five Habits of High-Impact Board Members
Getting started with AI Agents and Multi-Agent Systems
Assigned Numbers - 2025 - Bluetooth® Document
The various Industrial Revolutions .pptx
Chapter 5: Probability Theory and Statistics
What is a Computer? Input Devices /output devices
Tartificialntelligence_presentation.pptx
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Getting Started with Data Integration: FME Form 101
Modernising the Digital Integration Hub
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
A contest of sentiment analysis: k-nearest neighbor versus neural network

Sql

  • 2. Table of Contents SQL Intro .......................................................................................................................................................3 SQL Select .....................................................................................................................................................4 SQL Select Distinct ........................................................................................................................................4 SQL Where.....................................................................................................................................................4 SQL And & Or ...............................................................................................................................................5 SQL Order By ................................................................................................................................................5 SQL Insert Into ...............................................................................................................................................5 SQL Update ....................................................................................................................................................6 SQL Delete .....................................................................................................................................................6 SQL Select Top ..............................................................................................................................................6 SQL Select Top ..............................................................................................................................................7 SQL Like ........................................................................................................................................................7 SQL Wildcards ...............................................................................................................................................7 SQL IN ...........................................................................................................................................................8 SQL Between .................................................................................................................................................8 SQL Join ........................................................................................................................................................8 SQL Inner Join ...............................................................................................................................................9 SQL Left Join .................................................................................................................................................9 SQL Right Join...............................................................................................................................................9 SQL Full Join ...............................................................................................................................................10 SQL Union ...................................................................................................................................................10 SQL Select Into ............................................................................................................................................10 SQL Insert Into Select ..................................................................................................................................11 SQL Create Database ...................................................................................................................................11 SQL Create Table .........................................................................................................................................11 SQL Constraints ...........................................................................................................................................12 SQL Not Null ...............................................................................................................................................12 SQL Unique .................................................................................................................................................13 SQL Primary Key.........................................................................................................................................13 SQL Foreign Key .........................................................................................................................................14 SQL Check ...................................................................................................................................................14 SQL Default .................................................................................................................................................14 SQL Create Index .........................................................................................................................................15 SQL Drop .....................................................................................................................................................15 SQL Alter .....................................................................................................................................................15 SQL Page 1
  • 3. SQL Null ......................................................................................................................................................16 SQL General Data Types .............................................................................................................................17 References ....................................................................................................................................................18 SQL Page 2
  • 4. SQL Intro What is SQL?  SQL stands for Structured Query Language  SQL lets you access and manipulate databases  SQL is an ANSI (American National Standards Institute) standard What Can SQL do?  SQL can execute queries against a database  SQL can retrieve data from a database  SQL can insert records in a database  SQL can update records in a database  SQL can delete records from a database  SQL can create new databases  SQL can create new tables in a database  SQL can create stored procedures in a database  SQL can create views in a database  SQL can set permissions on tables, procedures, and views What is RDBMS?  RDBMS stands for Relational Database Management System.  RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.  The data in RDBMS is stored in database objects called tables.  A table is a collection of related data entries and it consists of columns and rows. SQL Page 3
  • 5. SQL Select Definition The SELECT statement is used to select data from a database. The result is stored in a result table, called the result-set. Syntax SELECT column_name FROM table_name; Example SELECT City FROM Customers; SQL Select Distinct Definition The SELECT DISTINCT statement is used to return only distinct (different) values. Syntax SELECT DISTINCT column_name,column_name FROM table_name; Example SELECT DISTINCT City FROM Customers; SQL Where Definition The WHERE clause is used to filter records. Syntax SELECT column_name, column_name FROM table_name WHERE column_name operator value; Example SELECT * FROM Customers WHERE Country='Mexico'; SQL Page 4
  • 6. SQL And & Or The AND operator displays a record if both the first condition AND the Definition second condition are true. The OR operator displays a record if either the first condition OR the second condition is true. Syntax SELECT column_name, FROM table_name WHERE column_name (AND/OR) column_name; Example SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; SQL Order By Definition Syntax Example The ORDER BY keyword is used to sort the result-set by one or more columns. SELECT column_name, column_name FROM table_name ORDER BY column_name, column_name ASC|DESC; SELECT * FROM Customers ORDER BY Country DESC; SQL Insert Into Definition Syntax Example SQL The INSERT INTO statement is used to insert new records in a table. INSERT INTO table_name VALUES (value1, value2, value3,...); INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...); INSERT INTO Customers (CustomerName, City, Country) VALUES ('Cardinal', 'Stavanger', 'Norway'); Page 5
  • 7. SQL Update Definition Syntax Example The UPDATE statement is used to update existing records in a table. UPDATE table_name SET column1=value1, column2=value2,... WHERE some_column=some_value; UPDATE Customers SET ContactName='Alfred Schmidt', City='Hamburg' WHERE CustomerName='Alfreds Futterkiste'; SQL Delete Definition The DELETE statement is used to delete rows in a table. Syntax DELETE FROM table_name WHERE some_column=some_value; Example DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste' AND ContactName='Maria Anders'; SQL Select Top Definition Syntax Example SQL The SELECT TOP clause is used to specify the number of records to return. SELECT TOP number|percent column_name(s) FROM table_name; SELECT TOP 2 * FROM Customers; SELECT TOP 50 PERCENT * FROM Customers; Page 6
  • 8. SQL Select Top Definition Syntax Example The SELECT TOP clause is used to specify the number of records to return. SELECT TOP number|percent column_name(s) FROM table_name; SELECT TOP 2 * FROM Customers; SELECT TOP 50 PERCENT * FROM Customers; SQL Like Definition The LIKE operator is used to search for a specified pattern in a column. Syntax SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern; Example SELECT * FROM Customers WHERE City LIKE 's%'; SQL Wildcards Definition Wildcard characters are used with the SQL LIKE operator. They are used Syntax to search for data within a table. SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern; SELECT * FROM Customers WHERE City LIKE 'ber%'; Example SELECT * FROM Customers WHERE City LIKE '_erlin'; SELECT * FROM Customers WHERE City LIKE '[!bsp]%'; SQL Page 7
  • 9. SQL IN Definition The IN operator allows you to specify multiple values in a WHERE clause. Syntax SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...); Example SELECT * FROM Customers WHERE City IN ('Paris','London'); SQL Between Definition The BETWEEN operator selects values within a range. The values can be Syntax numbers, text, or dates. SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2; SELECT * FROM Products WHERE Price BETWEEN 10 AND 20; Example SELECT * FROM Products WHERE Price NOT BETWEEN 10 AND 20; SELECT * FROM Orders WHERE OrderDate BETWEEN #07/04/1996# AND #07/09/1996#; SQL Join Definition Syntax Example SQL An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them. SELECT column_name(s) FROM table1 JOIN table2 ON table1.column_name=table2.column_name; SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders JOIN Customers ON Orders.CustomerID=Customers.CustomerID; Page 8
  • 10. SQL Inner Join The INNER JOIN keyword selects all rows from both tables as long as Definition Syntax Example there is a match between the columns in both tables. INNER JOIN is the same as JOIN. SELECT column_name(s) FROM table1 JOIN table2 ON table1.column_name=table2.column_name; SELECT Customers.CustomerName, Orders.OrderID FROM Customers INNER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName; SQL Left Join The LEFT JOIN keyword returns all rows from the left table (table1), Definition Syntax Example with the matching rows in the right table (table2). The result is NULL in the right side when there is no match. SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name=table2.column_name; SELECT Customers.CustomerName, Orders.OrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName; SQL Right Join The RIGHT JOIN keyword returns all rows from the right table Definition Syntax Example SQL (table2), with the matching rows in the left table (table1). The result is NULL in the left side when there is no match. SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name=table2.column_name; SELECT Orders.OrderID, Employees.FirstName FROM Orders RIGHT JOIN Employees ON Orders.EmployeeID=Employees.EmployeeID ORDER BY Orders.OrderID; Page 9
  • 11. SQL Full Join Definition Syntax Example The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2). SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name=table2.column_name; SELECT Customers.CustomerName, Orders.OrderID FROM Customers FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName; SQL Union Definition Syntax Example The SQL UNION operator combines the result of two or more SELECT statements. SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2; SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY City; SQL Select Into Definition Syntax Example SQL The SELECT INTO statement selects data from one table and inserts it into a new table. SELECT * INTO newtable [IN externaldb] FROM table1; SELECT * INTO CustomersBackup2013 FROM Customers; Page 10
  • 12. SQL Insert Into Select Definition Syntax Example The INSERT INTO SELECT statement copies data from one table and inserts it into an existing table. INSERT INTO table2 SELECT * FROM table1; INSERT INTO table2 (column_name(s)) SELECT column_name(s) FROM table1; INSERT INTO Customers (CustomerName, Country) SELECT SupplierName, Country FROM Suppliers; INSERT INTO Customers (CustomerName, Country) SELECT SupplierName, Country FROM Suppliers WHERE Country='Germany'; SQL Create Database Definition The CREATE DATABASE statement is used to create a database. Syntax CREATE DATABASE dbname; Example CREATE DATABASE my_db; SQL Create Table The CREATE TABLE statement is used to create a table in a database. Definition Syntax SQL Tables are organized into rows and columns; and each table must have a name. CREATE TABLE table_name ( column_name1 data_type(size), column_name2 data_type(size), column_name3 data_type(size), .... ); Page 11
  • 13. Example CREATE TABLE Persons ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) ); SQL Constraints Definition Syntax Example SQL constraints are used to specify rules for the data in a table. CREATE TABLE table_name ( column_name1 data_type(size) constraint_name, column_name2 data_type(size) constraint_name, column_name3 data_type(size) constraint_name, .... ); NOT NULL- Indicates that a column cannot store NULL value. UNIQUE- Ensures that each row for a column must have a unique value. PRIMARY KEY- A combination of a NOT NULL and UNIQUE. Ensures that a column (or combination of two or more columns) have an unique identity which helps to find a particular record in a table more easily and quickly. FOREIGN KEY- Ensure the referential integrity of the data in one table to match values in another table CHECK- Ensures that the value in a column meets a specific condition. DEFAULT- Specifies a default value when specified none for this column. SQL Not Null Definition Example SQL The NOT NULL constraint enforces a column to NOT accept NULL values. CREATE TABLE Persons NotNull ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) ) Page 12
  • 14. SQL Unique Definition Example The UNIQUE constraint uniquely identifies each record in a database table. CREATE TABLE Persons Unique ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), UNIQUE (P_Id) ) SQL Primary Key The PRIMARY KEY constraint uniquely identifies each record in a database table. Definition Primary keys must contain unique values. A primary key column cannot contain NULL values. Each table should have a primary key, and each table can have only ONE Example SQL primary key. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (P_Id) ) Page 13
  • 15. SQL Foreign Key Definition Example A FOREIGN KEY in one table points to a PRIMARY KEY in another table. CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) ) SQL Check Definition Example The CHECK constraint is used to limit the value range that can be placed in a column. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CHECK (P_Id>0) ) SQL Default The DEFAULT constraint is used to insert a default value into a column. Definition Example SQL The default value will be added to all new records, if no other value is specified. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CHECK (P_Id>0) ) Page 14
  • 16. SQL Create Index The CREATE INDEX statement is used to create indexes in tables. Definition Indexes allow the database application to find data fast; without reading the whole table. Syntax CREATE INDEX index_name ON table_name (column_name) Example CREATE INDEX PIndex ON Persons (LastName) SQL Drop The DROP statement is used to delete a table or database. Definition Syntax Example TRANCATE statement is when we only want to delete the data inside the table, and not the table itself. DROP TABLE table_name DROP DATABASE database_name TRUNCATE TABLE table_name DROP TABLE Person DROP DATABASE test Truncate TABLE Person SQL Alter Definition The ALTER TABLE statement is used to add, delete, or modify columns Syntax ALTER TABLE table_name ADD column_name datatype Example ALTER TABLE Persons DROP COLUMN DateOfBirth SQL in an existing table. Page 15
  • 17. SQL Null NULL values represent missing unknown data. Definition By default, a table column can hold NULL values. Note: It is not possible to compare NULL and 0; they are not Syntax Example SQL equivalent. SELECT column_name FROM table WHERE column_name IS NULL SELECT column_name FROM table WHERE column_name IS NOT NULL SELECT LastName,FirstName,Address FROM Persons WHERE Address IS NULL SELECT LastName,FirstName,Address FROM Persons WHERE Address IS NOT NULL Page 16
  • 18. SQL General Data Types Database Type Description CHARACTER(n) Character string. Fixed-length n VARCHAR(n) or CHARACTER VARYING(n) BINARY(n) Character string. Variable length. Maximum length n Binary string. Fixed-length n BOOLEAN Stores TRUE or FALSE values VARBINARY(n) or BINARY VARYING(n) INTEGER(p) Binary string. Variable length. Maximum length n Integer numerical (no decimal). Precision p SMALLINT Integer numerical (no decimal). Precision 5 INTEGER Integer numerical (no decimal). Precision 10 BIGINT Integer numerical (no decimal). Precision 19 DECIMAL(p,s) REAL Exact numerical, precision p, scale s. Example: decimal(5,2) is a number that has 3 digits before the decimal and 2 digits after the decimal Exact numerical, precision p, scale s. (Same as DECIMAL) Approximate numerical, mantissa precision p. A floating number in base 10 exponential notation. The size argument for this type consists of a single number specifying the minimum precision Approximate numerical, mantissa precision 7 FLOAT Approximate numerical, mantissa precision 16 DOUBLE PRECISION Approximate numerical, mantissa precision 16 DATE Stores year, month, and day values TIME Stores hour, minute, and second values TIMESTAMP Stores year, month, day, hour, minute, and second values Composed of a number of integer fields, representing a period of time, depending on the type of interval A set-length and ordered collection of elements NUMERIC(p,s) FLOAT(p) INTERVAL ARRAY MULTISET XML SQL A variable-length and unordered collection of elements Stores XML data Page 17