Unit II SQL

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 96

SQL

(Structured Query Language)


By
Dr. Rifaqat Ali
Department of Mathematics and Scientific Computing
National Institute of Technology Hamirpur
Email id : [email protected]
SQL:
• SQL is a database computer language designed for the retrieval and
management of data in a relational database.
• SQL stands for Structured Query Language.
• SQL is one of the most widely used query language over the
databases.
• SQL is an ANSI (American National Standards Institute) standard
language, but there are many different versions of the SQL language.
What is SQL?
• It is a computer language for storing, manipulating and retrieving
data in a relational database.
• SQL is the standard language for Relational Database System.
• All the Relational Database Management Systems (RDMS) like
MySQL, MS Access, Oracle, Sybase, Informix, Postgres and SQL
Server use SQL as their standard database language.
• Also, they are using different dialects, such as − MS SQL Server using
T-SQL, Oracle using PL/SQL, MS Access version of SQL is called JET
SQL (native format) etc.
Why SQL?
It is widely popular because it offers the following advantages.
Allows users to access data in RDBMS.
Allows users to describe, define, and manipulate the data in a database.
Allows to embed to other languages using SQL modules, libraries, and
compilers.
Allows users to create and drop databases and tables.
Allows users to create view, stored procedure, functions in a database.
Allows users to set permissions on tables, procedures and views.
A Brief History of SQL:
• 1970 − Dr. Edgar F. "Ted" Codd of IBM is known as the father of relational
databases. He described a relational model for databases.
• 1974 − Structured Query Language appeared.
• 1978 − IBM worked to develop Codd's ideas and released a product named
System/R.
• 1986 − IBM developed the first prototype of relational database and
standardized by ANSI.
• The first relational database was released by Relational Software which later
came to be known as Oracle.
SQL Commands:
• The standard SQL commands to interact with relational databases are
CREATE, SELECT, INSERT, UPDATE, DELETE and DROP.

DDL - Data Definition Language


S.No. Command & Description
CREATE
1
Creates a new table, a view of a table, or other object in the database.
ALTER
2 Modifies an existing database object, such as a table.
DROP
3
Deletes an entire table, a view of a table or other objects in the database.
DML - Data Manipulation Language
S.No. Command & Description

SELECT
1 Retrieves certain records from one or more tables.

INSERT
2 Creates a record.
UPDATE
3 Modifies records.
DELETE
4 Deletes records.
DCL - Data Control Language

S.No. Command & Description

GRANT
1 Gives a privilege to user.

REVOKE
2 Takes back privileges granted from user.
RDBMS:

• RDBMS stands for Relational Database Management System.


• RDBMS is the basis for SQL, and for all modern database
systems like MS SQL Server, IBM DB2, Oracle, MySQL, and
Microsoft Access.
• RDBMS is a database management system (DBMS) that is based
on the relational model as introduced by E. F. Codd.
Tables:
• The data in an RDBMS is stored in database objects which are called as tables.
• This table is basically a collection of related data entries and it consists of
numerous columns and rows.
• A table is the most common and simplest form of data storage in a relational
database.
CUSTOMERS Table

ID Name Age Address Salary

1 Amit Kumar 20 Shimla 5000.00

2 Anuj Kumar 21 Kangra 3000.00

3 Shubham Singh 19 Hamirpur 2000.00


SQL Constraints
• Constraints are the rules applied on data columns on a table.
• They ensure the accuracy and reliability of the data in the database.
• Constraints can either be column level or table level.
• Column level constraints are applied only to one column whereas, table level
constraints are applied to the entire table.
The most commonly used constraints available in SQL are:
NOT NULL Constraint: Ensures that a column cannot have a NULL value.
DEFAULT Constraint: Provides a default value for a column when none is
specified.
UNIQUE Constraint: Ensures that all the values in a column are different.
Continued…

PRIMARY Key: Uniquely identifies each row/record in a database


table.
FOREIGN Key: Uniquely identifies a row/record in any another
database table.
CHECK Constraint: The CHECK constraint ensures that all values in a
column satisfy certain conditions.
INDEX: Used to create and retrieve data from the database very
quickly.
Data Integrity:

The following categories of data integrity exist with each RDBMS


• Entity Integrity: There are no duplicate rows in a table.
• Domain Integrity: Enforces valid entries for a given column by
restricting the type, the format, or the range of values.
• Referential integrity: Rows cannot be deleted, which are used
by other records.
• User-Defined Integrity: Enforces some specific business rules
that do not fall into entity, domain or referential integrity.
Types of RDBMS Databases
1. MySQL:
• It is an open source SQL database, which is developed by a Swedish company
MySQLAB.
• MySQL is supporting many different platforms including Microsoft Windows,
the major Linux distributions, UNIX, and Mac OS X.
• MySQL has free and paid versions, depending on its usage
(non-commercial/commercial) and features.
• MySQL comes with a very fast, multi-threaded, multi-user and robust SQL
database server.
Features of MySQL:
High Performance
High Availability
Scalability and Flexibility Run anything
Robust Transactional Support
Web and Data Warehouse Strengths
Strong Data Protection
Comprehensive Application Development
Management Ease
Open Source Freedom and 24 x 7 Support
Lowest Total Cost of Ownership
2. MS SQL Server
• It is a Relational Database Management System developed by Microsoft Inc.
• Its primary query languages are T-SQL and ANSI SQL.
Features of MS SQL Server :
High Performance, and High Availability
Database mirroring, and Database snapshots
CLR integration, and Service Broker
DDL triggers and Ranking functions
Row version-based isolation levels
XML integration, and TRY...CATCH
Database Mail
3. ORACLE
• It is a very large multi-user based database management system.
• Oracle is a relational database management system developed by
'Oracle Corporation‘.
• It is an excellent database server choice for client/server computing.
• Oracle supports all major operating systems for both clients and servers,
including MSDOS, NetWare, UnixWare, and OS/2.
Features of ORACLE :
Concurrency, Read Consistency, and Locking Mechanisms
Portability, and Self-managing database
Resource Manager, and Data Warehousing
4. MS ACCESS
• Microsoft Access is an entry-level database management software.
• MS Access database is not only inexpensive but also a powerful database for
small-scale projects.
• MS Access uses the Jet database engine, which utilizes a specific SQL language
dialect (sometimes referred to as Jet SQL).
Features of MS ACCESS:
Users can create tables, queries, forms and reports and connect them together
with macros.
Option of importing and exporting the data to many formats including Excel,
Outlook, ASCII, dBase, Paradox, FoxPro, SQL Server, Oracle, ODBC, etc.
There is also the Jet Database format (MDB or ACCDB in Access 2007), which
can contain the application and data in one file.
SQL - Syntax
SQL is followed by a unique set of rules and guidelines called Syntax.
All the SQL statements start with any of the keywords like SELECT, INSERT,
UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements
end with a semicolon (;).
Note that SQL is case insensitive, which means SELECT and select have
same meaning in SQL statements.
Whereas, MySQL makes difference in table names. So, if you are working
with MySQL, then you need to give table names as they exist in the
database.
Some of The Most Important SQL
Commands
SELECT: extracts data from a database
UPDATE: updates data in a database
DELETE: deletes data from a database
INSERT INTO: inserts new data into a database
CREATE DATABASE: creates a new database
ALTER DATABASE: modifies a database
CREATE TABLE: creates a new table
ALTER TABLE: modifies a table
DROP TABLE: deletes a table
CREATE INDEX: creates an index (search key)
DROP INDEX: deletes an index
SQL Comments
• Comments are used to explain sections of SQL statements, or to prevent
execution of SQL statements.
• Single line comments start with --.
Example:
--Select all:
SELECT * FROM Customers;
Example:
SELECT * FROM Customers -- WHERE City='Berlin';
Example:
--SELECT * FROM Customers;
SELECT * FROM Products;
Multi-line Comments
• Multi-line comments start with /* and end with */.
Example:
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;
Example:
/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;
Example: SELECT CustomerName, /*City,*/ Country FROM Customers;
Data Types
Data type Description
CHAR(size) A FIXED length string (can contain letters, numbers, and special
characters). The size parameter specifies the column length in
characters - can be from 0 to 255. Default is 1
VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and special
characters). The size parameter specifies the maximum column
length in characters - can be from 0 to 65535
BINARY(size) Equal to CHAR(), but stores binary byte strings. The size parameter
specifies the column length in bytes. Default is 1
VARBINARY(size) Equal to VARCHAR(), but stores binary byte strings.
The size parameter specifies the maximum column length in bytes.
TINYBLOB For BLOBs (Binary Large OBjects). Max length: 255 bytes
TINYTEXT Holds a string with a maximum length of 255 characters
Data type Description
TEXT(size) Holds a string with a maximum length of 65,535 bytes
BLOB(size) For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data

MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters

MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data

LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters

LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data

ENUM(val1, val2, ...) A string object that can have only one value, chosen from a list of possible
values. You can list up to 65535 values in an ENUM list. If a value is inserted that
is not in the list, a blank value will be inserted. The values are sorted in the
order you enter them

SET(val1, val2, ...) A string object that can have 0 or more values, chosen from a list of possible
values. You can list up to 64 values in a SET list
Data type Description
BIT(size) A bit-value type. The number of bits per value is specified in size. The size parameter can hold a
value from 1 to 64. The default value for size is 1.
TINYINT(size) A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to 255.
The size parameter specifies the maximum display width (which is 255)
INT(size) A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is from 0 to
4294967295. The size parameter specifies the maximum display width (which is 255)

BIGINT(size) A large integer. Signed range is from -9223372036854775808 to 9223372036854775807.


Unsigned range is from 0 to 18446744073709551615. The size parameter specifies the maximum
display width (which is 255)
FLOAT(size, d) A floating point number. The total number of digits is specified in size. The number of digits after
the decimal point is specified in the d parameter. This syntax is deprecated in MySQL 8.0.17, and it
will be removed in future MySQL versions
DOUBLE(size, d) A normal-size floating point number. The total number of digits is specified in size. The number of
digits after the decimal point is specified in the d parameter
DECIMAL(size, d) An exact fixed-point number. The total number of digits is specified in size. The number of digits
after the decimal point is specified in the d parameter. The maximum number for size is 65. The
maximum number for d is 30. The default value for size is 10. The default value for d is 0.
SQL CREATE DATABASE Statement
• The CREATE DATABASE statement is used to create a new SQL database.
Syntax:
CREATE DATABASE databasename;
Example:
CREATE DATABASE testDB;
CREATE DATABASE studentDB;
Note: Once a database is created, you can check it with the following SQL
command: SHOW DATABASES;
SQL DROP DATABASE Statement
• The DROP DATABASE statement is used to drop an existing SQL database.
Syntax:
DROP DATABASE databasename;
Example:
DROP DATABASE testDB;
Note: Once a database is dropped, you can check it with the following SQL
command: SHOW DATABASES;
SQL CREATE TABLE Statement
• The CREATE TABLE statement is used to create a new table in a database.
Syntax:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
• The column parameters specify the names of the columns of the table.
• The datatype parameter specifies the type of data the column can hold (e.g.
varchar, integer, date, etc.).
Continued…
Example:
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Create Table Using Another Table
• A copy of an existing table can also be created using CREATE TABLE.
• The new table gets the same column definitions. All columns or specific
columns can be selected.
• If you create a new table using an existing table, the new table will be
filled with the existing values from the old table.
Syntax:
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
Continued…
Example:
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;
SQL DROP TABLE Statement

• The DROP TABLE statement is used to drop an existing table in a


database.
Syntax:
DROP TABLE table_name;
Example:
DROP TABLE Shippers;
• The TRUNCATE TABLE statement is used to delete the data inside a
table, but not the table itself.
TRUNCATE TABLE table_name;
SQL ALTER TABLE Statement

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


an existing table.
• The ALTER TABLE statement is also used to add and drop various
constraints on an existing table.
Syntax:
ALTER TABLE table_name
ADD column_name datatype;
Example:
ALTER TABLE Customers
ADD Email varchar(255);
Continued…
• To delete a column in a table, use the following syntax
ALTER TABLE table_name
DROP COLUMN column_name;
Example:
ALTER TABLE Customers
DROP COLUMN Email;
• To change the data type of a column in a table, use the following
syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
SQL Create Constraints

