SlideShare a Scribd company logo
SEQL /SQL
WHAT IS SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National
Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in
1987
WHAT CAN SQL DO?
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and
views
RDBMS
RDBMS stands for Relational Database Management
System.
RDBMS is the basis for SQL, and for all modern
database systems such as MS SQL Server, IBM DB2,
Oracle, MySQL, and Microsoft Access.
The data in RDBMS is stored in database objects called
tables. A table is a collection of related data entries and it
consists of columns and rows.
SQL STATEMENTS
Most of the actions you need to perform on a database
are done with SQL statements.
SQL statements consists of keywords that are easy to
understand.
KEEP IN MIND THAT...
SQL keywords are NOT case sensitive: select is the same
as SELECT
SEMICOLON AFTER SQL STATEMENTS?
Some database systems require a semicolon at the end of
each SQL statement.
Semicolon is the standard way to separate each SQL
statement in database systems that allow more than one
SQL statement to be executed in the same call to the
server.
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
DATABASE
CREATE DATABASE db_name;
DROP DATABASE db_name;
SHOW DATABASE db_name;
BACKUP DATABASE databasename
TO DISK = 'filepath’;
(example : BACKUP DATABASE testDB
TO DISK = 'D:backupstestDB.bak';)
CREATING OUR FIRST TABLE
USE db_name;
CREATE TABLE table_name(
column_name1 datatype,
Column_name 2, datatype,
……);
Example : 1. CREATE TABLE student(id INT,
sname VARCHAR(50),
age INT);
2. CREATE TABLE student(
id INT PRIMARY KEY,
sname VARCHAR(50),
age INT NOT NULL);
DELETE TABLE
DROP 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.
To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype;
(Example:- ALTER TABLE Customers ADD Email
varchar(255);)
ALTER TABLE - DROP COLUMN
To delete a column in a table, use the following syntax
(notice that some database systems don't allow deleting a
column):
ALTER TABLE table_name
DROP COLUMN column_name;
Example : ALTER TABLE Customers
DROP COLUMN Email;
ALTER TABLE - RENAME COLUMN
To rename a column in a table, use the following syntax:
ALTER TABLE table_name
RENAME COLUMN old_name to new_name;
Example : ALTER TABLE Customers
rename COLUMN Email to Mail_ID;
THE SQL INSERT INTO STATEMENT
The INSERT INTO statement is used to insert new
records in a table.
Specify both the column names and the values to be
inserted:
INSERT INTO table_name (column1, column2, column3
, ...)
VALUES (value1, value2, value3, ...);
Example : INSERT INTO customer (CustomerID, FirstName,
LastName, Email)
VALUES (1, 'John', 'Doe', 'john.doe@example.com');
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. However, make sure the order of the values is in
the same order as the columns in the table. Here,
the INSERT INTO syntax would be as follows:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
Example : INSERT INTO customer
VALUES (2, 'Jane', 'Smith', 'jane.smith@example.com');
INSERT DATA ONLY IN SPECIFIED COLUMNS
It is also possible to only insert data in specific columns.
The following SQL statement will insert a new record,
but only insert data in the "CustomerName", "City", and
"Country" columns (CustomerID will be updated
automatically):
Example : INSERT INTO Customers (CustomerName, City, Country)
VALUES ('John Doe', 'New York', 'USA');
INSERT MULTIPLE ROWS
It is also possible to insert multiple rows in one
statement.
To insert multiple rows of data, we use the
same INSERT INTO statement, but with multiple values.
Example : INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Alice Johnson', 'Los Angeles', 'USA'), ('Bob Smith',
'London', 'UK'), ('Charlie Brown', 'Sydney', 'Australia’);
Make sure you separate each set of values with a
comma ,.
THE SQL UPDATE STATEMENT
The UPDATE statement is used to modify the existing records in a
table.
UPDATE Syntax : UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example : UPDATE Customers
SET City = 'San Francisco', Country = 'USA'
WHERE CustomerID = 5;
Note: Be careful when updating records in a table! Notice
the WHERE clause in the UPDATE statement. The WHERE clause
specifies which record(s) that should be updated. If you omit
the WHERE clause, all records in the table will be updated!
THE SQL DELETE STATEMENT
The DELETE statement is used to delete existing records
in a table.
DELETE Syntax :
DELETE FROM table_name WHERE condition;
Example : DELETE FROM Customers WHERE CustomerID = 10;
DELETE ALL RECORDS
It is possible to delete all rows in a table without deleting
the table. This means that the table structure, attributes,
and indexes will be intact:
DELETE FROM table_name;
Example : DELETE FROM Customers;
Delete a Table
To delete the table completely, use the DROP
TABLE statement:
Example : DROP TABLE Customers;
THE SQL SELECT STATEMENT
The SELECT statement is used to select data from a
database.
Syntax : SELECT column1, column2, ...
FROM table_name;
Example : SELECT CustomerName,
City FROM Customers;
SELECT ALL COLUMNS
If you want to return all columns, without specifying
every column name, you can use the SELECT * syntax:
SELECT * FROM table_name;
Example : SELECT * FROM Customers;
THE SQL SELECT DISTINCT STATEMENT
The SELECT DISTINCT statement is used to return only
distinct (different) values.
For example, Select all the different countries from the
"Customers" table:
Inside a table, a column often contains many duplicate values;
and sometimes you only want to list the different (distinct)
values.
Syntax : SELECT DISTINCT column1, column2, ...
FROM table_name;
Example : SELECT DISTINCT Country FROM Customers;
THE SQL WHERE CLAUSE
The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a
specified condition.
Syntax : SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example:- Select all customers from Mexico:
SELECT * FROM Customers
WHERE Country='Mexico’;
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 sign _ represents one, single character
Syntax : SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Example: Select all customers that starts with the letter "a“ -
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
THE SQL AND OPERATOR
The WHERE clause can contain one or many AND operators.
The AND operator is used to filter records based on more than one
condition.
Syntax : SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
Example : Select all customers from Spain that starts with the letter ‘G’ -
SELECT * FROM Customers
WHERE Country = 'Spain' AND CustomerName LIKE 'G%’;
Note : AND vs OR
- The AND operator displays a record if all the conditions are TRUE.
- The OR operator displays a record if any of the conditions are TRUE.
THE SQL OR OPERATOR
The WHERE clause can contain one or more OR operators.
The OR operator is used to filter records based on more than
one condition.
Syntax : SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
Example : Select all customers from Germany or Spain –
SELECT * FROM Customers
WHERE Country = 'Germany' OR Country = 'Spain';
THE NOT OPERATOR
The NOT operator is used in combination with other operators to
give the opposite result, also called the negative result.
Syntax : SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Example : Select only the customers that are NOT from Spain -
SELECT * FROM Customers
WHERE NOT Country = 'Spain’;
In the example above, the NOT operator is used in combination with
the = operator, but it can be used in combination with other
comparison and/or logical operators.
WHAT IS A NULL VALUE?
A field with a NULL value is a field with no value.
If a field in a table is optional, it is possible to insert a new record or update a
record without adding a value to this field. Then, the field will be saved with a
NULL value.
Note: 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!
How to Test for NULL Values?
It is not possible to test for NULL values with comparison operators, such as =, <,
or <>.
We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax : SELECT column_names
FROM table_name
WHERE column_name IS NULL;
IS NOT NULL Syntax : SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
THE IS NULL OPERATOR
The IS NULL operator is used to test for empty values (NULL
values).
The following SQL lists all customers with a NULL value in the
"Address" field:
Example : SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
Tip: Always use IS NULL to look for NULL values.
The IS NOT NULL Operator
The IS NOT NULL operator is used to test for non-empty values (NOT
NULL values).
The following SQL lists all customers with a value in the "Address" field:
THE SQL COUNT() FUNCTION
The COUNT() function returns the number of rows that
matches a specified criterion.
Syntax : SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Example : Find the total number of products in the Products table -
SELECT COUNT(*)
FROM Products;
ADD A WHERE CLAUSE
You can add a WHERE clause to specify conditions:
Example : Find the number of products where Price is higher than 20 -
SELECT COUNT(ProductID)
FROM Products
WHERE Price > 20;
SPECIFY COLUMN
You can specify a column name instead of the asterix
symbol (*).
If you specify a column instead of (*), NULL values will
not be counted.
Example : Find the number of products where the ProductName is not
null - SELECT COUNT(ProductName)
FROM Products;
IGNORE DUPLICATES
You can ignore duplicates by using
the DISTINCT keyword in the COUNT function.
If DISTINCT is specified, rows with the same value for
the specified column will be counted as one.
Example : How many different prices are there in the Products table -
SELECT COUNT(DISTINCT Price)
FROM Products;
THE 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.
MIN Example : Find the lowest price -
SELECT MIN(Price)
FROM Products;
MAX Example : Find the highest price -
SELECT MAX(Price)
FROM Products;
Syntax : SELECT MIN(column_name)
FROM table_name
WHERE condition;
Example : SELECT MIN(Price)
FROM Products where ProductCategory = ‘Pen’;
Syntax : SELECT MAX(column_name)
FROM table_name
WHERE condition;
Example : SELECT MAX(Price)
FROM Products where ProductCategory = ‘Pen’;
ADD A WHERE CLAUSE
THE SQL ORDER BY
The ORDER BY keyword is used to sort the result-set in
ascending or descending order.
Syntax : SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2,…
... ASC|DESC;
Example: Sort the products by price -
SELECT * FROM Products
ORDER BY Price;
DESC
The ORDER BY keyword sorts the records in ascending
order by default. To sort the records in descending order,
use the DESC keyword.
Example : Sort the products from highest to lowest price -
SELECT * FROM Products
ORDER BY Price DESC;
ORDER ALPHABETICALLY
For string values the ORDER BY keyword will order alphabetically.
Example : Sort the products alphatbetically by ProductName -
SELECT * FROM Products
ORDER BY ProductName;
Alphabetically DESC :
To sort the table reverse alphabetically, use the DESC keyword.
Example : Sort the products by ProductName in reverse order -
SELECT * FROM Products
ORDER BY ProductName DESC;
ORDER BY SEVERAL COLUMNS
The following SQL statement selects all customers from the
"Customers" table, sorted by the "Country" and the
"CustomerName" column. This means that it orders by Country,
but if some rows have the same Country, it orders them by
CustomerName.
Example : SELECT * FROM Customers
ORDER BY Country, CustomerName;
Using Both ASC and DESC :
The following SQL statement selects all customers from the
"Customers" table, sorted ascending by the "Country" and
descending by the "CustomerName" column:
Example : SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
THE SQL GROUP BY QUERY
The GROUP BY statement groups rows that have the same values into
summary rows, like "find the number of customers in each country".
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
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Example : SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
.
.
THE _ WILDCARD
The _ wildcard represents a single character.
It can be any character or number, but each _ represents
one, and only one, character.
Example : Return all customers from a city that starts with 'L' followed
by one wildcard character, then 'nd' and then two wildcard characters -
SELECT * FROM Customers
WHERE city LIKE ’N_g___';
THE % WILDCARD
The % wildcard represents any number of characters,
even zero characters.
Example : Return all customers from a city that contains the letter ‘L’ -
SELECT * FROM Customers
WHERE city LIKE '%L%';
STARTS WITH
To return records that starts with a specific letter or phrase, add
the % at the end of the letter or phrase.
Example : Return all customers that starts with 'La’ -
SELECT * FROM Customers
WHERE CustomerName LIKE 'La%’;
Tip: You can also combine any number of conditions
using AND or OR operators.
Example : Return all customers that starts with 'a' or starts with ‘b’-
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%' OR CustomerName LIKE 'b%';
ENDS WITH
To return records that ends with a specific letter or
phrase, add the % at the beginning of the letter or phrase.
Example : Return all customers that ends with ‘a’ -
SELECT * FROM Customers
WHERE CustomerName LIKE '%a’;
Tip: You can also combine "starts with" and "ends with”.
Example : Return all customers that starts with "b" and ends with "s“ –
SELECT * FROM Customers
WHERE CustomerName LIKE 'b%s';
CONTAINS
To return records that contains a specific letter or phrase,
add the % both before and after the letter or phrase.
Example : Return all customers that contains the phrase 'or’ -
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
COMBINE WILDCARDS
Any wildcard, like % and _ , can be used in combination with
other wildcards.
Example :
1. Return all customers that starts with "a" and are at least 3 characters in
length - SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%’;
2. Example : Return all customers that have "r" in the second position -
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
WITHOUT WILDCARD
If no wildcard is specified, the phrase has to have an exact
match to return a result.
Example : Return all customers from Spain -
SELECT * FROM Customers
WHERE Country LIKE 'Spain';
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, ...);
Example : SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
.
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;
.
.
full detailled SQL notesquestion bank (1).pdf
THE SQL JOIN QUERY
A JOIN clause is used to combine rows from two or more tables, based
on a related column between them.
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.
.
THE SQL INNER JOIN QUERY
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 Products.ProductID,
Products.ProductName,Categories.CategoryName
FROM Products
INNER JOIN Categories ON Products.CategoryID =
Categories.CategoryID;
.
THE SQL LEFT JOIN QUERY
The LEFT JOIN keyword returns all records from the left table (table1), and
the matching records from the right table (table2). The result is 0 records 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;
.
THE SQL RIGHT JOIN QUERY
The RIGHT JOIN keyword returns all records from the right table
(table2), and the matching records from the left table (table1). The
result is 0 records from the left side, if 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;
.
THE SQL FULL OUTER JOIN QUERY
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
WHERE condition;
Example : SELECT Customers.CustomerName,
Orders.OrderID FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=
Orders.CustomerID
ORDER BY Customers.CustomerName;
.
FETCH FIRST
The following SQL statement shows the equivalent example
for Oracle:
Example :Select the first 3 records of the Customers table -
SELECT * FROM Customers
FETCH FIRST 3 ROWS ONLY;
SQL TOP PERCENT Example
The following SQL statement selects the first 50% of the
records from the "Customers" table (for SQL Server/MS
Access):
Example - SELECT TOP 50 PERCENT * FROM Customers;
The following SQL statement shows the equivalent example for
Oracle:
Example - SELECT * FROM Customers
WHERE Country='Germany’
FETCH FIRST 3 ROWS ONLY;
ADD the ORDER BY Keyword
Add the ORDER BY keyword when you want to sort the result,
and return the first 3 records of the sorted result.
For SQL Server and MS Access:
Example : Sort the result reverse alphabetically by CustomerName,
and return the first 3 records -
SELECT TOP 3 * FROM Customers
ORDER BY CustomerName DESC;
The following SQL statement shows the equivalent example
for Oracle:
Example - SELECT * FROM Customers
FETCH FIRST 50 PERCENT ROWS ONLY;
ADD a WHERE CLAUSE
The following SQL statement selects the first three records
from the "Customers" table, where the country is "Germany"
(for SQL Server/MS Access):
Example - SELECT TOP 3 * FROM Customers
WHERE Country='Germany';
LIMIT
The following SQL statement shows the equivalent
example for MySQL:
Example : Select the first 3 records of the Customers table -
SELECT * FROM Customers
LIMIT 3;
The following SQL statement shows the equivalent example for
MySQL:
Example - SELECT * FROM Customers
WHERE Country='Germany’
LIMIT 3;
The following SQL statement shows the equivalent
example for MySQL:
Example : SELECT * FROM Customers
ORDER BY CustomerName DESC
LIMIT 3;
The following SQL statement shows the equivalent
example for Oracle:
Example : SELECT * FROM Customers
ORDER BY CustomerName DESC
FETCH FIRST 3 ROWS ONLY;
THE SQL SELECT TOP CLAUSE
The SELECT TOP clause is used to specify the number of records to
return.
The SELECT TOP clause is useful on large tables with thousands of
records. Returning a large number of records can impact
performance.
Example : Select only the first 3 records of the Customers table -
SELECT TOP 3 * FROM Customers;
Note: Not all database systems support the SELECT TOP clause.
MySQL supports the LIMIT clause to select a limited number of
records, while Oracle uses FETCH FIRST n ROWS
ONLY and ROWNUM.
SQL SERVER / MS ACCESS SYNTAX:
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
MySQL Syntax: SELECT column_name(s) FROM table_name
WHERE condition LIMIT number;
Oracle 12 Syntax: SELECT column_name(s) FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY;
Older Oracle Syntax:
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
Older Oracle Syntax (with ORDER BY):
SELECT *
FROM (SELECT column_name(s) FROM table_name ORDER BY column_nam
e(s))
WHERE ROWNUM <= number;
Set Column Name (Alias)
When you use MIN() or MAX(), the returned column
will be named MIN(field) or MAX(field) by default. To
give the column a new name, use the AS keyword:
Example
SELECT MIN(Price) AS SmallestPrice
FROM Products;
USE AN ALIAS
Give the counted column a name by using
the AS keyword.
Example
Name the column "number of records":
SELECT COUNT(*) AS [number of records]
FROM Products;
The SQL SUM() Function
The SUM() function returns the total sum of a numeric
column.
Example
Return the sum of all Quantity fields in
the OrderDetails table:
SELECT SUM(Quantity)
FROM OrderDetails;
Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
ADD A WHERE CLAUSE
You can add a WHERE clause to specify conditions:
Example
Return the number of orders made for the product
with ProductID 11:
SELECT SUM(Quantity)
FROM OrderDetails
WHERE ProductId = 11;
USE AN ALIAS
Give the summarized column a name by using
the AS keyword.
Example
Name the column "total":
SELECT SUM(Quantity) AS total
FROM OrderDetails;
SUM() WITH AN EXPRESSION
The parameter inside the SUM() function can also be an
expression.
If we assume that each product in
the OrderDetails column costs 10 dollars, we can find the
total earnings in dollars by multiply each quantity with
10:
Example
Use an expression inside the SUM() function:
SELECT SUM(Quantity * 10)
FROM OrderDetails;
We can also join the OrderDetails table to
the Products table to find the actual amount, instead of
assuming it is 10 dollars:
Example
Join OrderDetails with Products, and use SUM() to find
the total amount:
SELECT SUM(Price * Quantity)
FROM OrderDetails
LEFT JOIN Products ON OrderDetails.ProductID =
Products.ProductID;
You will learn more about Joins later in this tutorial.
THE SQL AVG() FUNCTION
The AVG() function returns the average value of a
numeric column.
Example
Find the average price of all products:
SELECT AVG(Price)
FROM Products;
Note: NULL values are ignored.
Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
ADD A WHERE CLAUSE
You can add a WHERE clause to specify conditions:
Example
Return the average price of products in category 1:
SELECT AVG(Price)
FROM Products
WHERE CategoryID = 1;
USE AN ALIAS
Give the AVG column a name by using the AS keyword.
Example
Name the column "average price":
SELECT AVG(Price) AS [average price]
FROM Products;
HIGHER THAN AVERAGE
To list all records with a higher price than average, we
can use the AVG() function in a sub query:
Example
Return all products with a higher price than the average
price:
SELECT * FROM Products
WHERE price
> (SELECT AVG(price) FROM Products);

