0% found this document useful (0 votes)
14 views35 pages

SQL Notes

This document provides a summary of SQL (Structured Query Language) in 3 sentences or less: SQL is a standard language for storing, manipulating, and retrieving data in a relational database. It includes commands like SELECT, INSERT, UPDATE, DELETE, and others to work with data. SQL defines data types, operators, constraints and other syntax to ensure data integrity and allow complex queries of database tables.

Uploaded by

Madhu H S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
14 views35 pages

SQL Notes

This document provides a summary of SQL (Structured Query Language) in 3 sentences or less: SQL is a standard language for storing, manipulating, and retrieving data in a relational database. It includes commands like SELECT, INSERT, UPDATE, DELETE, and others to work with data. SQL defines data types, operators, constraints and other syntax to ensure data integrity and allow complex queries of database tables.

Uploaded by

Madhu H S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 35

SQL COMPLETE NOTES A-Z

Author Harshwardhan Fartale

LinkedIn https://www.linkedin.com/in/emharsha1812/

What is SQL?
SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data in
a relational database.

SQL is the standard language for a relational database system. All the Relational Database Management
Systems (RDMS) like MySQL, MS Access, Oracle, and SQL Server use SQL as their standard database
language.

A brief history of SQL


SQL was initially developed by IBM in the early 1970s. The initial version, called SEQUEL (Structured English
Query Language), was designed to manipulate and retrieve data stored in IBM’s quasi-relational database
management system, System R. Then, in the late 1970s, Relational Software Inc., which is now Oracle
Corporation, introduced the first commercially available implementation of SQL, Oracle V2 for VAX computers.

Why SQL?
SQL is widely popular because it can

Create the database and table structures.

Perform basic data management chores (add, delete and modify).

Perform complex queries to transform raw data into useful information.

SQL Commands
The standard SQL commands to interact with relational databases
are CREATE, SELECT, INSERT, UPDATE, DELETE, and DROP. These commands can be classified into the
following groups based on their nature:

DDL - Data Definition Language

Command Description

CREATE Creates a new table, a view of a table, or other objects in the database.

ALTER Modifies an existing database object, such as a table.

DROP Deletes an entire table, a view of a table or other objects in the database.

DML - Data Manipulation Language

Command Description

SELECT Retrieves certain records from one or more tables.

INSERT Creates a record.

SQL COMPLETE NOTES A-Z 1


UPDATE Modifies records.

DELETE Deletes records.

SQL data types


A SQL data type is an attribute that specifies the type of data of any object. You can specify the data type of each
column in the table based on your requirements.

Some of them are listed below:

Exact Numeric Data Types


Data Type Ranges From To

int -2,147,483,648 2,147,483,647

bigint -9,223,372,036,854,775,808 9,223,372,036,854,775,807

smallint -32,768 32,767

tinyint 0 255

bit 0 1

decimal -10^38 +1 10^38 -1

numeric -10^38 +1 10^38 -1

Approximate Numeric Data Types


Data Type Ranges From To

float -1.79E + 30 1.79E + 308

real -3.40E + 38 3.40E + 38

Date and Time Data Types


Data Type Ranges From To

datetime Jan 1, 1753 Dec 31, 9999

smalldatetime Jan 1, 1900 Jun 6, 2079

date Stores a date like June 30, 1991 -

time Stores a time like 12:30 P.M.

Character Strings Data Types


DATA TYPE Description

char Maximum length of 8,000 characters.( Fixed length non-Unicode characters)

varchar Maximum of 8,000 characters. (Variable-length non-Unicode data).

varchar(max) Maximum length of 2E + 31 characters, Variable-length non-Unicode data.

text Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters.

SQL COMPLETE NOTES A-Z 2


What is an operator in SQL?
An operator is a reserved word or character used primarily in a SQL statement’s WHERE clause to perform
operation(s), such as comparisons and arithmetic operations. These operators are used to specify conditions in a
SQL statement and to serve as conjunctions for multiple conditions in a statement.

SQL arithmetic operators


Assume variable ‘a’ holds 10 and variable ‘b’ holds 20.

Operator Description Example

+ (Addition) Adds values on either side of the operator a + b will give 30

- (Subtraction) Subtracts right-hand operand from left-hand operand a - b will give -10

* (Multiplication) Multiplies values on either side of the operator a * b will give 200

/ (Division) Divides left-hand operand by right-hand operand b / a will give 2