• Constraints can be specified when the table is created with the


CREATE TABLE statement, or after the table is created with the ALTER
TABLE statement.
Syntax:
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
Constraints:
• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
• FOREIGN KEY - Uniquely identifies a row/record in another table
• CHECK - Ensures that all values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column when no value is specified
• INDEX - Used to create and retrieve data from the database very quickly
SQL NOT NULL Constraint
• The NOT NULL constraint enforces a column to NOT accept NULL values.
Example:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
• To create a NOT NULL constraint on the "Age" column when the "Persons" table is
already created:
ALTER TABLE Persons
MODIFY Age int NOT NULL;
SQL UNIQUE Constraint
• The UNIQUE constraint ensures that all values in a column are different. Both the
UNIQUE and PRIMARY KEY constraints provide a guarantee of uniqueness for a
column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE
constraint.
Example:
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
• To create a UNIQUE constraint on the "ID" column, if Table is already created:
ALTER TABLE Persons
ADD UNIQUE (ID);
SQL PRIMARY KEY Constraint

• The PRIMARY KEY constraint uniquely identifies each record in a table.


• Primary keys must contain UNIQUE values, and cannot contain NULL values.
• A table can have only ONE primary key; and in the table, this primary key can
consist of single or multiple columns (fields).
Example:
CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
SQL FOREIGN KEY Constraint
• A FOREIGN KEY is a key used to link two tables together.
• A FOREIGN KEY is a field (or collection of fields) in one table that refers to the
PRIMARY KEY in another table.
• The table containing the foreign key is called the child table, and the table
containing the candidate key is called the referenced or parent table.

Table: Persons Table: Orders


PersonID LastName FirstName Age OrderID OrderNumber PersonID

1 Hansen Ola 30 1 77895 3


2 44678 3
2 Svendson Tove 23
3 22456 2
3 Pettersen Kari 20
4 24562 1
Continued…
Example: The following SQL creates a FOREIGN KEY on the "PersonID" column
when the "Orders" table is created:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
Example: To create a FOREIGN KEY constraint on the "PersonID" column when the
"Orders" table is already created, use the following SQL:
ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
SQL CHECK Constraint
• The CHECK constraint is used to limit the value range that can be placed in a
column.
Example: The CHECK constraint ensures the age of a person must be 18, or older:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
Example: Apply CHECK constraint on "Age" column when table is already created:
ALTER TABLE Persons
ADD CHECK (Age>=18);
SQL DEFAULT Constraint
• The DEFAULT constraint is used to provide a default value for a column.
Example: The DEFAULT value of "City" column when the "Persons" table is
created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sands'
);
The CREATE INDEX statement is used to create indexes in tables.
CREATE INDEX index_name
ON table_name (column1, column2, ...);
SQL AUTO INCREMENT
Auto increment allows a unique number to be generated automatically
when a new record is inserted into a table.
Example:
CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);
SQL Date Data Types
MySQL comes with the following data types for storing a date or a
date/time value in the database:
DATE – format: YYYY-MM-DD
DATETIME - format: YYYY-MM-DD HH:MI:SS
TIMESTAMP - format: YYYY-MM-DD HH:MI:SS
YEAR - format YYYY or YY
Example:
SELECT * FROM Orders
WHERE OrderDate='2008-11-11‘;
SQL CREATE VIEW Statement
• In SQL, a view is a virtual table based on the result-set of an SQL
statement. A view contains rows and columns, just like a real table.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example:
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
SQL Injection
• SQL injection is a code injection technique that might destroy your
database.
• SQL injection is one of the most common web hacking techniques.
• SQL injection is the placement of malicious code in SQL statements,
via web page input.
Example:
SELECT * FROM Users WHERE UserId = 105 OR 1=1;
Database Tables
• A database most often contains one or more tables. Each table is identified by a
name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data.
Table: Customers
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedados y Constitución 2222
helados

3 Antonio Moreno Antonio Mataderos 2312 México D.F. 05023 Mexico


