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
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';
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%';
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