SlideShare uma empresa Scribd logo
1 de 19
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

Mais conteúdo relacionado

Mais procurados

Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Jennifer Berk
 
Sql tutorial-Structured query language
Sql tutorial-Structured query languageSql tutorial-Structured query language
Sql tutorial-Structured query languageMayank Bansal
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)Sabana Maharjan
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive TechandMate
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commandsBelle Wx
 
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developerAhsan Kabir
 
Sql ch 12 - creating database
Sql ch 12 - creating databaseSql ch 12 - creating database
Sql ch 12 - creating databaseMukesh Tekwani
 
Chapter 07 ddl_sql
Chapter 07 ddl_sqlChapter 07 ddl_sql
Chapter 07 ddl_sqlNazir Ahmed
 

Mais procurados (19)

Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)
 
View & index in SQL
View & index in SQLView & index in SQL
View & index in SQL
 
Sql tutorial-Structured query language
Sql tutorial-Structured query languageSql tutorial-Structured query language
Sql tutorial-Structured query language
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Sql intro & ddl 1
Sql intro & ddl 1Sql intro & ddl 1
Sql intro & ddl 1
 
SQL
SQLSQL
SQL
 
Using T-SQL
Using T-SQL Using T-SQL
Using T-SQL
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Sql commands
Sql commandsSql commands
Sql commands
 
Dbms lab Manual
Dbms lab ManualDbms lab Manual
Dbms lab Manual
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
 
Query
QueryQuery
Query
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
DML using oracle
 DML using oracle DML using oracle
DML using oracle
 
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developer
 
Sql ch 12 - creating database
Sql ch 12 - creating databaseSql ch 12 - creating database
Sql ch 12 - creating database
 
Chapter 07 ddl_sql
Chapter 07 ddl_sqlChapter 07 ddl_sql
Chapter 07 ddl_sql
 

Destaque

Cloud computing
Cloud computingCloud computing
Cloud computingAtul Pant
 
E commerce Testing
E commerce TestingE commerce Testing
E commerce TestingAtul Pant
 
Performance Requirement Gathering
Performance Requirement GatheringPerformance Requirement Gathering
Performance Requirement GatheringAtul Pant
 
Performance Test Plan - Sample 2
Performance Test Plan - Sample 2Performance Test Plan - Sample 2
Performance Test Plan - Sample 2Atul Pant
 
Cloud Computing Documentation Report
Cloud Computing Documentation ReportCloud Computing Documentation Report
Cloud Computing Documentation ReportUsman Sait
 
Cloud computing Basics
Cloud computing BasicsCloud computing Basics
Cloud computing BasicsSagar Sane
 
Cloud computing simple ppt
Cloud computing simple pptCloud computing simple ppt
Cloud computing simple pptAgarwaljay
 
Cloud computing project report
Cloud computing project reportCloud computing project report
Cloud computing project reportNaveed Farooq
 
Introduction of Cloud computing
Introduction of Cloud computingIntroduction of Cloud computing
Introduction of Cloud computingRkrishna Mishra
 

Destaque (9)

Cloud computing
Cloud computingCloud computing
Cloud computing
 
E commerce Testing
E commerce TestingE commerce Testing
E commerce Testing
 
Performance Requirement Gathering
Performance Requirement GatheringPerformance Requirement Gathering
Performance Requirement Gathering
 
Performance Test Plan - Sample 2
Performance Test Plan - Sample 2Performance Test Plan - Sample 2
Performance Test Plan - Sample 2
 
Cloud Computing Documentation Report
Cloud Computing Documentation ReportCloud Computing Documentation Report
Cloud Computing Documentation Report
 
Cloud computing Basics
Cloud computing BasicsCloud computing Basics
Cloud computing Basics
 
Cloud computing simple ppt
Cloud computing simple pptCloud computing simple ppt
Cloud computing simple ppt
 
Cloud computing project report
Cloud computing project reportCloud computing project report
Cloud computing project report
 
Introduction of Cloud computing
Introduction of Cloud computingIntroduction of Cloud computing
Introduction of Cloud computing
 

Semelhante a Sql

SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowPavithSingh
 
chap 7.ppt(sql).ppt
chap 7.ppt(sql).pptchap 7.ppt(sql).ppt
chap 7.ppt(sql).pptarjun431527
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxBhupendraShahi6
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSabrinaShanta2
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSaiMiryala1
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...Jürgen Ambrosi
 
chapter9-SQL.pptx
chapter9-SQL.pptxchapter9-SQL.pptx
chapter9-SQL.pptxYaser52
 

Semelhante a Sql (20)

SQL
SQLSQL
SQL
 
MYSQL.ppt
MYSQL.pptMYSQL.ppt
MYSQL.ppt
 
Lab
LabLab
Lab
 
Sql
SqlSql
Sql
 
Chap 7
Chap 7Chap 7
Chap 7
 
LECTURE NOTES.pdf
LECTURE NOTES.pdfLECTURE NOTES.pdf
LECTURE NOTES.pdf
 
LECTURE NOTES.pdf
LECTURE NOTES.pdfLECTURE NOTES.pdf
LECTURE NOTES.pdf
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Module02
Module02Module02
Module02
 
SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data   SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data
 
SQL Query
SQL QuerySQL Query
SQL Query
 
chap 7.ppt(sql).ppt
chap 7.ppt(sql).pptchap 7.ppt(sql).ppt
chap 7.ppt(sql).ppt
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
Review of SQL
Review of SQLReview of SQL
Review of SQL
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
 
Hira
HiraHira
Hira
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
chapter9-SQL.pptx
chapter9-SQL.pptxchapter9-SQL.pptx
chapter9-SQL.pptx
 

Mais de Atul Pant

Loadrunner vs Jmeter
Loadrunner vs JmeterLoadrunner vs Jmeter
Loadrunner vs JmeterAtul Pant
 
LoadRunner Performance Testing
LoadRunner Performance TestingLoadRunner Performance Testing
LoadRunner Performance TestingAtul Pant
 
Performance Test Plan - Sample 1
Performance Test Plan - Sample 1Performance Test Plan - Sample 1
Performance Test Plan - Sample 1Atul Pant
 
Testing check list
Testing check listTesting check list
Testing check listAtul Pant
 
Payment gateway testing
Payment gateway testingPayment gateway testing
Payment gateway testingAtul Pant
 
Jmeter Performance Testing
Jmeter Performance TestingJmeter Performance Testing
Jmeter Performance TestingAtul Pant
 
Unix command
Unix commandUnix command
Unix commandAtul Pant
 

Mais de Atul Pant (7)

Loadrunner vs Jmeter
Loadrunner vs JmeterLoadrunner vs Jmeter
Loadrunner vs Jmeter
 
LoadRunner Performance Testing
LoadRunner Performance TestingLoadRunner Performance Testing
LoadRunner Performance Testing
 
Performance Test Plan - Sample 1
Performance Test Plan - Sample 1Performance Test Plan - Sample 1
Performance Test Plan - Sample 1
 
Testing check list
Testing check listTesting check list
Testing check list
 
Payment gateway testing
Payment gateway testingPayment gateway testing
Payment gateway testing
 
Jmeter Performance Testing
Jmeter Performance TestingJmeter Performance Testing
Jmeter Performance Testing
 
Unix command
Unix commandUnix command
Unix command
 

Último

Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 

Último (20)

Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 

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