% (Modulus) Divides left-hand operand by right-hand operand and returns remainder b % a will give 0

SQL comparison operators


Assume ‘variable a’ holds 10 and ‘variable b’ holds 20.

Operator Description Example

Checks if the values of two operands are equal or not, if yes then condition becomes
= (a = b) is not true
true

Checks if the values of two operands are equal or not, if values are not equal then
!= (a != b) is true
condition becomes true

Checks if the values of two operands are equal or not, if values are not equal then
<> (a <> b) is true
condition becomes true

Checks if the value of the left operand is greater than the value of right operand, if yes
> (a > b) is not true
then condition becomes true

Checks if the value of the left operand is less than the value of right operand, if yes
< (a < b) is true
then condition becomes true

Checks if the value of the left operand is greater than or equal to the value of right (a >= b) is not
>=
operand, if yes then condition becomes true true

Checks if the value of the left operand is less than or equal to the value of right
<= (a <= b) is true
operand, if yes then condition becomes true

SQL constraints
Constraints are the rules enforced on data columns in a table. These 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 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 following are some of the most commonly used constraints available in SQL:

The NOT NULL constraint

SQL COMPLETE NOTES A-Z 3


Ensures that a column cannot have a NULL value. By default, a column can hold NULL values. If you do not want
a column to have a NULL value, then you need to define such a constraint on this column specifying that NULL is
now not allowed for that column. A NULL is not the same as no data, rather, it represents unknown data.

The DEFAULT constraint


Provides a default value for a column when none is specified.

The UNIQUE constraint


Ensures that all the values in a column are different. The UNIQUE constraint prevents two records from having
identical values in a column. In the CUSTOMER table, for example, you might want to prevent two or more
people from having the same ID.

The PRIMARY key constraint


Uniquely identifies each row/record in a database table. A primary key is a field that uniquely identifies each
row/record in a database table. A primary key must contain unique values and cannot have NULL values. A table
can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a
primary key, they are called a composite key.

The FOREIGN Key constraint


Uniquely identifies a row/record in any other database table. A foreign key is a key used to link two tables
together. This is sometimes also called a referencing key. It can be a column or a combination of columns whose
values match a primary key in a different table.

The CHECK constraint


Ensures that all values in a column satisfy certain conditions. It enables a condition to check the value being
entered into a record. If the condition evaluates to false, the record violates the constraint and isn’t entered into
the table. For example, in the CUSTOMER table, we can check if the customer is over 18 years old by applying
the CHECK constraint on the Age attribute (column).

SQL COMMANDS
CREATE, DROP, and USE Databases

CREATE DATABASE
The SQL CREATE DATABASE statement is used to create a new SQL database.

Syntax
The basic syntax of this CREATE DATABASE statement is as follows:

CREATE DATABASE DatabaseName;

The database name should always be unique within the RDBMS.

SQL COMPLETE NOTES A-Z 4


Keep in mind that SQL keywords are NOT case sensitive: create is the same as CREATE .
Also, some database systems require a semicolon at the end of each SQL statement. A 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.

Example
If you want to create a new database, for example, testDB1, then the CREATE DATABASE statement would be as
shown below:

CREATE DATABASE testDB1;

The SHOW DATABASE command is used to display the list of databases present.

DROP DATABASE
The SQL DROP DATABASE statement is used to drop an existing database in SQL schema.

Syntax
The basic syntax of the DROP DATABASE statement is as follows:

DROP DATABASE DatabaseName;

Example
If you want to delete an existing database, for example testDB1, then the DROP DATABASE statement would be as
shown below:

DROP DATABASE testDB1;

Be careful when using this operation because deleting an existing database would
result in a complete loss of information stored in the database.

USE database
When you have multiple databases in your SQL schema before starting your operation, you need to select the
database where all the operations will be performed.
The SQL USE DATABASE statement is used to select any existing database in the SQL schema.

Syntax
The basic syntax of the USE statement is as shown below:

SQL COMPLETE NOTES A-Z 5


USE DatabaseName;

Example
Now, if you want to work with a database, for example testDB1, then you can execute the following SQL
command and start working with it:

USE testDB;

CREATE, DROP, and INSERT Table

CREATE TABLE
Creating a basic table involves naming the table and defining its columns and the data type for each column.
The SQL CREATE TABLE statement is used to create a new table.

Syntax
The basic syntax of the CREATE TABLE statement is as follows:

CREATE TABLE table_name(

column1 datatype,

column2 datatype,

column3 datatype,

.....

columnN datatype,

PRIMARY KEY(one or more columns)

);

CREATE TABLE is the keyword telling the database system what you want to do. The unique name or identifier for
the table follows the CREATE TABLE statement.
Then, in brackets, comes the list defining each column in the table and what data type it is.

Example
The following code block is an example which creates a CUSTOMERS table with ID as a primary key and NOT
NULL is the constraint showing that these fields cannot be NULL while creating records.

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2), /* The (18,2) simply means that we can have 18 digits with 2 of them after decimal point*/

SQL COMPLETE NOTES A-Z 6


PRIMARY KEY (ID)
);

You can verify that your table has been created successfully by using the DESC command:

DESC CUSTOMERS;

DROP TABLE
The SQL DROP TABLE statement is used to remove a table definition and all the data, indexes, triggers,
constraints and permission specifications for that table.

You should be very careful while using this command because once a table is deleted,
all the information available in that table will also be lost forever.

Syntax
The basic syntax of the DROP TABLE statement is as follows:

DROP TABLE table_name;

INSERT INTO
The SQL INSERT INTO statement is used to add new rows of data to a table in the database.

Syntax
There are two basic syntaxes of the INSERT INTO statement which are shown below.

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)

VALUES (value1, value2, value3,...valueN);

Here, column1, column2, column3,…columnN are the names of the columns in the table into which you want to
insert the data.
You may not need to specify the column name(s) in the SQL query if you are adding values for all the columns in
the table. But make sure the order of the values is the same as the columns in the table.
The SQL INSERT INTO syntax will be as follows:

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

The following statements would create six records in the CUSTOMERS table:

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,

SQL COMPLETE NOTES A-Z 7


NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2), /* The (18,2) simply means that we can have 18 digits with 2 of them after decimal point*/
PRIMARY KEY (ID)
);

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (1, 'Mark', 32, 'Texas', 50000.00 );

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (2, 'John', 25, 'NY', 65000.00 );

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (3, 'Emily', 23, 'Ohio', 20000.00 );

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (4, 'Bill', 25, 'Chicago', 75000.00 );

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (5, 'Tom', 27, 'Washington', 35000.00 );

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (6, 'Jane', 22, 'Texas', 45000.00 );

The code written from lines 10-26 will create the following table:

ID NAME AGE ADDRESS SALARY

1 Mark 32 Texas 50000.00

2 John 25 NY 65000.00

3 Emily 23 Ohio 20000.00

4 Bill 25 Chicago 75000.00

5 Tom 27 Washington 35000.00

6 Jane 22 Texas 45000.00

The SELECT clause

he SQL SELECT statement is used to fetch the data from a database table that returns this data in the form of a
result table. These result tables are called result-sets.

Syntax
The basic syntax of the SELECT statement is as follows:

SELECT column1, column2, ... columnN FROM table_name;

Here, SELECT specifies the column1, column2… to be selected and the FROM clause specifies from which table
these columns are to be selected.
If you want to fetch all the fields available in the table, then you can use the following syntax:

SQL COMPLETE NOTES A-Z 8


SELECT * FROM table_name;

Example
Consider the CUSTOMERS table we used in the last lesson:

ID NAME AGE ADDRESS SALARY

1 Mark 32 Texas 50000.00

2 John 25 NY 65000.00

3 Emily 23 Ohio 20000.00

4 Bill 25 Chicago 75000.00

5 Tom 27 Washington 35000.00

6 Jane 22 Texas 45000.00

Let’s say we want to fetch the ID , Name and Salary fields of the customers available in the CUSTOMERS table.
To do this we must specify these three column names after the SELECT statement. The following code shows how
this is possible:

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2), /* The (18,2) simply means that we can have 18 digits with 2 of them after decimal point*/
PRIMARY KEY (ID)
);

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (1, 'Mark', 32, 'Texas', 50000.00 );

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (2, 'John', 25, 'NY', 65000.00 );

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (3, 'Emily', 23, 'Ohio', 20000.00 );

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (4, 'Bill', 25, 'Chicago', 75000.00 );

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (5, 'Tom', 27, 'Washington', 35000.00 );

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (6, 'Jane', 22, 'Texas', 45000.00 );

SELECT ID, NAME, SALARY FROM CUSTOMERS;

The WHERE clause


