SQL JOIN:
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
INNER JOIN is the same as JOIN; the keyword INNER is optional.
Different types of JOINs
(INNER) JOIN: Select records that have matching values in both tables.
LEFT (OUTER) JOIN: Select records from the first (left-most) table with matching
right table records.
RIGHT (OUTER) JOIN: Select records from the second (right-most) table with
matching left table records.
FULL (OUTER) JOIN: Selects all records that match either left or right table
records.
All INNER and OUTER keywords are optional.
The SQL JOIN syntax
The general syntax is:
SELECT column-names
FROM table-name1 JOIN table-name2
ON [Link]-name1 = [Link]-
name2 WHERE condition;
The general syntax with INNER is:
SELECT column-names
FROM table-name1 INNER JOIN table-name2
ON [Link]-name1 = [Link]-
name2 WHERE condition;
SQL JOIN Examples
Problem: List all orders with customer information
SELECT OrderNumber, TotalAmount, FirstName, LastName, City,
Country FROM [Order] JOIN Customer
ON [Order].CustomerId = [Link];
Problem: List all orders with product names, quantities, and prices.
SELECT [Link], [Link], [Link], [Link]
FROM Order O JOIN OrderItem I ON [Link] = [Link]
JOIN Product P ON [Link] = [Link]
ORDER BY [Link];
1. INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
2. LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
3. RIGHT JOIN Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
4. FULL OUTER JOIN Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
Note: FULL JOIN is not supported by MYSQL.
SQL Self JOIN:
o A self JOIN occurs when a table takes a 'selfie'.
o A self JOIN is a regular join but the table is joined with itself.
o They are also useful for comparisons within a table.
SQL Self JOIN Examples
Problem: Match customers that are from the same city and country.
SELECT [Link] AS FirstName1, [Link] AS LastName1,
[Link] AS FirstName2, [Link] AS LastName2,
[Link], [Link]
FROM Customer A, Customer B
WHERE [Link]<>[Link]
AND [Link] = [Link]
AND [Link] = [Link]
ORDER BY [Link];
SET OPERATIONS
UNION Clause:
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.
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
UNION ALL Syntax
The UNION operator selects only distinct values by default. To allow duplicate
values, use UNION ALL.
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
SQL UNION Examples
Problem: List all contacts, i.e., suppliers and customers.
SELECT 'Customer' As Type,
FirstName + ' ' + LastName AS ContactName,
City, Country, Phone
FROM Customer
UNION
SELECT 'Supplier', ContactName, City, Country, Phone
FROM Supplier;
SQL Subqueries:
• A subquery is a SQL query within a query.
• Subqueries are nested queries that provide data to the enclosing query.
• Subqueries can return individual values or a list of records.
• Subqueries must be enclosed with parenthesis.
The SQL subquery syntax
• There is no general syntax; subqueries are regular queries placed inside
parenthesis.
• Subqueries can be used in different ways and at different locations inside a query:
Here is an subquery with the IN operator
SELECT column-names
FROM table-name1
WHERE value IN (SELECT column-name
FROM table-name2
WHERE condition);
Subqueries can also assign column values for each record:
SELECT column1 = (SELECT column-name FROM
table-name WHERE condition),
column-names
FROM table-name
WHERE condition;
SQL Subquery Examples:
Problem: List products with order quantities greater than 100.
SELECT ProductName
FROM Product
WHERE Id IN (SELECT ProductId
FROM OrderItem
E Quantity > 100);
Problem: List all customers with their total number of orders.
SELECT FirstName, LastName,
(SELECTCOUNT([Link])FROM [Order] O WHERE [Link] =
[Link]) as ordercount FROM Customer C;
SQL Constraints:
• SQL constraints are used to specify rules for data in a table.
• Constraints are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the table. If there is any
violation between the constraint and the data action, the action is aborted.
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,
....
);
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 - 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
• 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.
Example
CREATE TABLE Persons (
ID int NOT NULL,
LastNamevarchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
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.
Example
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastNamevarchar(255) NOT NULL,
FirstName varchar(255),
Age int,
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,
LastNamevarchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID));
Alerternative mthod for adding primary key
MySQL:
Alter tabe table_name add [primary key
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
• A FOREIGN KEY is a key used to link two tables together.
• A FOREIGN KEY is a field 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.
Example
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
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.
• If you define a CHECK constraint on a single column it allows 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.
Example
CREATE TABLE Persons (
ID int NOT NULL,
LastNamevarchar(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,
LastNamevarchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND
City='Sandnes')
);
SQL DEFAULT Constraint
• The DEFAULT constraint is used to provide a default value for a column.
• The default value will be added to all new records IF no other value is specified.
Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar (255) DEFAULT 'Kathmandu'
);
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 Views:
• 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. The fields in a view are
fields from one or more real tables in the database.
• You can add SQL functions, WHERE, and JOIN statements to a view and present
the data as if the data were coming from one single table.
CREATE VIEW Syntax
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example
CREATE VIEW KTM_Customer AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = "Kathmandu";
SQL Dropping a View
A view is deleted with the DROP VIEW command.
SQL DROP VIEW Syntax
DROP VIEW view_name;
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.
Example
CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastNamevarchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);
AUTO_INCREMENT sequence start with another value, use the following SQL
statement:
ALTER TABLE Persons AUTO_INCREMENT=100;
Note: To insert a new record into the "Persons" table, we will NOT have to
specifya value for the "Personid" column (a unique value will be added
automatically).
To Remove Auto-Increment
Alter table table_name modify column colum_namedata_type not null;
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
Syntax:
INSERT INTO table_name (date_column) VALUE ('YYYY-MM-DD');
Example: To insert date in the relation.
INSERT INTO Order VALUES (1, 'Mouse', '2012-01-01');
Or
insert into Order(Cust_Date) values(curdate());
SQL CREATE INDEX Statement
• The CREATE INDEX statement is used to create indexes in tables.
• Indexes are used to retrieve data from the database very fast. The users cannot see
the indexes; they are just used to speed up searches/queries.
CREATE INDEX Syntax
Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column1, column2, ...);
TO SHOW INDEX
Show index from table_name;
TO DROP INDEX
Drop index index_name on table_name
CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);
Example
CREATE INDEX idx_lastname
ON Persons (LastName);
To Change COLUMN Name:
ALTER TABLE table_name
RENAME COLUMN old_name TO new_name;
To rename the TABLE Name:
ALTER TABLE qwerty RENAME qwerty_2;
To ADD COLUMN before / after COLUMN in Table:
ALTER TABLE Customer
ADD COLUMN phone VARCHAR (15) AFTER name;