More Related Content

PDF
SQL Beginners anishurrehman.cloud.pdf
PPTX
PPTX
SQL Assessment Command Statements
DOC
Complete Sql Server querries
PPTX
about-SQL AND ETC.pptx
PPTX
SQL.pptx for the begineers and good know
PPTX
SQL Tutorial for Beginners
PPTX
Structure Query Language Advance Training
SQL Beginners anishurrehman.cloud.pdf
SQL Assessment Command Statements
Complete Sql Server querries
about-SQL AND ETC.pptx
SQL.pptx for the begineers and good know
SQL Tutorial for Beginners
Structure Query Language Advance Training

Similar to full detailled SQL notesquestion bank (1).pdf (20)

PPTX
Database Overview
PDF
PPT
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
PPTX
DML Statements.pptx
PPTX
SQl data base management and design
PDF
DBMS.pdf
PPT
chapter 8 SQL.ppt
PPTX
Sql slid
PPTX
Sql powerpoint
PPTX
SQL NAD DB.pptx
PPTX
SAMPLE QUESTION PAPER (THEORY) CLASS: XII SESSION: 2024-25 COMPUTER SCIENCE...
PPTX
SQL.pptx SAMPLE QUESTION PAPER (THEORY) CLASS: XII SESSION: 2024-25 COMPUTE...
PPTX
SQL | DML
PPT
MY SQL
PPTX
SQL command practical power point slides, which help you in learning sql.pptx
PPTX
SQL command practical power point slides, which help you in learning sql.pptx
PPTX
2..basic queries.pptx
DOCX
SQL report
PPTX
SQL DATABASE MANAGAEMENT SYSTEM FOR CLASS 12 CBSE
PDF
SQL for data scientist And data analysist Advanced
Database Overview
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
DML Statements.pptx
SQl data base management and design
DBMS.pdf
chapter 8 SQL.ppt
Sql slid
Sql powerpoint
SQL NAD DB.pptx
SAMPLE QUESTION PAPER (THEORY) CLASS: XII SESSION: 2024-25 COMPUTER SCIENCE...
SQL.pptx SAMPLE QUESTION PAPER (THEORY) CLASS: XII SESSION: 2024-25 COMPUTE...
SQL | DML
MY SQL
SQL command practical power point slides, which help you in learning sql.pptx
SQL command practical power point slides, which help you in learning sql.pptx
2..basic queries.pptx
SQL report
SQL DATABASE MANAGAEMENT SYSTEM FOR CLASS 12 CBSE
SQL for data scientist And data analysist Advanced
Ad