The SQL WHERE clause is used to specify a condition while fetching the data from a single table. If the given
condition is satisfied, then those specific records are returned from the table.

Syntax

SQL COMPLETE NOTES A-Z 9


The basic syntax of the SELECT statement with the WHERE clause is as shown below:

SELECT column1, column2, ... columnN

FROM table_name

WHERE [condition];

You can specify a condition using the comparison or logical operators like >, <, =, LIKE , NOT , etc.

Example #1
Let’s consider the CUSTOMERS table again.

ID NAME AGE ADDRESS SALARY

1 Mark 32 Texas 50000.00

2 John 25 NY 65000.00

3 Emily 23 Ohio 20000.00

4 Bill 25 Chicago 75000.00

5 Tom 27 Washington 35000.00

6 Jane 22 Texas 45000.00

Let’s say we want to fetch the ID , Name and Salary fields from the CUSTOMERS table, provided that the salary
of the customer is greater than $50,000.
So when we write our SQL query, will get the following result:

SQL COMPLETE NOTES A-Z 10


The following code shows how to do this in SQL:

SELECT ID, NAME, SALARY


FROM CUSTOMERS
WHERE SALARY>50000;

Example #2
Let’s consider another query, which would fetch all the fields from the CUSTOMERS table for a customer with the
name John.
The SQL query is for this problem written below:

SELECT *
FROM CUSTOMERS
WHERE NAME='John';

Here, it is important to note that all the strings and characters should be inside single
quotes (’’), whereas, numeric values should be given without any quotes.

The AND & OR clauses


The SQL AND & OR operators are used to combine multiple conditions in order to narrow data in an SQL
statement. These two operators are called the conjunctive operators.
These operators provide a means to make multiple comparisons with different operators in the same SQL
statement.

SQL COMPLETE NOTES A-Z 11


The AND Operator
The AND operator allows the existence of multiple conditions in a SQL statement’s WHERE clause.

Syntax
The basic syntax of the AND operator with a WHERE clause is as follows:

SELECT column1, column2, ... columnN

FROM table_name

WHERE [condition1] AND [condition2]...AND [conditionN];

You can combine N number of conditions using the AND operator. For an action to be taken by the SQL
statement, whether it be a transaction or a query, all conditions separated by the AND must be TRUE .

Example
In this example, we will retrieve the ID , Name and Salary fields from the CUSTOMERS table, where the salary is
greater than $20,000 (inclusive) and the age is less than 25 years.

The steps needed to solve this problem are highlighted below:

SQL COMPLETE NOTES A-Z 12


The following code shows how to do this in SQL;

SELECT ID, NAME, SALARY


FROM CUSTOMERS
WHERE SALARY>=20000 AND age<25;

The OR Operator
The OR operator is used to combine multiple conditions in a SQL statement’s WHERE clause.

Syntax
The basic syntax of the OR operator with a WHERE clause is as follows:

SELECT column1, column2, ... columnN

FROM table_name

WHERE [condition1] OR [condition2]...OR [conditionN];

You can combine N number of conditions using the OR operator. For an action to be taken by the SQL statement,
whether it be a transaction or query, any ONE of the conditions separated by the OR can be TRUE .

Example
Consider the following query, which will fetch the ID , Name and Salary fields from the CUSTOMERS table, where
the salary is greater than $50,000 or the age is less than or equal to 25 years.

The following slides show the steps needed to solve this problem:

SQL COMPLETE NOTES A-Z 13


The following code shows how to do this in SQL;

SELECT ID, NAME, SALARY


FROM CUSTOMERS

SQL COMPLETE NOTES A-Z 14


WHERE SALARY >50000 OR AGE <25

Aggregate functions in SQL


In database management, an aggregate function is a function where the values of multiple rows are grouped
together to form a single value of more significant meaning.

Some of the aggregate functions are

COUNT()

SUM()

AVG()

MIN()

MAX()

Again we will be using the CUSTOMERS table.

The COUNT function


The COUNT() function returns the number of rows that match a specified criterion.

Syntax
The syntax for the COUNT() function is as follows:

SELECT COUNT(column_name)

FROM table_name

WHERE condition;

This query will return the number of Non-Null values in the specified column.

Example
Let’s say we apply the COUNT function to the salary column:

SQL COMPLETE NOTES A-Z 15


The following code shows the SQL query:

SELECT COUNT(SALARY)
FROM CUSTOMERS;

it returned the number of Non-Null values over the column salary i.e, 6.

