SlideShare a Scribd company logo
SQL
(Structured Query Language)
A LANGUAGE OF DATABASE
SQL Overview
SQL is a programming language for Relational Databases. It is designed over relational algebra
and tuple relational calculus. SQL comes as a package with all major distributions of RDBMS.
SQL comprises both data definition and data manipulation languages. Using the data definition
properties of SQL, one can design and modify database schema, whereas data manipulation
properties allows SQL to store and retrieve data from database.
Characteristics of SQL
SQL allows the user to create, update, delete, and retrieve data from a database.
* SQL is very simple and easy to learn.
* SQL works with database programs like DB2, Oracle, MS Access, Sybase, MS SQL Sever etc.
Advantages of SQL
• High Speed:
SQL Queries can be used to retrieve large amounts of records from a database quickly and efficiently.
• Well Defined Standards Exist:
SQL databases use long-established standard, which is being adopted by ANSI & ISO. Non-SQL
databases do not adhere to any clear standard.
• No Coding Required:
Using standard SQL it is easier to manage database systems without having to write substantial
amount of code.
•Emergence of ORDBMS:
Previously SQL databases were synonymous with relational database. With the emergence of Object
Oriented DBMS, object storage capabilities are extended to relational databases.
Disadvantages of SQL
• Difficulty in Interfacing:
Interfacing an SQL database is more complex than adding a few lines of code.
• More Features Implemented in Proprietary way:
Although SQL databases conform to ANSI & ISO standards, some databases go for proprietary
extensions to standard SQL to ensure vendor lock-in.
SQL Data Types
1. BIGINT Data Type
2. BOOLEAN Data Type
3. CHAR Data Type
4. DECIMAL Data Type
5. DOUBLE Data Type
6. FLOAT Data Type
7. INT Data Type
8. SMALLINT Data Type
9. STRING Data Type
10. TIMESTAMP Data Type
11. TINYINT Data Type
12. VARCHAR Data Type
SQL Literals
The terms literal and constant value are synonymous and refer to a fixed data value
1. Numeric Literals
2. String Literals: String needs to be in single quotes
3. Boolean Literals: TRUE or FALSE
4. Timestamp Literals
5. NULL
String Literals
Use the text literal notation to specify values whenever 'string' or appears in the syntax of
expressions, conditions, SQL functions, and SQL statements in other parts of this reference
'Hello'
'ORACLE.dbs‘
q'!name LIKE '%DBMS_%%'!'
q'<'So,' she said, 'It's finished.'>‘
Numeric Literals
You must use the integer notation to specify an integer whenever integer appears in
expressions, conditions, SQL functions, and SQL statements described in other parts of this
reference. 25
+6.34
0.5
25e-03
-1
25f
+6.34F
0.5d
-1D
Date Time Literals
You can specify a DATE value as a string literal, or you can convert a character or numeric value
to a date value with the TO_DATE function. DATE literals are the only case in which Oracle
Database accepts a TO_DATE expression in place of a string literal.
To specify a DATE value as a literal, you must use the Gregorian calendar. You can specify an ANSI
literal, as shown in this example:
DATE '1998-12-25‘
TO_DATE('98-DEC-25 17:30','YY-MON-DD HH24:MI')
Timestamp Literals
TIMESTAMP '1997-01-31 09:26:56.66 +02:00‘
TIMESTAMP '1999-04-15 8:00:00 US/Pacific‘ (with Zone)
Types of SQL Commands
1. Data Definition Language
2. Data Manipulation Language
Data Definition Language(DDL)
CREATE
Creates new databases, tables and views from RDBMS.
Create database tutorialspoint;
Create table article;
Create view for_students;
DROP
Drops commands, views, tables, and databases from RDBMS.
Drop object_type object_name;
Drop database tutorialspoint;
Drop table article;
Drop view for_students;
ALTER
Modifies database schema.
This command adds an attribute in the relation article with the
name subject of string type.
Alter table article add subject
varchar;
Data Manipulation Language(DML)
SQL is equipped with data manipulation language (DML). DML modifies the database instance by
inserting, updating and deleting its data. DML is responsible for all froms data modification in a
database. SQL contains the following set of commands in its DML section −
1. SELECT/FROM/WHERE
2. INSERT INTO/VALUES
3. UPDATE/SET/WHERE
4. DELETE FROM/WHERE
These basic constructs allow database programmers and users to enter data and information into the
database and retrieve efficiently using a number of filter options.
Select author_name From book_author Where age > 50;
INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ])
UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE condition]
DELETE FROM table_name [WHERE condition];
Tables
A relational database system contains one or more objects called tables. The data or information
for the database are stored in these tables. Tables are uniquely identified by their names and are
comprised of columns and rows. Columns contain the column name, data type, and any other
attributes for the column. Rows contain the records or data for the columns. Here is a sample
table called "weather".
city, state, high, and low are the columns. The rows contain the data for this table:
Weather
city state high low
Phoenix Arizona 105 90
Tucson Arizona 101 92
Flagstaff Arizona 88 69
San Diego California 77 60
Albuquerque New Mexico 80 72
Creating Table
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);
CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Syntax Example
PersonID LastName FirstName Address City
Insert into Table
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
INSERT INTO persons(PersonID,LastName,FirstName,Address,City)
VALUES(1011,’Mehta’,’Kunal’,’myaddress’,’Haridwar’);
CREATE TABLE persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
PersonID LastName FirstName Address City
1011 Mehta Kunal Myaddress Haridwar
SELECT STATEMENT
• SELECT column_name,column_name FROM table_name;
• SELECT * FROM table_name;
CustomerID CustomerName ContactName Address City PostalCode Country
1 HARI Maria Anders Obere Str. 57 Berlin 12209 Germany
2 RAM Ana Trujillo Avda. de la
Constitución
2222
México D.F. 05021 Mexico
3 SHYAM Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
SELECT DISTINCT
• In a table, a column may contain many duplicate values; and sometimes you only want to list
the different (distinct) values.
• The DISTINCT keyword can be used to return only distinct (different) values.
CustomerID CustomerName ContactName Address City PostalCode Country
1 HARI Maria Anders Obere Str. 57 Berlin 12209 Germany
2 RAM Ana Trujillo Avda. de la
Constitución
2222
México D.F. 05021 Mexico
3 SHYAM Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
SELECT DISTINCT column_name,column_name FROM table_name;
WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified criterion.
SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
SELECT * FROM Customers
WHERE Country='Mexico';
CustomerID CustomerName City Country
1 HARI Berlin Germany
2 RAM México D.F. Mexico
3 SHYAM México D.F. Mexico
AND & OR Clause
The AND operator displays a record if both the first condition AND the second condition are
true.
The OR operator displays a record if either the first condition OR the second condition is true.
CustomerID CustomerName City Country
1 HARI Berlin Germany
2 RAM México D.F. Mexico
3 SHYAM México D.F. Mexico
SELECT * FROM Customers
WHERE Country='Germany'
AND City='Berlin';
SELECT * FROM Customers
WHERE City='México D.F.'
OR City='München';
SELECT * FROM Customers
WHERE Country='Germany'
AND (City='Berlin' OR City='München');
DELETE STATEMENT
DELETE FROM table_name WHERE some_column=some_value;
CustomerID CustomerName City PostalCode Country
1 HARI Berlin 12209 Germany
2 RAM México D.F. 05021 Mexico
3 SHYAM México D.F. 05023 Mexico
DELETE FROM Customers WHERE CustomerName=‘Hari’ AND City=‘Berlin';
DELETE FROM Customers WHERE CustomerName=‘Ram’ AND Country=‘Germany';
UPDATE
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
CustomerID CustomerName City PostalCode Country
1 HARI Berlin 12209 Germany
2 RAM México D.F. 05021 Mexico
3 SHYAM México D.F. 05021 Mexico
CustomerID CustomerName City PostalCode Country
1 HARI Berlin 12209 Germany
2 RAM México D.F. 05021 Mexico
3 SHYAM Hamburg 05021 Germany
UPDATE Customers
SET City=‘Hamburg’,
COUNTRY=‘GERMANY’
WHERE CustomerName=‘SHYAM’;
CustomerID CustomerName City PostalCode Country
1 HARI Hamburg 12209 Germany
2 RAM Hamburg 05021 Germany
3 SHYAM Hamburg 05021 Germany
UPDATE Customers
SET City=‘Hamburg',
City=‘Germany';
ORDER BY Clause
The ORDER BY keyword is used to sort the result-set by one or more columns.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a
descending order, you can use the DESC keyword.
SELECT column_name, column_name
FROM table_name
ORDER BY column_name ASC|DESC;
SELECT * FROM Customers
ORDER BY Country;
CustomerID CustomerName City Country
1 HARI Berlin Germany
2 RAM México D.F. Mexico
3 SHYAM México D.F. Mexico
SELECT * FROM Customers
ORDER BY Country DESC;
DROP & TRUNCATE
DROP TABLE table_name
DROP DATABASE database_name
TRUNCATE TABLE table_name
ALTER TABLE STATEMENT
ALTER TABLE table_name
ADD column_name datatype
ALTER TABLE table_name
DROP COLUMN column_name
P_Id FirstName Address City
1 Ola Timoteivn 10 Sandnes
2 Tove Borgvn 23 Sandnes
3 Kari Storgt 20 Stavanger
ALTER TABLE Persons
ADD DOB date
P_Id FirstName Address City DOB
1 Ola Timoteivn 10 Sandnes
2 Tove Borgvn 23 Sandnes
3 Kari Storgt 20 Stavange
r
ALTER TABLE Persons
ALTER COLUMN DOB year
Creating Views
Syntax:
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Example:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No
Query from View: SELECT * FROM [Current Product List]
Updating Views
Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Example:
CREATE OR REPLACE VIEW [Current Product List] AS
SELECT ProductID,ProductName,Category
FROM Products
WHERE Discontinued=No
Aggregate Functions
1. AVG() - Returns the average value
2. COUNT() - Returns the number of rows
3. MAX() - Returns the largest value
4. MIN() - Returns the smallest value
5. SUM() - Returns the sum
SQL Scalar Functions
1. UCASE() - Converts a field to upper case
a) SELECT UCASE(column_name) FROM table_name;
2. LCASE() - Converts a field to lower case
a) SELECT LCASE(column_name) FROM table_name;
3. MID() - Extract characters from a text field
a) SELECT SUBSTRING(column_name,start,length) AS some_name FROM table_name;
4. LEN() - Returns the length of a text field
5. ROUND() - Rounds a numeric field to the number of decimals specified
6. NOW() - Returns the current system date and time
7. FORMAT() - Formats how a field is to be displayed
a) SELECT ProductName, Price, FORMAT(Now(),'YYYY-MM-DD') AS PerDate FROM Products;
LIKE
The LIKE operator is used to search for a specified pattern in a column.
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
SELECT * FROM Customers
WHERE City LIKE 's%';
SELECT * FROM Customers
WHERE Country LIKE '%land%';
SELECT * FROM Customers
WHERE Country NOT LIKE '%land%';
IN
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
SELECT * FROM Customers
WHERE City IN ('Paris','London');
BETWEEN
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
◦ SQL statement selects all products with a price BETWEEN 10 and 20
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
◦ To display the products outside the range of the previous example, use NOT BETWEEN
Joins
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field
between them.
There are four types of JOINS.
1. INNER JOIN: Returns all rows when there is at least one match in BOTH tables
2. LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
3. RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
4. FULL JOIN: Return all rows when there is a match in ONE of the tables
Inner Join
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo
Emparedados y
helados
Ana Trujillo Mexico
3 Antonio Moreno
Taquería
Antonio Moreno Mexico
SELECT Orders.OrderID, Customers.CustomerName,
Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
OrderID CustomerName OrderDate
10308 Ana Trujillo Emparedados y helados 9/18/1996
Output:
Customers
Orders
…
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;
Left Join
The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in
the right table (table2). The result is NULL in the right side when there is no match.
Syntax:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
or
SELECT column_name(s)
FROM table1
LEFT OUTER 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;
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo
Emparedados y
helados
Ana Trujillo Mexico
3 Antonio Moreno
Taquería
Antonio Moreno Mexico
CustomerName OrderID
Alfreds Futterkiste null
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería null
Customers
Orders
Output:
Right Join
The RIGHT JOIN keyword returns all rows from the right table (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;
or
SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;
…
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
RIGHT JOIN Customers
ON Orders.CustomerID=Customers.CustomerID
ORDER BY Orders.OrderID;
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo
Emparedados y
helados
Ana Trujillo Mexico
3 Antonio Moreno
Taquería
Antonio Moreno Mexico
Customers
Orders
Output:
OrderID CustomerName
Alfreds Futterkiste
10309 Ana Trujillo Emparedados y helados
Antonio Moreno Taquería
Full Join or Full Outer Join
• The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right
table (table2).
• The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
…
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo
Emparedados y
helados
Ana Trujillo Mexico
3 Antonio Moreno
Taquería
Antonio Moreno Mexico
Customers
Orders
Output:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
CustomerName OrderID
Alfreds Futterkiste
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería
10309
10310
Union
The UNION operator is used to combine the result-set of two or more SELECT statements.
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Syntax:
This will list all
the DISTINCT city
names from both the
tables.
Output:Query:
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Syntax:
This will list all
the city names
includes duplicate
from both the
tables.
Output:Query:
SQL Operators
1. Arithmetic Operators
2. BETWEEN Operator
3. Comparison Operators
4. EXISTS Operator
5. IN Operator
6. IS NULL Operator
7. LIKE Operator
8. Logical Operators
9. REGEXP Operator
10. RLIKE Operator
Intersection
Minus
THANKS

More Related Content

What's hot (20)

PPTX
introdution to SQL and SQL functions
farwa waqar
 
PPT
MySQL and its basic commands
Bwsrang Basumatary
 
PPTX
SQL Commands
Sachidananda M H
 
PPT
1 - Introduction to PL/SQL
rehaniltifat
 
PDF
Create table
Nitesh Singh
 
PPT
MySQL
Gouthaman V
 
PPT
Databases: Normalisation
Damian T. Gordon
 
PPTX
joins in database
Sultan Arshad
 
PPT
MYSQL.ppt
webhostingguy
 
PPT
Working with Databases and MySQL
Nicole Ryan
 
PPTX
SQL commands
GirdharRatne
 
PPTX
SQL - Structured query language introduction
Smriti Jain
 
PPTX
Basic SQL and History
SomeshwarMoholkar
 
PPTX
SQL Basics
Hammad Rasheed
 
PPT
SQL.ppt
Ranjit273515
 
PPT
Sql join
Vikas Gupta
 
PPTX
Sql commands
Pooja Dixit
 
PPTX
Integrity Constraints
madhav bansal
 
PPT
Database Relationships
wmassie
 
introdution to SQL and SQL functions
farwa waqar
 
MySQL and its basic commands
Bwsrang Basumatary
 
SQL Commands
Sachidananda M H
 
1 - Introduction to PL/SQL
rehaniltifat
 
Create table
Nitesh Singh
 
Databases: Normalisation
Damian T. Gordon
 
joins in database
Sultan Arshad
 
MYSQL.ppt
webhostingguy
 
Working with Databases and MySQL
Nicole Ryan
 
SQL commands
GirdharRatne
 
SQL - Structured query language introduction
Smriti Jain
 
Basic SQL and History
SomeshwarMoholkar
 
SQL Basics
Hammad Rasheed
 
SQL.ppt
Ranjit273515
 
Sql join
Vikas Gupta
 
Sql commands
Pooja Dixit
 
Integrity Constraints
madhav bansal
 
Database Relationships
wmassie
 

Similar to SQL Queries Information (20)

PDF
LECTURE NOTES.pdf
ChryslerPanaguiton
 
PDF
LECTURE NOTES.pdf
ChryslerPanaguiton
 
PDF
Chapter 4 Structured Query Language
Eddyzulham Mahluzydde
 
DOCX
Database Management Lab -SQL Queries
shamim hossain
 
PDF
Rdbms day3
Nitesh Singh
 
PPTX
DBMS Part-3.pptx
Prof. Dr. K. Adisesha
 
PPT
INTRODUCTION TO SQL QUERIES REALTED BRIEF
VADAPALLYPRAVEENKUMA1
 
PDF
Sql
Atul Pant
 
PPT
Sql 2006
Cathie101
 
PPTX
Lab
neelam_rawat
 
PPTX
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SabrinaShanta2
 
PPTX
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SaiMiryala1
 
PPTX
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
BhupendraShahi6
 
PDF
6_SQL.pdf
LPhct2
 
DOCX
DBMS
Karan Thakkar
 
PPT
Interactive SQL: SQL, Features of SQL, DDL & DML
IsakkiDeviP
 
PPTX
ADV Powepoint 2 Lec.pptx
ArjayBalberan1
 
LECTURE NOTES.pdf
ChryslerPanaguiton
 
LECTURE NOTES.pdf
ChryslerPanaguiton
 
Chapter 4 Structured Query Language
Eddyzulham Mahluzydde
 
Database Management Lab -SQL Queries
shamim hossain
 
Rdbms day3
Nitesh Singh
 
DBMS Part-3.pptx
Prof. Dr. K. Adisesha
 
INTRODUCTION TO SQL QUERIES REALTED BRIEF
VADAPALLYPRAVEENKUMA1
 
Sql 2006
Cathie101
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SabrinaShanta2
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SaiMiryala1
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
BhupendraShahi6
 
6_SQL.pdf
LPhct2
 
Interactive SQL: SQL, Features of SQL, DDL & DML
IsakkiDeviP
 
ADV Powepoint 2 Lec.pptx
ArjayBalberan1
 
Ad

More from Nishant Munjal (20)

PPTX
Database Management System
Nishant Munjal
 
PPTX
Functions & Recursion
Nishant Munjal
 
PPTX
Array, string and pointer
Nishant Munjal
 
PPTX
Programming in C
Nishant Munjal
 
PPTX
Introduction to computers
Nishant Munjal
 
PPTX
Unix Administration
Nishant Munjal
 
PPTX
Shell Programming Concept
Nishant Munjal
 
PPTX
VI Editor
Nishant Munjal
 
PPTX
Introduction to Unix
Nishant Munjal
 
PPTX
Routing Techniques
Nishant Munjal
 
PPTX
Asynchronous Transfer Mode
Nishant Munjal
 
PPTX
Overview of Cloud Computing
Nishant Munjal
 
PPTX
Database Design and Normalization Techniques
Nishant Munjal
 
PPTX
Concurrency Control
Nishant Munjal
 
PPTX
Transaction Processing Concept
Nishant Munjal
 
PPTX
Database Management System
Nishant Munjal
 
PPTX
Relational Data Model Introduction
Nishant Munjal
 
PPTX
Virtualization, A Concept Implementation of Cloud
Nishant Munjal
 
PPTX
Technical education benchmarks
Nishant Munjal
 
PPSX
Bluemix Introduction
Nishant Munjal
 
Database Management System
Nishant Munjal
 
Functions & Recursion
Nishant Munjal
 
Array, string and pointer
Nishant Munjal
 
Programming in C
Nishant Munjal
 
Introduction to computers
Nishant Munjal
 
Unix Administration
Nishant Munjal
 
Shell Programming Concept
Nishant Munjal
 
VI Editor
Nishant Munjal
 
Introduction to Unix
Nishant Munjal
 
Routing Techniques
Nishant Munjal
 
Asynchronous Transfer Mode
Nishant Munjal
 
Overview of Cloud Computing
Nishant Munjal
 
Database Design and Normalization Techniques
Nishant Munjal
 
Concurrency Control
Nishant Munjal
 
Transaction Processing Concept
Nishant Munjal
 
Database Management System
Nishant Munjal
 
Relational Data Model Introduction
Nishant Munjal
 
Virtualization, A Concept Implementation of Cloud
Nishant Munjal
 
Technical education benchmarks
Nishant Munjal
 
Bluemix Introduction
Nishant Munjal
 
Ad

Recently uploaded (20)

PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PDF
WD2(I)-RFQ-GW-1415_ Shifting and Filling of Sand in the Pond at the WD5 Area_...
ShahadathHossain23
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PDF
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PDF
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
PPTX
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PPTX
Distribution reservoir and service storage pptx
dhanashree78
 
PDF
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
PPT
Testing and final inspection of a solar PV system
MuhammadSanni2
 
PDF
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
PDF
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PPT
New_school_Engineering_presentation_011707.ppt
VinayKumar304579
 
PDF
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
PPTX
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
PDF
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
PPTX
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
WD2(I)-RFQ-GW-1415_ Shifting and Filling of Sand in the Pond at the WD5 Area_...
ShahadathHossain23
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
Distribution reservoir and service storage pptx
dhanashree78
 
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
Testing and final inspection of a solar PV system
MuhammadSanni2
 
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
Design Thinking basics for Engineers.pdf
CMR University
 
New_school_Engineering_presentation_011707.ppt
VinayKumar304579
 
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 

SQL Queries Information

  • 1. SQL (Structured Query Language) A LANGUAGE OF DATABASE
  • 2. SQL Overview SQL is a programming language for Relational Databases. It is designed over relational algebra and tuple relational calculus. SQL comes as a package with all major distributions of RDBMS. SQL comprises both data definition and data manipulation languages. Using the data definition properties of SQL, one can design and modify database schema, whereas data manipulation properties allows SQL to store and retrieve data from database.
  • 3. Characteristics of SQL SQL allows the user to create, update, delete, and retrieve data from a database. * SQL is very simple and easy to learn. * SQL works with database programs like DB2, Oracle, MS Access, Sybase, MS SQL Sever etc.
  • 4. Advantages of SQL • High Speed: SQL Queries can be used to retrieve large amounts of records from a database quickly and efficiently. • Well Defined Standards Exist: SQL databases use long-established standard, which is being adopted by ANSI & ISO. Non-SQL databases do not adhere to any clear standard. • No Coding Required: Using standard SQL it is easier to manage database systems without having to write substantial amount of code. •Emergence of ORDBMS: Previously SQL databases were synonymous with relational database. With the emergence of Object Oriented DBMS, object storage capabilities are extended to relational databases.
  • 5. Disadvantages of SQL • Difficulty in Interfacing: Interfacing an SQL database is more complex than adding a few lines of code. • More Features Implemented in Proprietary way: Although SQL databases conform to ANSI & ISO standards, some databases go for proprietary extensions to standard SQL to ensure vendor lock-in.
  • 6. SQL Data Types 1. BIGINT Data Type 2. BOOLEAN Data Type 3. CHAR Data Type 4. DECIMAL Data Type 5. DOUBLE Data Type 6. FLOAT Data Type 7. INT Data Type 8. SMALLINT Data Type 9. STRING Data Type 10. TIMESTAMP Data Type 11. TINYINT Data Type 12. VARCHAR Data Type
  • 7. SQL Literals The terms literal and constant value are synonymous and refer to a fixed data value 1. Numeric Literals 2. String Literals: String needs to be in single quotes 3. Boolean Literals: TRUE or FALSE 4. Timestamp Literals 5. NULL
  • 8. String Literals Use the text literal notation to specify values whenever 'string' or appears in the syntax of expressions, conditions, SQL functions, and SQL statements in other parts of this reference 'Hello' 'ORACLE.dbs‘ q'!name LIKE '%DBMS_%%'!' q'<'So,' she said, 'It's finished.'>‘ Numeric Literals You must use the integer notation to specify an integer whenever integer appears in expressions, conditions, SQL functions, and SQL statements described in other parts of this reference. 25 +6.34 0.5 25e-03 -1 25f +6.34F 0.5d -1D
  • 9. Date Time Literals You can specify a DATE value as a string literal, or you can convert a character or numeric value to a date value with the TO_DATE function. DATE literals are the only case in which Oracle Database accepts a TO_DATE expression in place of a string literal. To specify a DATE value as a literal, you must use the Gregorian calendar. You can specify an ANSI literal, as shown in this example: DATE '1998-12-25‘ TO_DATE('98-DEC-25 17:30','YY-MON-DD HH24:MI') Timestamp Literals TIMESTAMP '1997-01-31 09:26:56.66 +02:00‘ TIMESTAMP '1999-04-15 8:00:00 US/Pacific‘ (with Zone)
  • 10. Types of SQL Commands 1. Data Definition Language 2. Data Manipulation Language
  • 11. Data Definition Language(DDL) CREATE Creates new databases, tables and views from RDBMS. Create database tutorialspoint; Create table article; Create view for_students; DROP Drops commands, views, tables, and databases from RDBMS. Drop object_type object_name; Drop database tutorialspoint; Drop table article; Drop view for_students; ALTER Modifies database schema. This command adds an attribute in the relation article with the name subject of string type. Alter table article add subject varchar;
  • 12. Data Manipulation Language(DML) SQL is equipped with data manipulation language (DML). DML modifies the database instance by inserting, updating and deleting its data. DML is responsible for all froms data modification in a database. SQL contains the following set of commands in its DML section − 1. SELECT/FROM/WHERE 2. INSERT INTO/VALUES 3. UPDATE/SET/WHERE 4. DELETE FROM/WHERE These basic constructs allow database programmers and users to enter data and information into the database and retrieve efficiently using a number of filter options. Select author_name From book_author Where age > 50; INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ]) UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE condition] DELETE FROM table_name [WHERE condition];
  • 13. Tables A relational database system contains one or more objects called tables. The data or information for the database are stored in these tables. Tables are uniquely identified by their names and are comprised of columns and rows. Columns contain the column name, data type, and any other attributes for the column. Rows contain the records or data for the columns. Here is a sample table called "weather". city, state, high, and low are the columns. The rows contain the data for this table: Weather city state high low Phoenix Arizona 105 90 Tucson Arizona 101 92 Flagstaff Arizona 88 69 San Diego California 77 60 Albuquerque New Mexico 80 72
  • 14. Creating Table CREATE TABLE table_name ( column_name1 data_type(size), column_name2 data_type(size), column_name3 data_type(size), .... ); CREATE TABLE Persons ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) ); Syntax Example PersonID LastName FirstName Address City
  • 15. Insert into Table INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...); INSERT INTO persons(PersonID,LastName,FirstName,Address,City) VALUES(1011,’Mehta’,’Kunal’,’myaddress’,’Haridwar’); CREATE TABLE persons ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) ); PersonID LastName FirstName Address City 1011 Mehta Kunal Myaddress Haridwar
  • 16. SELECT STATEMENT • SELECT column_name,column_name FROM table_name; • SELECT * FROM table_name; CustomerID CustomerName ContactName Address City PostalCode Country 1 HARI Maria Anders Obere Str. 57 Berlin 12209 Germany 2 RAM Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico 3 SHYAM Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
  • 17. SELECT DISTINCT • In a table, a column may contain many duplicate values; and sometimes you only want to list the different (distinct) values. • The DISTINCT keyword can be used to return only distinct (different) values. CustomerID CustomerName ContactName Address City PostalCode Country 1 HARI Maria Anders Obere Str. 57 Berlin 12209 Germany 2 RAM Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico 3 SHYAM Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico SELECT DISTINCT column_name,column_name FROM table_name;
  • 18. WHERE Clause The WHERE clause is used to extract only those records that fulfill a specified criterion. SELECT column_name,column_name FROM table_name WHERE column_name operator value; SELECT * FROM Customers WHERE Country='Mexico'; CustomerID CustomerName City Country 1 HARI Berlin Germany 2 RAM México D.F. Mexico 3 SHYAM México D.F. Mexico
  • 19. AND & OR Clause The AND operator displays a record if both the first condition AND the second condition are true. The OR operator displays a record if either the first condition OR the second condition is true. CustomerID CustomerName City Country 1 HARI Berlin Germany 2 RAM México D.F. Mexico 3 SHYAM México D.F. Mexico SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; SELECT * FROM Customers WHERE City='México D.F.' OR City='München'; SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR City='München');
  • 20. DELETE STATEMENT DELETE FROM table_name WHERE some_column=some_value; CustomerID CustomerName City PostalCode Country 1 HARI Berlin 12209 Germany 2 RAM México D.F. 05021 Mexico 3 SHYAM México D.F. 05023 Mexico DELETE FROM Customers WHERE CustomerName=‘Hari’ AND City=‘Berlin'; DELETE FROM Customers WHERE CustomerName=‘Ram’ AND Country=‘Germany';
  • 21. UPDATE UPDATE table_name SET column1=value1,column2=value2,... WHERE some_column=some_value; CustomerID CustomerName City PostalCode Country 1 HARI Berlin 12209 Germany 2 RAM México D.F. 05021 Mexico 3 SHYAM México D.F. 05021 Mexico
  • 22. CustomerID CustomerName City PostalCode Country 1 HARI Berlin 12209 Germany 2 RAM México D.F. 05021 Mexico 3 SHYAM Hamburg 05021 Germany UPDATE Customers SET City=‘Hamburg’, COUNTRY=‘GERMANY’ WHERE CustomerName=‘SHYAM’; CustomerID CustomerName City PostalCode Country 1 HARI Hamburg 12209 Germany 2 RAM Hamburg 05021 Germany 3 SHYAM Hamburg 05021 Germany UPDATE Customers SET City=‘Hamburg', City=‘Germany';
  • 23. ORDER BY Clause The ORDER BY keyword is used to sort the result-set by one or more columns. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword. SELECT column_name, column_name FROM table_name ORDER BY column_name ASC|DESC; SELECT * FROM Customers ORDER BY Country; CustomerID CustomerName City Country 1 HARI Berlin Germany 2 RAM México D.F. Mexico 3 SHYAM México D.F. Mexico SELECT * FROM Customers ORDER BY Country DESC;
  • 24. DROP & TRUNCATE DROP TABLE table_name DROP DATABASE database_name TRUNCATE TABLE table_name
  • 25. ALTER TABLE STATEMENT ALTER TABLE table_name ADD column_name datatype ALTER TABLE table_name DROP COLUMN column_name P_Id FirstName Address City 1 Ola Timoteivn 10 Sandnes 2 Tove Borgvn 23 Sandnes 3 Kari Storgt 20 Stavanger ALTER TABLE Persons ADD DOB date P_Id FirstName Address City DOB 1 Ola Timoteivn 10 Sandnes 2 Tove Borgvn 23 Sandnes 3 Kari Storgt 20 Stavange r ALTER TABLE Persons ALTER COLUMN DOB year
  • 26. Creating Views Syntax: CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition Example: CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName FROM Products WHERE Discontinued=No Query from View: SELECT * FROM [Current Product List]
  • 27. Updating Views Syntax: CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition Example: CREATE OR REPLACE VIEW [Current Product List] AS SELECT ProductID,ProductName,Category FROM Products WHERE Discontinued=No
  • 28. Aggregate Functions 1. AVG() - Returns the average value 2. COUNT() - Returns the number of rows 3. MAX() - Returns the largest value 4. MIN() - Returns the smallest value 5. SUM() - Returns the sum
  • 29. SQL Scalar Functions 1. UCASE() - Converts a field to upper case a) SELECT UCASE(column_name) FROM table_name; 2. LCASE() - Converts a field to lower case a) SELECT LCASE(column_name) FROM table_name; 3. MID() - Extract characters from a text field a) SELECT SUBSTRING(column_name,start,length) AS some_name FROM table_name; 4. LEN() - Returns the length of a text field 5. ROUND() - Rounds a numeric field to the number of decimals specified 6. NOW() - Returns the current system date and time 7. FORMAT() - Formats how a field is to be displayed a) SELECT ProductName, Price, FORMAT(Now(),'YYYY-MM-DD') AS PerDate FROM Products;
  • 30. LIKE The LIKE operator is used to search for a specified pattern in a column. SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern; SELECT * FROM Customers WHERE City LIKE 's%'; SELECT * FROM Customers WHERE Country LIKE '%land%'; SELECT * FROM Customers WHERE Country NOT LIKE '%land%';
  • 31. IN SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...); SELECT * FROM Customers WHERE City IN ('Paris','London');
  • 32. BETWEEN SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2; SELECT * FROM Products WHERE Price BETWEEN 10 AND 20; ◦ SQL statement selects all products with a price BETWEEN 10 and 20 SELECT * FROM Products WHERE Price NOT BETWEEN 10 AND 20; ◦ To display the products outside the range of the previous example, use NOT BETWEEN
  • 33. Joins An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them. There are four types of JOINS. 1. INNER JOIN: Returns all rows when there is at least one match in BOTH tables 2. LEFT JOIN: Return all rows from the left table, and the matched rows from the right table 3. RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table 4. FULL JOIN: Return all rows when there is a match in ONE of the tables
  • 34. Inner Join OrderID CustomerID OrderDate 10308 2 1996-09-18 10309 37 1996-09-19 10310 77 1996-09-20 CustomerID CustomerName ContactName Country 1 Alfreds Futterkiste Maria Anders Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico 3 Antonio Moreno Taquería Antonio Moreno Mexico SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; OrderID CustomerName OrderDate 10308 Ana Trujillo Emparedados y helados 9/18/1996 Output: Customers Orders
  • 35. … SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name=table2.column_name; SELECT column_name(s) FROM table1 JOIN table2 ON table1.column_name=table2.column_name;
  • 36. Left Join The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match. Syntax: SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name=table2.column_name; or SELECT column_name(s) FROM table1 LEFT OUTER JOIN table2 ON table1.column_name=table2.column_name;
  • 37. … SELECT Customers.CustomerName, Orders.OrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName; OrderID CustomerID OrderDate 10308 2 1996-09-18 10309 37 1996-09-19 10310 77 1996-09-20 CustomerID CustomerName ContactName Country 1 Alfreds Futterkiste Maria Anders Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico 3 Antonio Moreno Taquería Antonio Moreno Mexico CustomerName OrderID Alfreds Futterkiste null Ana Trujillo Emparedados y helados 10308 Antonio Moreno Taquería null Customers Orders Output:
  • 38. Right Join The RIGHT JOIN keyword returns all rows from the right table (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; or SELECT column_name(s) FROM table1 RIGHT OUTER JOIN table2 ON table1.column_name=table2.column_name;
  • 39. … SELECT Orders.OrderID, Customers.CustomerName FROM Orders RIGHT JOIN Customers ON Orders.CustomerID=Customers.CustomerID ORDER BY Orders.OrderID; OrderID CustomerID OrderDate 10308 2 1996-09-18 10309 37 1996-09-19 10310 77 1996-09-20 CustomerID CustomerName ContactName Country 1 Alfreds Futterkiste Maria Anders Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico 3 Antonio Moreno Taquería Antonio Moreno Mexico Customers Orders Output: OrderID CustomerName Alfreds Futterkiste 10309 Ana Trujillo Emparedados y helados Antonio Moreno Taquería
  • 40. Full Join or Full Outer Join • The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2). • The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins. SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name=table2.column_name;
  • 41. … OrderID CustomerID OrderDate 10308 2 1996-09-18 10309 37 1996-09-19 10310 77 1996-09-20 CustomerID CustomerName ContactName Country 1 Alfreds Futterkiste Maria Anders Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico 3 Antonio Moreno Taquería Antonio Moreno Mexico Customers Orders Output: SELECT Customers.CustomerName, Orders.OrderID FROM Customers FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName; CustomerName OrderID Alfreds Futterkiste Ana Trujillo Emparedados y helados 10308 Antonio Moreno Taquería 10309 10310
  • 42. Union The UNION operator is used to combine the result-set of two or more SELECT statements. SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY City; SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2; SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2; Syntax: This will list all the DISTINCT city names from both the tables. Output:Query: SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers ORDER BY City; SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2; Syntax: This will list all the city names includes duplicate from both the tables. Output:Query:
  • 43. SQL Operators 1. Arithmetic Operators 2. BETWEEN Operator 3. Comparison Operators 4. EXISTS Operator 5. IN Operator 6. IS NULL Operator 7. LIKE Operator 8. Logical Operators 9. REGEXP Operator 10. RLIKE Operator
  • 45. Minus