Recently uploaded (20)

PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
advance database management system book.pdf
PDF
HVAC Specification 2024 according to central public works department
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PDF
AI-driven educational solutions for real-life interventions in the Philippine...
PDF
Trump Administration's workforce development strategy
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
What if we spent less time fighting change, and more time building what’s rig...
PPTX
Computer Architecture Input Output Memory.pptx
PDF
My India Quiz Book_20210205121199924.pdf
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
Computing-Curriculum for Schools in Ghana
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PDF
Empowerment Technology for Senior High School Guide
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PPTX
20th Century Theater, Methods, History.pptx
PPTX
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
Paper A Mock Exam 9_ Attempt review.pdf.
advance database management system book.pdf
HVAC Specification 2024 according to central public works department
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
Share_Module_2_Power_conflict_and_negotiation.pptx
AI-driven educational solutions for real-life interventions in the Philippine...
Trump Administration's workforce development strategy
LDMMIA Reiki Yoga Finals Review Spring Summer
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
What if we spent less time fighting change, and more time building what’s rig...
Computer Architecture Input Output Memory.pptx
My India Quiz Book_20210205121199924.pdf
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
Computing-Curriculum for Schools in Ghana
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
Empowerment Technology for Senior High School Guide
Practical Manual AGRO-233 Principles and Practices of Natural Farming
20th Century Theater, Methods, History.pptx
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
Ad