The SUM function


The SUM() function returns the total sum of a numeric column.

Syntax
The syntax for the SUM() function is as follows:

SELECT SUM(column_name)

FROM table_name

WHERE condition;

SQL COMPLETE NOTES A-Z 16


This query will return the sum of all Non-Null values in a particular column.
The following code shows the SQL Query:

SELECT SUM(SALARY)
FROM CUSTOMERS;

he sum of all Non-Null values in the salary column is 290,000.

The AVG function


The AVG() function returns the average value of a numeric column.

Syntax
The syntax for the AVG() function is as follows:

SELECT AVG(column_name)

FROM table_name

WHERE condition;

This query will return the average of all Non-Null values in a particular column.

Example
Let’s say we apply the AVG function to the salary column:
The following code shows the SQL Query:

SELECT AVG(SALARY)
FROM CUSTOMERS;

The MAX function


The MAX() function returns the largest value of the selected column.

Syntax
The syntax for the MAX() function is as follows:

SELECT MAX(column_name)

FROM table_name

WHERE condition;

This query will return the max of all Non-Null values in a particular column.

Example
Let’s say we want to find the highest salary in the CUSTOMERS table:

SQL COMPLETE NOTES A-Z 17


The following code shows the SQL query:

SELECT MAX(SALARY)
FROM CUSTOMERS

So MAX() function will return 75000.00

The MIN function


The MIN() function returns the smallest value in the selected column.

Syntax
The syntax for the MIN() function is as follows:

SELECT MIN(column_name)

FROM table_name

WHERE condition;

This query will return the min of all Non-Null values in a particular column.

Example
Let’s say we want to find the lowest salary in the CUSTOMERS table:
The following code shows the SQL query:

SELECT MIN(SALARY)
FROM CUSTOMERS;

So MIN() function will return 20000.00

The ORDER BY clause


The SQL ORDER BY clause is used to sort the data of one or more columns in ascending or descending order.
Some databases sort the query results in ascending order by default.

Syntax
The basic syntax of the ORDER BY clause is as follows:

SELECT column-list

FROM table_name

WHERE condition

SQL COMPLETE NOTES A-Z 18


ORDER BY column1, column2, .. columnN;

You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort
is in the column-list.

Example
We will sort the CUSTOMERS table in ascending order by the NAME column:

SELECT *
FROM CUSTOMERS
ORDER BY NAME;

Now let’s say we want to sort the list according to NAME but in descending order. The code below depicts this:

SELECT *
FROM CUSTOMERS
ORDER BY NAME DESC;

If we don’t write anything after the ORDER BY clause, then the column will be sorted in ascending order by default.
However, we can also specify that we want to sort the list in ascending order by using the ASC keyword. The
code below depicts this:

SELECT *
FROM CUSTOMERS
ORDER BY NAME ASC;

The GROUP BY clause

The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into
groups. The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.

Syntax
The basic syntax of a GROUP BY clause is shown below. The GROUP BY clause must follow the conditions in
the WHERE clause and must precede the ORDER BY clause if one is used.

SELECT column1, column2 ... columnN

FROM table_name

WHERE conditions

GROUP BY column1, column2 ... columnN

ORDER BY column1, column2 ... columnN;

Example
Consider the CUSTOMERS table below but with a few changes:

SQL COMPLETE NOTES A-Z 19


ID NAME AGE ADDRESS SALARY

1 Mark 32 Texas 50,000

2 Mark 23 LA 77,000

3 John 25 NY 65,000

4 Emily 23 Ohio 20,000

5 John 31 Arizona 54,000

6 Bill 25 Chicago 75,000

7 Bill 28 Florida 31,000

8 Emily 29 Michigan 43,000

9 Tom 27 Washington 35,000

10 Jane 22 Texas 45,0000

As you can see, there are duplicate names in the table above.

If you want to know the total amount earned by customers with the same name, then the GROUP BY query will
return the following result:

SQL COMPLETE NOTES A-Z 20


The code for the GROUP BY query is written below:

SELECT NAME, SUM(SALARY)


FROM CUSTOMERS
GROUP BY NAME
ORDER BY NAME;

the GROUP BY statement groups the customers based on their names and then the SUM() function is applied over
the SALARY column so we get the total salary per customer group.

Quiz
What will be the output of the following query ?

SELECT NAME, MIN(AGE)


FROM CUSTOMERS
GROUP BY NAME;

