SELECT
SELECT Country FROM Customers;
Select Distinct
SELECT DISTINCT Country FROM Customers;
Select CountDistinct
SELECT COUNT(DISTINCT Country) FROM Customers;
Where Claus
=, <, >, <>, >=, <=,
BETWEEN
SELECT * FROM Products
WHERE Price BETWEEN 50 AND 60;
IN
IN: This operator checks if the value in the City column matches any of the values in the specified list.
SELECT * FROM Customers
WHERE City IN ('Paris','London');
LIKE
's%': This pattern specifies that the City column should start with the letter 's' and can have any
characters following it.
SELECT * FROM Customers
WHERE City LIKE 's%';
Pattern Selection
SELECT * FROM Customers
WHERE City LIKE 's%';
% is called pattern matching option or wildcard character
There are some others.
1. Percentage Sign (%)
Represents any sequence of characters (including zero characters).
Example: LIKE 'S%' would match any string that starts with "S" (e.g., "Seattle," "San
Francisco").
SELECT * FROM Customers WHERE City LIKE '%s%n%'; any string with s and n in it.
2. Underscore (_)
Represents a single character.
Example: LIKE 'S_n%' would match any string that starts with "S" and has any character in
the third position, such as "Sonora" or "Sana, san"
3. Square Brackets ([]) (supported in some SQL dialects like SQL Server)
Specifies a range or set of characters to match at a single position.
Example: LIKE 'S[aeiou]n%' would match "San," "Sen," etc., but not "Sbn."
4. Caret (^) inside Square Brackets
Used inside square brackets to negate a set of characters (SQL Server).
Example: LIKE 'S[^aeiou]n%' would match "Sbn" but not "San" or "Sen."
5. Escape Character (ESCAPE)
Allows you to search for literal % or _ symbols in the text.
Example: LIKE '20\% OFF' ESCAPE '\' would match the string "20% OFF" by using \ as
the escape character.
Examples with Usage
LIKE 'A%' – Matches any string starting with "A".
LIKE '%land' – Matches any string ending with "land".
LIKE '_a%' – Matches any string with "a" as the second character.
LIKE '[A-C]%' (SQL Server) – Matches strings starting with "A", "B", or "C".
These pattern-matching options make SQL flexible for performing complex text searches.
The SQL ORDER BY
The ORDER BY keyword is used to sort the result-set in ascending or descending
order.
SELECT * FROM Products
ORDER BY Price;
SELECT * FROM Products
ORDER BY Price DESC;
SELECT * FROM Products
ORDER BY ProductName;
The SQL AND Operator
The WHERE clause can contain one or many AND operators.
Select all customers from Spain that starts with the letter 'G':
SELECT *
FROM Customers
WHERE Country = 'Spain' AND CustomerName LIKE 'G%';
SELECT * FROM Customers
WHERE Country = 'Germany'
AND City = 'Berlin'
AND PostalCode > 12000;
Combining AND and OR
You can combine the AND and OR operators.
The following SQL statement selects all customers from Spain that starts with a
"G" or an "R".
Make sure you use parenthesis to get the correct result.
SELECT * FROM Customers
WHERE Country
= 'Spain' AND (CustomerName LIKE 'G%' OR CustomerName LIKE 'R%');
Select all customers that either:
are from Spain and starts with either "G", or
starts with the letter "R":
SELECT * FROM Customers
WHERE Country
= 'Spain' AND CustomerName LIKE 'G%' OR CustomerName LIKE 'R%';
The SQL OR Operator
The WHERE clause can contain one or more OR operators.
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.
SELECT * FROM Customers
WHERE NOT Country = 'Spain';
The SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');
What is a NULL Value?
A field with a NULL value is a field with no value.
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
The IS NOT NULL Operator
The IS NOT NULLoperator is used to test for non-empty values (NOT NULL
values).
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.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
The SQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
Delete All Records
DELETE FROM Customers;
Delete a Table
To delete the table completely, use the DROP TABLE statement:
DROP TABLE Customers;
SQL ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, RENAME or modify columns
in an existing table.
ALTER TABLE Customers
ADD Email varchar(255);
ALTER TABLE Customers
DROP COLUMN Email;
ALTER TABLE Customers RENAME COLUMN First_Name TO FirstName;
ALTER TABLE Employees MODIFY COLUMN Salary DECIMAL(10,2);
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.
SQL constraints are used to specify rules for data in a table.
The following constraints are commonly used in SQL:
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 - Prevents actions that would destroy links between tables
CHECK - Ensures that the values in a column satisfies a specific condition
DEFAULT - Sets a default value for a column if no value is specified
CREATE INDEX - Used to create and retrieve data from the database very
quickly
Constraints can be column level or table level. Column level constraints apply to
a column, and table level constraints apply to the whole table.
SQL NOT NULL Constraint
By default, a column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot
insert a new record, or update a record without adding a value to this field.
SQL NOT NULL on CREATE TABLE
The following SQL ensures that the "ID", "LastName", and "FirstName" columns
will NOT accept NULL values when the "Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
SQL NOT NULL on ALTER TABLE
To create a NOT NULL constraint on the "Age" column when the "Persons" table
is already created, use the following SQL:
ALTER TABLE Persons
MODIFY COLUMN Age int NOT NULL;
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 for
uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only
one PRIMARY KEY constraint per table.
SQL UNIQUE Constraint on CREATE TABLE
The following SQL creates a UNIQUE constraint on the "ID" column when the
"Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
SQL UNIQUE Constraint on CREATE TABLE
The following SQL creates a UNIQUE constraint on the "ID" column when the
"Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);
To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple
columns, use the following SQL syntax:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);
SQL UNIQUE Constraint on ALTER TABLE
To create a UNIQUE constraint on the "ID" column when the table is already
created, use the following SQL:
ALTER TABLE Persons
ADD UNIQUE (ID);
To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple
columns, use the following SQL syntax:
ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);
DROP a UNIQUE Constraint
To drop a UNIQUE constraint, use the following SQL:
ALTER TABLE Persons
DROP INDEX UC_Person;
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).
SQL PRIMARY KEY on CREATE TABLE
The following SQL creates a PRIMARY KEY on the "ID" column when the
"Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY
KEY constraint on multiple columns, use the following SQL syntax:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
Note: In the example above there is only ONE PRIMARY KEY (PK_Person).
However, the VALUE of the primary key is made up of TWO COLUMNS (ID +
LastName).
SQL PRIMARY KEY on ALTER TABLE
To create a PRIMARY KEY constraint on the "ID" column when the table is
already created, use the following SQL:
ALTER TABLE Persons
ADD PRIMARY KEY (ID);
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY
KEY constraint on multiple columns, use the following SQL syntax:
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);
Note: If you use ALTER TABLE to add a primary key, the primary key column(s)
must have been declared to not contain NULL values (when the table was first
created).
DROP a PRIMARY KEY Constraint
To drop a PRIMARY KEY constraint, use the following SQL:
MySQL:
ALTER TABLE Persons
DROP PRIMARY KEY;
SQL FOREIGN KEY Constraint
The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to
the PRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the
primary key is called the referenced or parent table.
Look at the following two tables:
Notice that the "PersonID" column in the "Orders" table points to the "PersonID"
column in the "Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons"
table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the
foreign key column, because it has to be one of the values contained in the
parent table.
SQL FOREIGN KEY on CREATE TABLE
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)
);
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN
KEY constraint on multiple columns, use the following SQL syntax:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);
SQL FOREIGN KEY on ALTER TABLE
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);
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN
KEY constraint on multiple columns, use the following SQL syntax:
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
DROP a FOREIGN KEY Constraint
To drop a FOREIGN KEY constraint, use the following SQL:
ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;
SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a
column.
If you define a CHECK constraint on a column it will allow only certain values for
this column.
If you define a CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row.
SQL CHECK on CREATE TABLE
The following SQL creates a CHECK constraint on the "Age" column when the
"Persons" table is created. The CHECK constraint ensures that 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)
);
To allow naming of a CHECK constraint, and for defining a CHECK constraint on
multiple columns, use the following SQL syntax:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);
SQL CHECK on ALTER TABLE
To create a CHECK constraint on the "Age" column when the table is already
created, use the following SQL:
ALTER TABLE Persons
ADD CHECK (Age>=18);
DROP a CHECK Constraint
To drop a CHECK constraint, use the following SQL:
ALTER TABLE Persons
DROP CHECK CHK_PersonAge;
SQL DEFAULT Constraint
The DEFAULT constraint is used to set a default value for a column.
The default value will be added to all new records, if no other value is specified.
SQL DEFAULT on CREATE TABLE
The following SQL sets a DEFAULT value for the "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 'Sandnes'
);
The DEFAULT constraint can also be used to insert system values, by using
functions like GETDATE():
CREATE TABLE Orders (
ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT GETDATE()
);
SQL DEFAULT on ALTER TABLE
To create a DEFAULT constraint on the "City" column when the table is already
created, use the following SQL:
ALTER TABLE Persons
ALTER City SET DEFAULT 'Sandnes';
DROP a DEFAULT Constraint
To drop a DEFAULT constraint, use the following SQL:
ALTER TABLE Persons
ALTER City DROP DEFAULT;
AUTO INCREMENT Field
Auto-increment allows a unique number to be generated automatically when a
new record is inserted into a table.
Often this is the primary key field that we would like to be created automatically
every time a new record is inserted.
Syntax for MySQL
The following SQL statement defines the "Personid" column to be an auto-
increment primary key field in the "Persons" table:
CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);
MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment
feature.
By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1
for each new record.
To let the AUTO_INCREMENT sequence start with another value, use the following
SQL statement:
ALTER TABLE Persons AUTO_INCREMENT=100;
To insert a new record into the "Persons" table, we will NOT have to specify a
value for the "Personid" column (a unique value will be added automatically):
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen');
The SQL statement above would insert a new record into the "Persons" table.
The "Personid" column would be assigned a unique value. The "FirstName"
column would be set to "Lars" and the "LastName" column would be set to
"Monsen".
SQL Aggregate Functions
An aggregate function is a function that performs a calculation on a set of
values, and returns a single value.
Aggregate functions are often used with the GROUP BY clause of
the SELECT statement. The GROUP BY clause splits the result-set into groups of
values and the aggregate function can be used to return a single value for each
group.
The most commonly used SQL aggregate functions are:
MIN() - returns the smallest value within the selected column
MAX() - returns the largest value within the selected column
COUNT() - returns the number of rows in a set
SUM() - returns the total sum of a numerical column
AVG() - returns the average value of a numerical column
Aggregate functions ignore null values (except for COUNT()).
We will go through the aggregate functions above in the next chapters.
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 ExampleGet your own SQL Server
Find the lowest price in the Price column:
SELECT MIN(Price)
FROM Products;
MAX Example
Find the highest price in the Price column:
SELECT MAX(Price)
FROM Products;
Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Set Column Name (Alias)
When you use MIN() or MAX(), the returned column will not have a descriptive
name. To give the column a descriptive name, use the AS keyword:
SELECT MIN(Price) AS SmallestPrice
FROM Products;
Use MIN() with GROUP BY
Here we use the MIN() function and the GROUP BY clause, to return the smallest
price for each category in the Products table:
SELECT MIN(Price) AS SmallestPrice, CategoryID
FROM Products
GROUP BY CategoryID;
The SQL COUNT() Function
The COUNT() function returns the number of rows that matches a specified
criterion.
Find the total number of rows in the Products table:
SELECT COUNT(*)
FROM Products;
Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Specify Column
You can specify a column name instead of the asterix symbol (*).
If you specify a column name 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;
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;
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;
Use COUNT() with GROUP BY
Here we use the COUNT() function and the GROUP BY clause, to return the
number of records for each category in the Products table:
Example
SELECT COUNT(*) AS [Number of records], CategoryID
FROM Products
GROUP BY CategoryID;
The SQL SUM() Function
The SUM() function returns the total sum of a numeric column.
ExampleGet your own SQL Server
Return the sum of all Quantity fields in the OrderDetails table:
SELECT SUM(Quantity)
FROM OrderDetails;
Add a WHERE Clause
You can add a WHERE clause to specify conditions:
Example
Return the sum of the Quantity field for the product with ProductID 11:
SELECT SUM(Quantity)
FROM OrderDetails
WHERE ProductId = 11;
Use SUM() with GROUP BY
Here we use the SUM() function and the GROUP BY clause, to return
the Quantity for each OrderID in the OrderDetails table:
Example
SELECT OrderID, SUM(Quantity) AS [Total Quantity]
FROM OrderDetails
GROUP BY OrderID;
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;
The SQL AVG() Function
The AVG() function returns the average value of a numeric column.
ExampleGet your own SQL Server
Find the average price of all products:
SELECT AVG(Price)
FROM Products;
Add a WHERE Clause
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);
Use AVG() with GROUP BY
Here we use the AVG() function and the GROUP BY clause, to return the average
price for each category in the Products table:
Example
SELECT AVG(Price) AS AveragePrice, CategoryID
FROM Products
GROUP BY CategoryID;