full detailled SQL notesquestion bank (1).pdf

  • 2. WHAT IS SQL? SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the International Organization for Standardization (ISO) in 1987
  • 3. WHAT CAN SQL DO? SQL can execute queries against a database SQL can retrieve data from a database SQL can insert records in a database SQL can update records in a database SQL can delete records from a database SQL can create new databases SQL can create new tables in a database SQL can create stored procedures in a database SQL can create views in a database SQL can set permissions on tables, procedures, and views
  • 4. RDBMS RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows.
  • 5. SQL STATEMENTS Most of the actions you need to perform on a database are done with SQL statements. SQL statements consists of keywords that are easy to understand.
  • 6. KEEP IN MIND THAT... SQL keywords are NOT case sensitive: select is the same as SELECT
  • 7. SEMICOLON AFTER SQL STATEMENTS? Some database systems require a semicolon at the end of each SQL statement. Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server.
  • 8. 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
  • 9. DATABASE CREATE DATABASE db_name; DROP DATABASE db_name; SHOW DATABASE db_name; BACKUP DATABASE databasename TO DISK = 'filepath’; (example : BACKUP DATABASE testDB TO DISK = 'D:backupstestDB.bak';)
  • 10. CREATING OUR FIRST TABLE USE db_name; CREATE TABLE table_name( column_name1 datatype, Column_name 2, datatype, ……); Example : 1. CREATE TABLE student(id INT, sname VARCHAR(50), age INT); 2. CREATE TABLE student( id INT PRIMARY KEY, sname VARCHAR(50), age INT NOT NULL);
  • 11. DELETE TABLE DROP TABLE table_name;
  • 12. 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. To add a column in a table, use the following syntax: ALTER TABLE table_name ADD column_name datatype; (Example:- ALTER TABLE Customers ADD Email varchar(255);)
  • 13. ALTER TABLE - DROP COLUMN To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column): ALTER TABLE table_name DROP COLUMN column_name; Example : ALTER TABLE Customers DROP COLUMN Email;
  • 14. ALTER TABLE - RENAME COLUMN To rename a column in a table, use the following syntax: ALTER TABLE table_name RENAME COLUMN old_name to new_name; Example : ALTER TABLE Customers rename COLUMN Email to Mail_ID;
  • 15. THE SQL INSERT INTO STATEMENT The INSERT INTO statement is used to insert new records in a table. Specify both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3 , ...) VALUES (value1, value2, value3, ...); Example : INSERT INTO customer (CustomerID, FirstName, LastName, Email) VALUES (1, 'John', 'Doe', 'john.doe@example.com');
  • 16. 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. However, make sure the order of the values is in the same order as the columns in the table. Here, the INSERT INTO syntax would be as follows: INSERT INTO table_name VALUES (value1, value2, value3, ...); Example : INSERT INTO customer VALUES (2, 'Jane', 'Smith', 'jane.smith@example.com');
  • 17. INSERT DATA ONLY IN SPECIFIED COLUMNS It is also possible to only insert data in specific columns. The following SQL statement will insert a new record, but only insert data in the "CustomerName", "City", and "Country" columns (CustomerID will be updated automatically): Example : INSERT INTO Customers (CustomerName, City, Country) VALUES ('John Doe', 'New York', 'USA');
  • 18. INSERT MULTIPLE ROWS It is also possible to insert multiple rows in one statement. To insert multiple rows of data, we use the same INSERT INTO statement, but with multiple values. Example : INSERT INTO Customers (CustomerName, City, Country) VALUES ('Alice Johnson', 'Los Angeles', 'USA'), ('Bob Smith', 'London', 'UK'), ('Charlie Brown', 'Sydney', 'Australia’); Make sure you separate each set of values with a comma ,.
  • 19. THE SQL UPDATE STATEMENT The UPDATE statement is used to modify the existing records in a table. UPDATE Syntax : UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition; Example : UPDATE Customers SET City = 'San Francisco', Country = 'USA' WHERE CustomerID = 5; Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated!
  • 20. THE SQL DELETE STATEMENT The DELETE statement is used to delete existing records in a table. DELETE Syntax : DELETE FROM table_name WHERE condition; Example : DELETE FROM Customers WHERE CustomerID = 10;
  • 21. DELETE ALL RECORDS It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact: DELETE FROM table_name; Example : DELETE FROM Customers; Delete a Table To delete the table completely, use the DROP TABLE statement: Example : DROP TABLE Customers;
  • 22. THE SQL SELECT STATEMENT The SELECT statement is used to select data from a database. Syntax : SELECT column1, column2, ... FROM table_name; Example : SELECT CustomerName, City FROM Customers;
  • 23. SELECT ALL COLUMNS If you want to return all columns, without specifying every column name, you can use the SELECT * syntax: SELECT * FROM table_name; Example : SELECT * FROM Customers;
  • 24. THE SQL SELECT DISTINCT STATEMENT The SELECT DISTINCT statement is used to return only distinct (different) values. For example, Select all the different countries from the "Customers" table: Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values. Syntax : SELECT DISTINCT column1, column2, ... FROM table_name; Example : SELECT DISTINCT Country FROM Customers;
  • 25. THE SQL WHERE CLAUSE The WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition. Syntax : SELECT column1, column2, ... FROM table_name WHERE condition; Example:- Select all customers from Mexico: SELECT * FROM Customers WHERE Country='Mexico’;
  • 26. 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 sign _ represents one, single character Syntax : SELECT column1, column2, ... FROM table_name WHERE columnN LIKE pattern; Example: Select all customers that starts with the letter "a“ - SELECT * FROM Customers WHERE CustomerName LIKE 'a%';
  • 27. THE SQL AND OPERATOR The WHERE clause can contain one or many AND operators. The AND operator is used to filter records based on more than one condition. Syntax : SELECT column1, column2, ... FROM table_name WHERE condition1 AND condition2 AND condition3 ...; Example : Select all customers from Spain that starts with the letter ‘G’ - SELECT * FROM Customers WHERE Country = 'Spain' AND CustomerName LIKE 'G%’; Note : AND vs OR - The AND operator displays a record if all the conditions are TRUE. - The OR operator displays a record if any of the conditions are TRUE.
  • 28. THE SQL OR OPERATOR The WHERE clause can contain one or more OR operators. The OR operator is used to filter records based on more than one condition. Syntax : SELECT column1, column2, ... FROM table_name WHERE condition1 OR condition2 OR condition3 ...; Example : Select all customers from Germany or Spain – SELECT * FROM Customers WHERE Country = 'Germany' OR Country = 'Spain';
  • 29. THE NOT OPERATOR The NOT operator is used in combination with other operators to give the opposite result, also called the negative result. Syntax : SELECT column1, column2, ... FROM table_name WHERE NOT condition; Example : Select only the customers that are NOT from Spain - SELECT * FROM Customers WHERE NOT Country = 'Spain’; In the example above, the NOT operator is used in combination with the = operator, but it can be used in combination with other comparison and/or logical operators.
  • 30. WHAT IS A NULL VALUE? A field with a NULL value is a field with no value. If a field in a table is optional, it is possible to insert a new record or update a record without adding a value to this field. Then, the field will be saved with a NULL value. Note: 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! How to Test for NULL Values? It is not possible to test for NULL values with comparison operators, such as =, <, or <>. We will have to use the IS NULL and IS NOT NULL operators instead. IS NULL Syntax : SELECT column_names FROM table_name WHERE column_name IS NULL; IS NOT NULL Syntax : SELECT column_names FROM table_name WHERE column_name IS NOT NULL;
  • 31. THE IS NULL OPERATOR The IS NULL operator is used to test for empty values (NULL values). The following SQL lists all customers with a NULL value in the "Address" field: Example : SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NOT NULL; Tip: Always use IS NULL to look for NULL values. The IS NOT NULL Operator The IS NOT NULL operator is used to test for non-empty values (NOT NULL values). The following SQL lists all customers with a value in the "Address" field:
  • 32. THE SQL COUNT() FUNCTION The COUNT() function returns the number of rows that matches a specified criterion. Syntax : SELECT COUNT(column_name) FROM table_name WHERE condition; Example : Find the total number of products in the Products table - SELECT COUNT(*) FROM Products;
  • 33. ADD A WHERE CLAUSE You can add a WHERE clause to specify conditions: Example : Find the number of products where Price is higher than 20 - SELECT COUNT(ProductID) FROM Products WHERE Price > 20;
  • 34. SPECIFY COLUMN You can specify a column name instead of the asterix symbol (*). If you specify a column instead of (*), NULL values will not be counted. Example : Find the number of products where the ProductName is not null - SELECT COUNT(ProductName) FROM Products;
  • 35. IGNORE DUPLICATES You can ignore duplicates by using the DISTINCT keyword in the COUNT function. If DISTINCT is specified, rows with the same value for the specified column will be counted as one. Example : How many different prices are there in the Products table - SELECT COUNT(DISTINCT Price) FROM Products;
  • 36. THE 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. MIN Example : Find the lowest price - SELECT MIN(Price) FROM Products; MAX Example : Find the highest price - SELECT MAX(Price) FROM Products;
  • 37. Syntax : SELECT MIN(column_name) FROM table_name WHERE condition; Example : SELECT MIN(Price) FROM Products where ProductCategory = ‘Pen’; Syntax : SELECT MAX(column_name) FROM table_name WHERE condition; Example : SELECT MAX(Price) FROM Products where ProductCategory = ‘Pen’; ADD A WHERE CLAUSE
  • 38. THE SQL ORDER BY The ORDER BY keyword is used to sort the result-set in ascending or descending order. Syntax : SELECT column1, column2, ... FROM table_name ORDER BY column1, column2,… ... ASC|DESC; Example: Sort the products by price - SELECT * FROM Products ORDER BY Price;
  • 39. DESC The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword. Example : Sort the products from highest to lowest price - SELECT * FROM Products ORDER BY Price DESC;
  • 40. ORDER ALPHABETICALLY For string values the ORDER BY keyword will order alphabetically. Example : Sort the products alphatbetically by ProductName - SELECT * FROM Products ORDER BY ProductName; Alphabetically DESC : To sort the table reverse alphabetically, use the DESC keyword. Example : Sort the products by ProductName in reverse order - SELECT * FROM Products ORDER BY ProductName DESC;
  • 41. ORDER BY SEVERAL COLUMNS The following SQL statement selects all customers from the "Customers" table, sorted by the "Country" and the "CustomerName" column. This means that it orders by Country, but if some rows have the same Country, it orders them by CustomerName. Example : SELECT * FROM Customers ORDER BY Country, CustomerName; Using Both ASC and DESC : The following SQL statement selects all customers from the "Customers" table, sorted ascending by the "Country" and descending by the "CustomerName" column: Example : SELECT * FROM Customers ORDER BY Country ASC, CustomerName DESC;
  • 42. THE SQL GROUP BY QUERY The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". 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 WHERE condition GROUP BY column_name(s) ORDER BY column_name(s); Example : SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country; . .
  • 43. THE _ WILDCARD The _ wildcard represents a single character. It can be any character or number, but each _ represents one, and only one, character. Example : Return all customers from a city that starts with 'L' followed by one wildcard character, then 'nd' and then two wildcard characters - SELECT * FROM Customers WHERE city LIKE ’N_g___';
  • 44. THE % WILDCARD The % wildcard represents any number of characters, even zero characters. Example : Return all customers from a city that contains the letter ‘L’ - SELECT * FROM Customers WHERE city LIKE '%L%';
  • 45. STARTS WITH To return records that starts with a specific letter or phrase, add the % at the end of the letter or phrase. Example : Return all customers that starts with 'La’ - SELECT * FROM Customers WHERE CustomerName LIKE 'La%’; Tip: You can also combine any number of conditions using AND or OR operators. Example : Return all customers that starts with 'a' or starts with ‘b’- SELECT * FROM Customers WHERE CustomerName LIKE 'a%' OR CustomerName LIKE 'b%';
  • 46. ENDS WITH To return records that ends with a specific letter or phrase, add the % at the beginning of the letter or phrase. Example : Return all customers that ends with ‘a’ - SELECT * FROM Customers WHERE CustomerName LIKE '%a’; Tip: You can also combine "starts with" and "ends with”. Example : Return all customers that starts with "b" and ends with "s“ – SELECT * FROM Customers WHERE CustomerName LIKE 'b%s';
  • 47. CONTAINS To return records that contains a specific letter or phrase, add the % both before and after the letter or phrase. Example : Return all customers that contains the phrase 'or’ - SELECT * FROM Customers WHERE CustomerName LIKE '%or%';
  • 48. COMBINE WILDCARDS Any wildcard, like % and _ , can be used in combination with other wildcards. Example : 1. Return all customers that starts with "a" and are at least 3 characters in length - SELECT * FROM Customers WHERE CustomerName LIKE 'a__%’; 2. Example : Return all customers that have "r" in the second position - SELECT * FROM Customers WHERE CustomerName LIKE '_r%';
  • 49. WITHOUT WILDCARD If no wildcard is specified, the phrase has to have an exact match to return a result. Example : Return all customers from Spain - SELECT * FROM Customers WHERE Country LIKE 'Spain';
  • 50. 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, ...); Example : SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK'); .
  • 51. 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; . .
  • 53. THE SQL JOIN QUERY A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Example : SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID; . .
  • 54. 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. .
  • 55. THE SQL INNER JOIN QUERY 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 Products.ProductID, Products.ProductName,Categories.CategoryName FROM Products INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID; .
  • 56. THE SQL LEFT JOIN QUERY The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the right table (table2). The result is 0 records 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; .
  • 57. THE SQL RIGHT JOIN QUERY The RIGHT JOIN keyword returns all records from the right table (table2), and the matching records from the left table (table1). The result is 0 records from the left side, if 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; .
  • 58. THE SQL FULL OUTER JOIN QUERY 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 WHERE condition; Example : SELECT Customers.CustomerName, Orders.OrderID FROM Customers FULL OUTER JOIN Orders ON Customers.CustomerID= Orders.CustomerID ORDER BY Customers.CustomerName; .
  • 59. FETCH FIRST The following SQL statement shows the equivalent example for Oracle: Example :Select the first 3 records of the Customers table - SELECT * FROM Customers FETCH FIRST 3 ROWS ONLY; SQL TOP PERCENT Example The following SQL statement selects the first 50% of the records from the "Customers" table (for SQL Server/MS Access): Example - SELECT TOP 50 PERCENT * FROM Customers;
  • 60. The following SQL statement shows the equivalent example for Oracle: Example - SELECT * FROM Customers WHERE Country='Germany’ FETCH FIRST 3 ROWS ONLY; ADD the ORDER BY Keyword Add the ORDER BY keyword when you want to sort the result, and return the first 3 records of the sorted result. For SQL Server and MS Access: Example : Sort the result reverse alphabetically by CustomerName, and return the first 3 records - SELECT TOP 3 * FROM Customers ORDER BY CustomerName DESC;
  • 61. The following SQL statement shows the equivalent example for Oracle: Example - SELECT * FROM Customers FETCH FIRST 50 PERCENT ROWS ONLY; ADD a WHERE CLAUSE The following SQL statement selects the first three records from the "Customers" table, where the country is "Germany" (for SQL Server/MS Access): Example - SELECT TOP 3 * FROM Customers WHERE Country='Germany';
  • 62. LIMIT The following SQL statement shows the equivalent example for MySQL: Example : Select the first 3 records of the Customers table - SELECT * FROM Customers LIMIT 3;
  • 63. The following SQL statement shows the equivalent example for MySQL: Example - SELECT * FROM Customers WHERE Country='Germany’ LIMIT 3;
  • 64. The following SQL statement shows the equivalent example for MySQL: Example : SELECT * FROM Customers ORDER BY CustomerName DESC LIMIT 3; The following SQL statement shows the equivalent example for Oracle: Example : SELECT * FROM Customers ORDER BY CustomerName DESC FETCH FIRST 3 ROWS ONLY;
  • 65. THE SQL SELECT TOP CLAUSE The SELECT TOP clause is used to specify the number of records to return. The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records can impact performance. Example : Select only the first 3 records of the Customers table - SELECT TOP 3 * FROM Customers; Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses FETCH FIRST n ROWS ONLY and ROWNUM.
  • 66. SQL SERVER / MS ACCESS SYNTAX: SELECT TOP number|percent column_name(s) FROM table_name WHERE condition; MySQL Syntax: SELECT column_name(s) FROM table_name WHERE condition LIMIT number; Oracle 12 Syntax: SELECT column_name(s) FROM table_name ORDER BY column_name(s) FETCH FIRST number ROWS ONLY; Older Oracle Syntax: SELECT column_name(s) FROM table_name WHERE ROWNUM <= number; Older Oracle Syntax (with ORDER BY): SELECT * FROM (SELECT column_name(s) FROM table_name ORDER BY column_nam e(s)) WHERE ROWNUM <= number;
  • 67. Set Column Name (Alias) When you use MIN() or MAX(), the returned column will be named MIN(field) or MAX(field) by default. To give the column a new name, use the AS keyword: Example SELECT MIN(Price) AS SmallestPrice FROM Products;
  • 68. USE AN ALIAS Give the counted column a name by using the AS keyword. Example Name the column "number of records": SELECT COUNT(*) AS [number of records] FROM Products;
  • 69. The SQL SUM() Function The SUM() function returns the total sum of a numeric column. Example Return the sum of all Quantity fields in the OrderDetails table: SELECT SUM(Quantity) FROM OrderDetails;
  • 71. ADD A WHERE CLAUSE You can add a WHERE clause to specify conditions: Example Return the number of orders made for the product with ProductID 11: SELECT SUM(Quantity) FROM OrderDetails WHERE ProductId = 11;
  • 72. USE AN ALIAS Give the summarized column a name by using the AS keyword. Example Name the column "total": SELECT SUM(Quantity) AS total FROM OrderDetails;
  • 73. SUM() WITH AN EXPRESSION The parameter inside the SUM() function can also be an expression. If we assume that each product in the OrderDetails column costs 10 dollars, we can find the total earnings in dollars by multiply each quantity with 10: Example Use an expression inside the SUM() function: SELECT SUM(Quantity * 10) FROM OrderDetails;
  • 74. We can also join the OrderDetails table to the Products table to find the actual amount, instead of assuming it is 10 dollars: Example Join OrderDetails with Products, and use SUM() to find the total amount: SELECT SUM(Price * Quantity) FROM OrderDetails LEFT JOIN Products ON OrderDetails.ProductID = Products.ProductID; You will learn more about Joins later in this tutorial.
  • 75. THE SQL AVG() FUNCTION The AVG() function returns the average value of a numeric column. Example Find the average price of all products: SELECT AVG(Price) FROM Products; Note: NULL values are ignored. Syntax SELECT AVG(column_name) FROM table_name WHERE condition;
  • 76. ADD A WHERE CLAUSE You can add a WHERE clause to specify conditions: Example Return the average price of products in category 1: SELECT AVG(Price) FROM Products WHERE CategoryID = 1;
  • 77. USE AN ALIAS Give the AVG column a name by using the AS keyword. Example Name the column "average price": SELECT AVG(Price) AS [average price] FROM Products;
  • 78. HIGHER THAN AVERAGE To list all records with a higher price than average, we can use the AVG() function in a sub query: Example Return all products with a higher price than the average price: SELECT * FROM Products WHERE price > (SELECT AVG(price) FROM Products);