Answer
The query will group people with same name and from within the group, it will return the person who is youngest.

SQL COMPLETE NOTES A-Z 21


NAME MIN(AGE)

Bill 25

Emily 23

Jane 22

John 25

Mark 23

Tom 27

The HAVING clause


The HAVING clause is utilized in SQL as a conditional clause with the GROUP BY clause. This conditional clause
only returns rows where aggregate function results are matched with given conditions.

The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.

Syntax
The basic syntax of the HAVING clause is as follows:

SELECT column1, column2, ... columnN

FROM table_name

WHERE [ conditions ]

GROUP BY column1, column2, ... columnN

HAVING [ conditions ]

ORDER BY column1, column2, ... columnN;

As you can see, the HAVING clause must follow the GROUP BY clause in a query and must also precede the ORDER

BY clause if used.

Example
Consider the CUSTOMERS table below but with a few changes:

ID NAME AGE ADDRESS SALARY

1 Mark 32 Texas 50,000

2 Jeff 23 LA 77,000

3 John 25 NY 65,000

4 Emily 23 Ohio 20,000

5 John 31 Texas 54,000

6 Bill 25 Texas 75,000

7 Bob 28 NY 31,000

8 Elyse 29 Ohio 43,000

SQL COMPLETE NOTES A-Z 22


9 Tom 27 Washington 35,000

10 Jane 22 NY 45,0000

As you can see, there are many customers that live at the same ADDRESS (i.e. live in the same state).
We want to write a SQL statement that returns the number of customers in each state, but only if that state has
more than 2 customers:

SQL COMPLETE NOTES A-Z 23


SELECT ADDRESS, COUNT(ID)
FROM CUSTOMERS
GROUP BY ADDRESS
HAVING COUNT(ID) > 2;

Alias syntax
You can rename a table or a column temporarily by giving another name known as an Alias. The use of table
aliases is to rename a table in a specific SQL statement. Column aliases are used to rename a table’s columns
for a particular SQL query. This renaming is a temporary change and the actual table/column name does not
change in the database.

Syntax of a table alias


The basic syntax of a table alias is as follows:

SELECT column1, column2 ... columnN

FROM table_name AS alias_name

WHERE condition;

Example
For our example, we will be using the following tables:

Customer Table

SQL COMPLETE NOTES A-Z 24


ID NAME AGE ADDRESS SALARY

1 Mark 32 Texas 50,000

2 John 25 NY 65,000

3 Emily 23 Ohio 20,000

4 Bill 25 Chicago 75,000

5 Tom 27 Washington 35,000

6 Jane 22 Texas 45,000

Orders Table

ORDER_ID DATE CUSTOMER_ID AMOUNT

100 2019-09-08 2 5000

101 2019-08-20 5 3000

102 2019-05-12 1 1000

103 2019-02-02 2 2000

SQL JOINS
A JOIN clause is used to combine rows from two or more tables, based on a common column.

We will be using the CUSTOMER and ORDER tables as shown below:


Customer Table

ID NAME AGE ADDRESS SALARY

1 Mark 32 Texas 50,000

2 John 25 NY 65,000

3 Emily 23 Ohio 20,000

4 Bill 25 Chicago 75,000

5 Tom 27 Washington 35,000

6 Jane 22 Texas 45,000

Orders Table

ORDER_ID DATE CUSTOMER_ID AMOUNT

100 2019-09-08 2 5000

101 2019-08-20 5 3000

102 2019-05-12 1 1000

103 2019-02-02 2 2000

SQL COMPLETE NOTES A-Z 25


Notice that the CUSTOMER_ID in the ORDER table references ID in the CUSTOMER table.

Now, what if we need to query something that is the combination of information in both tables?
For example, we want to:

Find information on customers who ordered an item.

Find the number of customers who ordered a certain item.

Find the address of a customer in order to dispatch the order.

The joins in SQL can help you do that using the JOIN clause.

Different types of SQL JOINs


Here are the three different types of the JOINs we will be discussing in this chapter:

INNER JOIN / JOIN: Returns records that have matching values in both tables.

The values that are a match in both tables will be returned in the result-set.
• LEFT JOIN/ LEFT OUTER JOIN: Returns all records from the left table, and the matched records from the right
table.

SQL COMPLETE NOTES A-Z 26


All the values from the left table and matching values will be returned in the result-set.

• RIGHT JOIN/ RIGHT OUTER: Returns all records from the right table, and the matched records from the left
table.