Taquería Moreno

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds Christina Berguvsvägen 8 Luleå S-958 22 Sweden


snabbköp Berglund
The SQL SELECT Statement
• The SELECT statement is used to select data from a database.
Syntax:
SELECT column1, column2, ...
FROM table_name;
OR
SELECT * FROM table_name;
Example:
SELECT CustomerName, City FROM Customers;
Example:
SELECT * FROM Customers;
The SQL SELECT DISTINCT Statement
The SELECT DISTINCT statement is used to return only distinct values.
Syntax:
SELECT DISTINCT column1, column2, ...
FROM table_name;
Example:
SELECT Country FROM Customers;
Example:
SELECT DISTINCT Country FROM Customers;
Example:
SELECT COUNT (DISTINCT Country) FROM Customers;
The SQL WHERE Clause:
• The WHERE clause is used to filter records. The WHERE clause is used to extract
only those records that fulfill a specified condition.
Syntax:
SELECT column1, column2, ....
FROM table_name
WHERE condition;
Example:
SELECT * FROM Customers
WHERE Country='Mexico';
Example:
SELECT * FROM Customers
WHERE CustomerID=1;
Operators in The WHERE Clause
Operator Description

= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> Not equal. Note: In some versions of SQL this operator may be written as !=

BETWEEN Between a certain range


LIKE Search for a pattern
IN To specify multiple possible values for a column
The SQL AND, OR and NOT Operators
• The AND operator displays a record if all the conditions separated by AND are TRUE.
• The OR operator displays a record if any of the conditions separated by OR is TRUE.
• The NOT operator displays a record if the condition(s) is NOT TRUE.
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Continued…
Example: SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
Example: SELECT * FROM Customers
WHERE City='Berlin' OR City='Munchen';
Example: SELECT * FROM Customers
WHERE NOT Country='Germany';
Example: SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='Munchen');
Example: SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
The SQL ORDER BY Keyword
• The ORDER BY keyword sorts the records in ascending order by default.
• To sort the records in descending order, use the DESC keyword.
Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Example: SELECT * FROM Customers
ORDER BY Country;
Example: SELECT * FROM Customers
ORDER BY Country DESC;
Example: SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
The SQL INSERT INTO Statement
• The INSERT INTO statement is used to insert new records in a table.
Syntax:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
• If you are adding values for all the columns of the table, you do not need to
specify the column names in the SQL query.
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
Example: INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
NULL Value
• A NULL value is different from a zero value or a field that contains spaces.
• A field with a NULL value is one that has been left blank during record creation!
Syntax:
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
Example: SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
Example: SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
The SQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example: UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
Example: UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
Example: UPDATE Customers
SET ContactName='Juan';
SQL DELETE Statement

• The DELETE statement is used to delete existing records in a table.


Syntax:
DELETE FROM table_name WHERE condition;
Example:
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
Syntax:
DELETE FROM table_name;
Example:
DELETE FROM Customers;
SQL MIN() and MAX() Functions
• The MIN() function returns the smallest value of the selected column.
• The MAX() function returns the largest value of the selected column.
Syntax:
SELECT MIN(column_name)
FROM table_name
WHERE condition;
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Example: SELECT MIN(Price) AS SmallestPrice
FROM Products;
Example: SELECT MAX(Price) AS LargestPrice
FROM Products;
The SQL COUNT(), AVG() and SUM() Functions
• The COUNT() function returns the number of rows that matches a
specified criterion.
• The AVG() function returns the average value of a numeric column.
• The SUM() function returns the total sum of a numeric column.
Syntax:
SELECT COUNT (column_name)
FROM table_name
WHERE condition;
SELECT AVG (column_name)
FROM table_name
WHERE condition;
SELECT SUM (column_name)
FROM table_name
WHERE condition;
Continued….

Example: SELECT COUNT (ProductID)