All the values from the right table and matching values will be returned in the result-set.

NNER JOIN
The INNER JOIN keyword selects records that have matching values in both tables.

Syntax
The basic syntax of the INNER JOIN is as follows:

SQL COMPLETE NOTES A-Z 27


SELECT table1.column1, table2.column2 ...

FROM table1

INNER JOIN table2

ON table1.common_field = table2.common_field;

Example
We will be using the CUSTOMERS and ORDERS tables as defined in the previous lesson.
Let’s say we want to retrieve the information of only those customers that have placed an order. This can be done
by joining the two tables:

SQL COMPLETE NOTES A-Z 28


/* This is the same table we created in the previous lessons./
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2), / The (18,2) simply means that we can have 18 digits with 2 of them after decimal point*/
PRIMARY KEY (ID)
);

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (1, 'Mark', 32, 'Texas', 50000.00 );

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (2, 'John', 25, 'NY', 65000.00 );

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (3, 'Emily', 23, 'Ohio', 20000.00 );

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (4, 'Bill', 25, 'Chicago', 75000.00 );

SQL COMPLETE NOTES A-Z 29


INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)
VALUES (5, 'Tom', 27, 'Washington', 35000.00 );

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)


VALUES (6, 'Jane', 22, 'Texas', 45000.00 );

/This is the same ORDERS table we created in previous lectures./


CREATE TABLE ORDERS(
ORDER_ID INT NOT NULL,
DATE VARCHAR (20) NOT NULL,
CUSTOMER_ID INT NOT NULL,
AMOUNT INT,
PRIMARY KEY (ORDER_ID),
FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMERS(ID) /* We must specify the table to which this foriegn key refers*/
);

INSERT INTO ORDERS (ORDER_ID, DATE, CUSTOMER_ID, AMOUNT)


VALUES (100, '2019-09-08', 2, 5000 );

INSERT INTO ORDERS (ORDER_ID, DATE, CUSTOMER_ID, AMOUNT)


VALUES (101, '2019-08-20', 5, 3000 );

INSERT INTO ORDERS (ORDER_ID, DATE, CUSTOMER_ID, AMOUNT)


VALUES (102, '2019-05-12', 1, 1000 );

INSERT INTO ORDERS (ORDER_ID, DATE, CUSTOMER_ID, AMOUNT)


VALUES (103, '2019-02-02', 2, 2000 );

SELECT CUSTOMERS.ID, CUSTOMERS.NAME, ORDERS.AMOUNT, ORDERS.DATE


FROM CUSTOMERS
INNER JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

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.

That is why we don’t see Emily, Bill or Jane in the result-set; they have not placed any orders.

Quiz

SQL COMPLETE NOTES A-Z 30


Which of the following queries will return the NAME and AGE of a customer along with the DATE they placed an
order?

SELECT CUSTOMERS.NAME, CUSTOMERS.AGE, ORDERS.DATE


FROM CUSTOMERS
INNER JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

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 table1.column1, table2.column2...

FROM table1

LEFT JOIN table2

ON table1.common_field = table2.common_field;

Note: In some databases, LEFT JOIN is called LEFT OUTER JOIN.

SQL COMPLETE NOTES A-Z 31


The SQL query to retrieve all customers whether or not they have placed an order:

SQL COMPLETE NOTES A-Z 32


SELECT CUSTOMERS.ID, CUSTOMERS.NAME, ORDERS.AMOUNT, ORDERS.DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
ORDER BY CUSTOMERS.ID;

As you can see, the LEFT JOIN keyword returns all records from the left table (Customers), even if there are no
matches in the right table (Orders).

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 table1.column1, table2.column2...

FROM table1

RIGHT JOIN table2

ON table1.common_field = table2.common_field;

Note: In some databases, RIGHT JOIN is called RIGHT OUTER JOIN.

Example
Let’s say we want to return all orders and any customers that have placed an order:

SQL COMPLETE NOTES A-Z 33


SQL COMPLETE NOTES A-Z 34
The SQL query to retrieve all orders and some of the customers(those who have placed an order):

SELECT CUSTOMERS.ID, CUSTOMERS.NAME, ORDERS.AMOUNT, ORDERS.DATE


FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

As you can see, the RIGHT JOIN keyword returns all records from the right table (ORDERS), even if there are no
matches in the left table (CUSTOMERS).

SQL COMPLETE NOTES A-Z 35

You might also like