FROM Products;
Example: SELECT AVG (Price)
FROM Products;
Example: SELECT SUM (Quantity)
FROM OrderDetails;
The SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern
in a column.
• There are two wildcards often used in conjunction with the LIKE operator:
(%): The percent sign represents zero, one, or multiple characters
(_ ): The underscore represents a single character
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Example: The following SQL statement selects all customers with a
CustomerName starting with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
Continued…
Example: The following SQL statement selects all customers with a
CustomerName ending with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
Example: The following SQL statement selects all customers with a
CustomerName that have "or" in any position:
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
Example: The following SQL statement selects all customers with a
CustomerName that have "r" in the second position:
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
Continued…

Example: The following SQL statement selects all customers with a ContactName
that starts with "a" and ends with "o":
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
Example: The following SQL statement selects all customers with a CustomerName
that does NOT start with "a":
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
Example: The following SQL statement selects all customers with a CustomerName
that starts with "a" and are at least 3 characters in length:
SELECT * FROM Customers
WHERE CustomerName LIKE 'a_ _%';
LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position

WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position

WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at least 2
characters in length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at least 3
characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"
The SQL IN Operator
• The IN operator allows you to specify multiple values in a WHERE clause.
• The IN operator is a shorthand for multiple OR conditions.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
OR:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Continued…
Example: SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
Example: SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
Example: SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
(Selects all customers that are from the same countries as the
suppliers)
The SQL BETWEEN Operator

• The BETWEEN operator selects values within a given range. The values can be
numbers, text, or dates.
• The BETWEEN operator is inclusive: begin and end values are included.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Example: SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
Example: SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
BETWEEN with IN Example
• The following SQL statement selects all products with a price
BETWEEN 10 and 20. In addition; do not show products with a
CategoryID of 1,2, or 3:
Example: SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);
• The following SQL statement selects all products with a ProductName
BETWEEN Carnarvon Tigers and Mozzarella di Giovanni:
Example: SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni'
ORDER BY ProductName;
Continued…

Example: SELECT * FROM Products


WHERE ProductName NOT BETWEEN 'Carnarvon
Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

Example: SELECT * FROM Orders


WHERE OrderDate BETWEEN #01/07/1996# AND #31/07/1996#;
OR:
Example: SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
SQL Aliases
• SQL aliases are used to give temporary name of a table, or a column.
• An alias only exists for the duration of the query.
• Aliases can be useful when:
There are more than one table involved in a query, Functions are used in the
query, Column names are big or not very readable, Two or more columns are
combined together
Alias Column Syntax:
SELECT column_name AS alias_name
FROM table_name;
Alias Table Syntax:
SELECT column_name(s)
FROM table_name AS alias_name;
Continued…
Example: SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
Example: SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;
Example: SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' +
Country AS Address
FROM Customers;
Example: SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID = o.CustomerID;
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.
Table: Customers
Table: Orders
OrderID CustomerID OrderDate CustomerID CustomerName ContactName Country

10308 1 1996-09-18
1 Arif Maria Germany
10309 2 1996-09-19 2 Alok Ana Mexico
10310 3 1996-09-20 3 Raju Antonio Mexico

Example: SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate


FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Different Types of SQL JOINs
• (INNER) JOIN: Returns records that have matching values in both
tables
• LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
• FULL (OUTER) JOIN: Returns all records when there is a match in
either left or right table
SQL INNER JOIN
The INNER JOIN keyword selects records that have matching values in both tables.
Syntax:
SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
Example: SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Note: The INNER JOIN keyword selects all rows from both tables as long as there is
a match between the columns. If there are records in the "Orders" table that do
not have matches in "Customers", these orders will not be shown!
SQL LEFT JOIN
The LEFT JOIN keyword returns all records from the left table (table1), and the
matched records from the right table (table2). The result is NULL from the right
side, if there is no match.
Syntax:
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
Example: 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 records from the right table (table2), and
the matched records from the left table (table1). The result is NULL from the
left side, when there is no match.
Syntax:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;
Example: SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
SQL FULL OUTER JOIN
The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.
Syntax:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;

Example: SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
SQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT
statements.
Each SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the same order
Syntax:
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
This above syntax of UNION operator selects only distinct values by default. To allow
duplicate values, use UNION ALL:
Syntax:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Continued…
Example: It returns the cities (only distinct values) from both the "Customers" and
the "Suppliers" table:
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
Example: It returns the cities (duplicate values also) from both the "Customers"
and the "Suppliers" table:
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
Continued…
Example: It returns the German cities (only distinct values) from both the
"Customers" and the "Suppliers" table:
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Example: The following SQL statement lists all customers and suppliers:
SELECT 'Customer' AS Type, ContactName, City, Country
FROM Customers
UNION
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers;
SQL GROUP BY Statement
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM,
AVG) to group the result-set by one or more columns.
Syntax:
SELECT column_name(s)
FROM table_name
GROUP BY column_name(s)
ORDER BY column_name(s);
Example:
SELECT COUNT (CustomerID), Country
FROM Customers
GROUP BY Country;
Example:
SELECT COUNT (CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT (CustomerID) DESC;
The SQL HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Example: lists the number of customers in each country. Only include countries with more than
5 customers:
SELECT COUNT (CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT (CustomerID) > 5;
Continued…
Example: The following SQL statement lists the number of customers in each
country, sorted high to low (Only include countries with more than 5 customers):
SELECT COUNT (CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT (CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
Example: The following SQL statement lists the employees that have registered
more than 10 orders:
SELECT Employees.LastName, COUNT (Orders.OrderID) AS NumberOfOrders
FROM (Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT (Orders.OrderID) > 10;
The SQL EXISTS Operator
The EXISTS operator is used to test for the existence of any record in a subquery. The
EXISTS operator returns true if the subquery returns one or more records.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE EXISTS (SELECT column_name FROM table_name WHERE condition);
Example: SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price < 20);
Example: SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price = 22);
The SQL ANY and ALL Operators
• The ANY and ALL operators are used with a WHERE or HAVING clause.
• The ANY operator returns true if any of the subquery values meet the condition.
• The ALL operator returns true if all of the subquery values meet the condition
Syntax of ANY:
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);
Syntax of All:
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
Continued…
Example:
SELECT ProductName
FROM Products
WHERE ProductID= ANY (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);
Example:
SELECT ProductName
FROM Products
WHERE ProductID= ALL (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);
The SQL SELECT INTO Statement
The SELECT INTO statement copies data from one table into a new table.
Syntax: (Copy all columns into a new table)
SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
(Copy only some columns into a new table)
SELECT column1, column2, column3, ...
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
Continued…
Example: The following SQL statement creates a backup copy of Customers
SELECT * INTO CustomersBackup2017
FROM Customers;
Example: The following SQL statement uses the IN clause to copy the table into a
new table in another database
SELECT * INTO CustomersBackup2017 IN 'Backup.mdb'
FROM Customers;
Example: The following SQL statement copies only the German customers into a
new table
SELECT * INTO CustomersGermany
FROM Customers
WHERE Country = 'Germany';
The SQL INSERT INTO SELECT Statement
The INSERT INTO SELECT statement copies data from one table and inserts it
into another table.
Syntax: (Copy all columns from one table to another table)
INSERT INTO table2
SELECT * FROM table1
WHERE condition;
(Copy only some columns from one table into another table)
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
SQL INSERT INTO SELECT Examples

Example: The following SQL statement copies "Suppliers" into "Customers" (the columns that are
not filled with data, will contain NULL):
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers;
Example: The following SQL statement copies "Suppliers" into "Customers" (fill all columns):
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
SELECT SupplierName, ContactName, Address, City, PostalCode, Country FROM Suppliers;
Example: The following SQL statement copies only the German suppliers into "Customers":
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';
The SQL CASE Statement
• The CASE statement goes through conditions and returns a value when the first
condition is met (like an IF-THEN-ELSE statement). So, once a condition is true, it
will stop reading and return the result. If no conditions are true, it returns the
value in the ELSE clause.
• If there is no ELSE part and no conditions are true, it returns NULL.
Syntax:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
Example: It returns a value when the first condition met.
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;
Example: The following SQL will order the customers by City.
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);
References
1. https://www.tutorialspoint.com/sql/index.htm
2. https://www.geeksforgeeks.org/sql-tutorial/
3. https://www.w3schools.com/sql/

You might also like