You are on page 1of 78

ADEPTS INSTITUTE

SQL COMPLETE COURSES

P a g e 1 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

Using database, we need to database instruction system.

P a g e 2 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

We have two categories of database:

In Relational database, the tables are related together

P a g e 3 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

Example a SQL query

Database Management System(DBMS)


Is a software that keeps data.
Relational Database Management System(RDBMS)
P a g e 4 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
Is the most famous in this time and it is used to manage, organize, retrieve,
store, calculate a data within an entity(Table).
The most Relational Database Management System are:

All those have the same basic implementation and understand the
SQL structure. So most of code we will be learning in this course,
work on any database management system.
Type of Relationship
We have:
1. One to One
2. One to Many
3. Many to Many

What about NoSQL?

P a g e 5 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

In NoSQL database system, the tables are not related together

In Comparison

P a g e 6 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

How should you call:

The answer is depending on the country, the English country call


SEQUEL and Non English call SQL. If not, they are the same.

P a g e 7 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
Normalization
Normalization is database design technique which organizes tables in a
manner that reduces redundancy and dependency of data.
We have three normalizations:
▪ First normalization
▪ Second normalization
▪ Third normalization
1. First normalization form (1NF)
The first normalization is:
-Each table cell should contain a single value.
-Each record need to be unique
2. Second normalization form(2NF)
-Rule 1 in 1NF, they are the same.
-Rule 2, single column primary key
3. Third normalization form(3NF)
-Rule 1 be in 2NF
-Rule 2 has no transitive functional dependencies.
Database schema (Blue print=schema)
Database schema is the skeleton structure that we represent the local view of
the entire Database. It defines how database is organized and how the
relations among them are associated.

P a g e 8 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

Data Modeler/Diagrams
Defines the conceptual view of a database.
It works around the Real world entity; data modeler is considered as a good
option for designing Database.
Entity: can be real world object, either animate that can be easily identifiable.
Ex: Students, Teachers.
Attributes: are the entities representation. Ex: student name, age, level
❖ Types of attributes
-Simple attribute. Ex: Student phone number
-composite attribute. Ex: student complete name.
-Derived attributes. Ex: age can be derived date of birth
-Simple value attribute. Ex: Student ID
-Multiple value attributes. Ex: a person can have more than one phone
number.

Introduction to SQL
SQL is a standard language for accessing and manipulating databases.

What is SQL?
• SQL stands for Structured Query Language
• SQL lets you access and manipulate databases
• SQL is an ANSI (American National Standards Institute) standard

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

SQL is a Standard - BUT....

P a g e 9 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
Although SQL is an ANSI (American National Standards Institute) standard,
there are different versions of the SQL language.

However, to be compliant with the ANSI standard, they all support at least the
major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a
similar manner.

Using SQL in Your Web Site


To build a web site that shows data from a database, you will need:

• An RDBMS database program (i.e. MS Access, SQL Server, MySQL)


• To use a server-side scripting language, like PHP or ASP
• To use SQL to get the data you want
• To use HTML / CSS

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 Syntax
In this tutorial we will teach you all about the different SQL statements.

Keep in Mind That...

• SQL is 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.

In this tutorial, we will use semicolon at the end of each SQL statement.
P a g e 10 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

SQL Commands
Are the instruction, it use to communicate with the database, it also use to
perform specific task.

✓ There are four types of SQL commands:


1. DDL: Data Definition Language. It changes the structure of the table like
Here are some commands that come under

• CREATE TABLE - creates a new table


• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table

creating a table, deleting a table, altering a table etc…


2. DML: Data manipulation Language. It is used to modify the database; it
is responsible for all form of changes of database
Here are some commands that comes under DML

• INSERT INTO - inserts new data into a database


• UPDATE - updates data in a database
• DELETE - deletes data from a database

3. DCL: Data Control Language. It is used to grant take back authority from
any database user.
here are some commands that come under DCL
. Grant (is used to give data access).
. Revoke (is used to take back the permission from the user).
4. DQL: Data Query Language.
- DQL is used to fetch the data from the database.
It uses only the command SELECT
Select * from Employee;
This statement will display all the employee’s information in the
table Employee

SELECT - extracts data from a database

SQL General Data Types


P a g e 11 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
Each column in a database table is required to have a name and a data type.

SQL developers have to decide what types of data will be stored inside each and
every table column when creating a SQL table. The data type is a label and a
guideline for SQL to understand what type of data is expected inside of each
column, and it also identifies how SQL will interact with the stored data.

The following table lists the general data types in SQL:

SQL Server Data Types


String types:

Data type Description Storage

char(n) Fixed width character string. Maximum 8,000 characters Defined width

varchar(n) Variable width character string. Maximum 8,000 characters 2 bytes + number
of chars

varchar(max) Variable width character string. Maximum 1,073,741,824 2 bytes + number


characters of chars

text Variable width character string. Maximum 2GB of text data 4 bytes + number
of chars

nchar Fixed width Unicode string. Maximum 4,000 characters Defined width x 2

nvarchar Variable width Unicode string. Maximum 4,000 characters

nvarchar(max) Variable width Unicode string. Maximum 536,870,912

P a g e 12 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
characters

ntext Variable width Unicode string. Maximum 2GB of text data

bit Allows 0, 1, or NULL

binary(n) Fixed width binary string. Maximum 8,000 bytes

varbinary Variable width binary string. Maximum 8,000 bytes

varbinary(max) Variable width binary string. Maximum 2GB

image Variable width binary string. Maximum 2GB

The SQL CREATE DATABASE Statement


The CREATE DATABASE statement is used to create a database.

SQL CREATE DATABASE Syntax


CREATE DATABASE dbname;

The SQL CREATE TABLE Statement


The CREATE TABLE statement is used to create a table in a database.

Tables are organized into rows and columns; and each table must have a name.

SQL CREATE TABLE Syntax


CREATE TABLE table_name
(
column_name1 data_type(size),

P a g e 13 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
column_name2 data_type(size),
column_name3 data_type(size),
....
);

The column_name parameters specify the names of the columns of the table.

The data_type parameter specifies what type of data the column can hold (e.g.
varchar, integer, decimal, date, etc.).

The size parameter specifies the maximum length of the column of the table.

Example
CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

SQL PRIMARY KEY Constraint


The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain UNIQUE values.
A primary key column cannot contain NULL values.
Most tables should have a primary key, and each table can have only ONE
primary key.

SQL PRIMARY KEY Constraint on CREATE TABLE


The following SQL creates a PRIMARY KEY on the "P_Id" column when the
"Persons" table is created:

MySQL\SQL\:

CREATE TABLE Persons


(
P_Id int NOT NULL Constraint P_ID PRIMARY KEY (P_Id),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
P a g e 14 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

)
or
CREATE TABLE Persons
(
P_Id int NOT NULL
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
Constraint P_ID PRIMARY KEY (P_Id),
)

SQL PRIMARY KEY Constraint on ALTER TABLE


To create a PRIMARY KEY constraint on the "P_Id" column when the table is
already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD PRIMARY KEY (P_Id)

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

Note: If you use the ALTER TABLE statement to add a primary key, the primary
key column(s) must already have been declared to not contain NULL values
(when the table was first created).

SQL FOREIGN KEY Constraint on CREATE TABLE


The following SQL creates a FOREIGN KEY on the "P_Id" column when the
"Orders" table is created:

MySQL:

CREATE TABLE Orders


(
O_Id int NOT NULL,
P a g e 15 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)

SQL Server / Oracle / MS Access:

CREATE TABLE Orders


(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
)

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Orders


(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)

SQL FOREIGN KEY Constraint on ALTER TABLE


A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders"
table is already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders


ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:


P a g e 16 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)

To DROP a FOREIGN KEY Constraint


To drop a FOREIGN KEY constraint, use the following SQL:

MySQL:

ALTER TABLE Orders


DROP FOREIGN KEY fk_PerOrders

SQL Server / Oracle / MS Access:


ALTER TABLE Orders
DROP CONSTRAINT fk_PerOrders

The SQL INSERT INTO Statement


The INSERT INTO statement is used to insert new records in a table.

SQL INSERT INTO Syntax


It is possible to write the INSERT INTO statement in two forms.

The first form does not specify the column names where the data will be
inserted, only their values:

INSERT INTO table_name


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

The second form specifies both the column names and the values to be
inserted:

INSERT INTO table_name (column1,column2,column3,...)


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

The SQL SELECT Statement


The SELECT statement is used to select data from a database.

The result is stored in a result table, called the result-set.

P a g e 17 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
SQL SELECT Syntax
SELECT column_name,column_name
FROM table_name;

and

SELECT * FROM table_name;

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.

SQL CHECK Constraint on CREATE TABLE


The following SQL creates a CHECK constraint on the "P_Id" column when the
"Persons" table is created. The CHECK constraint specifies that the column
"P_Id" must only include integers greater than 0.

SQL Server:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
)

SQL Server / Oracle / MS Access:

CREATE TABLE Persons


(
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),

P a g e 18 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
City varchar(255)
)

To allow naming of a CHECK constraint, and for defining a CHECK constraint on


multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
)

SQL CHECK Constraint on ALTER TABLE


To create a CHECK constraint on the "P_Id" column when the table is already
created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD CHECK (P_Id>0)

To allow naming of a CHECK constraint, and for defining a CHECK constraint on


multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')

To DROP a CHECK Constraint


To drop a CHECK constraint, use the following SQL:

SQL Server / Oracle / MS Access:

ALTER TABLE Persons


DROP CONSTRAINT chk_Person

SQL Server:

P a g e 19 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
ALTER TABLE Persons
DROP CHECK chk_Person

SQL DEFAULT Constraint


The DEFAULT constraint is used to insert a default value into a column.

The default value will be added to all new records, if no other value is specified.

SQL DEFAULT Constraint on CREATE TABLE


The following SQL creates a DEFAULT constraint on the "City" column when the
"Persons" table is created:

My SQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
)

The DEFAULT constraint can also be used to insert system values, by using
functions like GETDATE ():

CREATE TABLE Orders(


O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
);

SQL DEFAULT Constraint on ALTER TABLE


To create a DEFAULT constraint on the "City" column when the table is already
created, use the following SQL:

MySQL

ALTER TABLE Persons


ALTER City SET DEFAULT 'SANDNES'

SQL Server:

P a g e 20 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
ALTER TABLE Passengers
ADD CONSTRAINT df_dest
DEFAULT 'Dabola' FOR Destination;

MS Access:

ALTER TABLE Persons


ALTER COLUMN City SET DEFAULT 'SANDNES'

Oracle:

ALTER TABLE Persons


MODIFY City DEFAULT 'SANDNES'

Insert into a Default Column


--Insert into Passenger
insert into Passengers values(10,'Abou','Kaba','Guinea',Default);
insert into Passengers values(11,'Aly','Barry','Guinea',Default);
insert into Passengers values(12,'Aisha','Conde','Guinea',Default);
insert into Passengers values(13,'Fatoumata','Camara','Guinea',Default);

To DROP a DEFAULT Constraint


To drop a DEFAULT constraint, use the following SQL:

MySQL:

ALTER TABLE Persons


ALTER City DROP DEFAULT

SQL Server / Oracle / MS Access:


ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT

Indexes
An index can be created in a table to find data more quickly and efficiently.

SQL CREATE INDEX Syntax


Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name


ON table_name (column_name)
P a g e 21 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
SQL CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name


ON table_name (column_name)

Note: The syntax for creating indexes varies amongst different databases.
Therefore: Check the syntax for creating indexes in your database.

CREATE INDEX Example


The SQL statement below creates an index named "PIndex" on the "LastName"
column in the "Persons" table:

CREATE INDEX PIndex


ON Persons (LastName)

If you want to create an index on a combination of columns, you can list the
column names within the parentheses, separated by commas:

CREATE INDEX PIndex


ON Persons (LastName, FirstName)

Displaying an INDEX
Select * from Table_Name WITH(Index(Index_Name));
Ex:
select * from saler with(index( SalerIndex))

Droping an INDEX
Drop Index IndexName on Table_Name
drop index SalerIndex on saler;
The SQL DELETE Statement
The DELETE statement is used to delete records in a table.

P a g e 22 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
SQL DELETE Syntax
DELETE FROM table_name
WHERE some_column=some_value;

Notice the WHERE clause in the SQL DELETE statement!


The WHERE clause specifies which record or records that should be
deleted. If you omit the WHERE clause, all records will be deleted!

SQL DELETE Example


Assume we wish to delete the customer "Alfreds Futterkiste" from the
"Customers" table.

We use the following SQL statement:

Example
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste' AND ContactName='Maria Anders';

Delete All Data


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;


or
DELETE * FROM table_name;

Note: Be very careful when deleting records. You cannot undo this
statement!

The SQL UPDATE Statement


The UPDATE statement is used to update existing records in a table.

SQL UPDATE Syntax


UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;

Notice the WHERE clause in the SQL UPDATE statement!

P a g e 23 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
The WHERE clause specifies which record or records that should be
updated. If you omit the WHERE clause, all records will be updated.

SQL UPDATE Example


Assume we wish to update the customer "Alfreds Futterkiste" with a new
contact person and city.

We use the following SQL statement:

Example
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste';

The selection from the "Customers" table will now look like this:

Update Warning!
Be careful when updating records. If we had omitted the WHERE clause, in
the example above, like this:

UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg';

The SQL WHERE Clause


The WHERE clause is used to extract only those records that fulfill a specified
criterion.

SQL WHERE Syntax


SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;

WHERE Clause Example


The following SQL statement selects all the customers from the country
"Mexico", in the "Customers" table:

P a g e 24 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
Example
SELECT * FROM Customers
WHERE Country='Mexico';

Text Fields vs. Numeric Fields


SQL requires single quotes around text values (most database systems will also
allow double quotes).

However, numeric fields should not be enclosed in quotes:

Example
SELECT * FROM Customers
WHERE CustomerID=1;

Operators in The WHERE Clause


The following operators can be used in the WHERE clause:

Operator Description

= Equal

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

> Greater than

< Less than

>= Greater than or equal

P a g e 25 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

<= Less than or equal

BETWEEN Between an inclusive range

LIKE Search for a pattern

IN To specify multiple possible values for a column

The SQL LIKE Operator


The LIKE operator is used to search for a specified pattern in a column.

SQL LIKE Syntax


SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;

SQL LIKE Operator Examples


The following SQL statement selects all customers with a City starting with the
letter "s":

Example
SELECT * FROM Customers
WHERE City LIKE 's%';

Tip: The "%" sign is used to define wildcards (missing letters) both before and
after the pattern. You will learn more about wildcards in the next chapter.

The following SQL statement selects all customers with a City ending with the
letter "s":

P a g e 26 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
Example
SELECT * FROM Customers
WHERE City LIKE '%s';

The following SQL statement selects all customers with a Country containing the
pattern "land":

Example
SELECT * FROM Customers
WHERE Country LIKE '%land%';

Using the NOT keyword allows you to select records that do NOT match the
pattern.

The following SQL statement selects all customers with Country NOT containing
the pattern "land":

Example
SELECT * FROM Customers
WHERE Country NOT LIKE '%land%';

The SQL BETWEEN Operator


The BETWEEN operator selects values within a range. The values can be
numbers, text, or dates.

SQL BETWEEN Syntax


SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

BETWEEN Operator Example


The following SQL statement selects all products with a price BETWEEN 10 and
20:

Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

NOT BETWEEN Operator Example

P a g e 27 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
To display the products outside the range of the previous example, use NOT
BETWEEN:

Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

BETWEEN Operator with IN Example


The following SQL statement selects all products with a price BETWEEN 10 and
20, but products with a CategoryID of 1,2, or 3 should not be displayed:

Example
SELECT * FROM Products
WHERE (Price BETWEEN 10 AND 20)
AND NOT CategoryID IN (1,2,3);

BETWEEN Operator with Text Value Example


The following SQL statement selects all products with a ProductName beginning
with any of the letter BETWEEN 'C' and 'M':

Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'C' AND 'M';

NOT BETWEEN Operator with Text Value Example


The following SQL statement selects all products with a ProductName beginning
with any of the letter NOT BETWEEN 'C' and 'M':

Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'C' AND 'M';

BETWEEN Operator with Date Value Example


The following SQL statement selects all orders with an OrderDate BETWEEN '04-
July-1996' and '09-July-1996':

Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/04/1996# AND #07/09/1996#;
P a g e 28 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
Notice that the BETWEEN operator can produce different result in
different databases!
In some databases, BETWEEN selects fields that are between and excluding the
test values.
In other databases, BETWEEN selects fields that are between and including the
test values.
And in other databases, BETWEEN selects fields between the test values,
including the first test value and excluding the last test value.

Therefore: Check how your database treats the BETWEEN operator!

SQL VIEW

SQL view allows us to facilitate a task that will be repeating

SQL view syntax:

Create view View_Name as select column1, column2, column3 etc. from Table_Name;

SQL View Example

create view shop as select constituency_code, Location_NAme, date_created


from Constituency_Table;

we can just display the view name to see the contents


select * from shop;
Creating the view with WHERE clause
create view Ghana as select * from Constituency_Table
where Constituency_Code between '32' and '34';
To see the contents, use select statement
select * from Ghana;

SQL AUTO INCREMENT Field


Auto-increment allows a unique number to be generated when a new record
is inserted into a table.

AUTO INCREMENT a Field


Very often we would like the value of the primary key field to be created
automatically every time a new record is inserted.

We would like to create an auto-increment field in a table.

P a g e 29 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
Syntax for MySQL

The following SQL statement defines the "ID" column to be an auto-increment


primary key field in the "Persons" table:

CREATE TABLE Persons


(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)

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 "ID" 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 "ID" column would be assigned a unique value. The "FirstName" column
would be set to "Lars" and the "LastName" column would be set to "Monsen".

Syntax for SQL Server

The following SQL statement defines the "ID" column to be an auto-increment


primary key field in the "Persons" table:

CREATE TABLE Persons


(
ID int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
P a g e 30 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
Address varchar(255),
City varchar(255)
)

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment


feature.

In the example above, the starting value for IDENTITY is 1, and it will increment
by 1 for each new record.

Tip: To specify that the "ID" column should start at value 10 and increment by
5, change it to IDENTITY (10,5).

To insert a new record into the "Persons" table, we will NOT have to specify a
value for the "ID" 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 "ID" column would be assigned a unique value. The "FirstName" column
would be set to "Lars" and the "LastName" column would be set to "Monsen".

Syntax for Access

The following SQL statement defines the "ID" column to be an auto-increment


primary key field in the "Persons" table:

CREATE TABLE Persons


(
ID Integer PRIMARY KEY AUTOINCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

The MS Access uses the AUTOINCREMENT keyword to perform an auto-


increment feature.

By default, the starting value for AUTOINCREMENT is 1, and it will increment by


1 for each new record.

Tip: To specify that the "ID" column should start at value 10 and increment by
5, change the auto increment to AUTOINCREMENT (10,5).

P a g e 31 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
To insert a new record into the "Persons" table, we will NOT have to specify a
value for the "ID" 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 "P_Id" column would be assigned a unique value. The "FirstName" column
would be set to "Lars" and the "LastName" column would be set to "Monsen".

Syntax for Oracle

In Oracle the code is a little bit trickier.

You will have to create an auto-increment field with the sequence object (this
object generates a number sequence).

Use the following CREATE SEQUENCE syntax:

CREATE SEQUENCE seq_person


MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10

The code above creates a sequence object called seq_person, that starts with 1
and will increment by 1. It will also cache up to 10 values for performance. The
cache option specifies how many sequence values will be stored in memory for
faster access.

To insert a new record into the "Persons" table, we will have to use the nextval
function (this function retrieves the next value from seq_person sequence):

INSERT INTO Persons (ID,FirstName,LastName)


VALUES (seq_person.nextval,'Lars','Monsen')

The SQL statement above would insert a new record into the "Persons" table.
The "ID" column would be assigned the next number from the seq_person
sequence. The "FirstName" column would be set to "Lars" and the "LastName"
column would be set to "Monsen".

The ALTER TABLE Statement


The ALTER TABLE statement is used to add, delete, or modify columns in an
existing table.

P a g e 32 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
SQL ALTER TABLE Syntax
To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype;

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

To change the data type of a column in a table, use the following syntax:

SQL Server / MS Access:

ALTER TABLE table_name


ALTER COLUMN column_name datatype

My SQL / Oracle (prior version 10G):

ALTER TABLE table_name


MODIFY COLUMN column_name datatype

Oracle 10G and later:

ALTER TABLE table_name


MODIFY column_name datatype

SQL ALTER TABLE Example


Now we want to add a column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons


ADD DateOfBirth date

Notice that the new column, "DateOfBirth", is of type date and is going to hold a
date. The data type specifies what type of data the column can hold.

Change Data Type Example

P a g e 33 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
Now we want to change the data type of the column named "DateOfBirth" in the
"Persons" table.

We use the following SQL statement:

ALTER TABLE Persons


ALTER COLUMN DateOfBirth year

Notice that the "DateOfBirth" column is now of type year and is going to hold a
year in a two-digit or four-digit format.

SQL Joins

An SQL JOIN clause is used to combine rows from two or more tables, based on
a common field between them.

The most common type of join is: SQL INNER JOIN (simple join). An SQL
INNER JOIN returns all rows from multiple tables where the join condition is
met.

Let's look at a selection from the "Orders" table:

OrderID CustomerID OrderDate


10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20

Then, have a look at a selection from the "Customers" table:


CustomerID CustomerName ContactName Country
1 Aliou Balde Maria Anders Germany
2 Moussa Camara Ana Mexico
3 Kaba Abou Antonio Mexico

Notice that the "CustomerID" column in the "Orders" table refers to the
"CustomerID" in the "Customers" table. The relationship between the two tables
above is the "CustomerID" column.

P a g e 34 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
Then, if we run the following SQL statement (that contains an INNER JOIN):

Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;

OrderID CustomerName OrderDate


10308 Ana Trujillo 9/18/1996
Emparedados y helados
10365 Antonio Moreno 11/27/1996
Taquería
10383 Around the Horn 12/16/1996
10355 Around the Horn 11/15/1996
10278 Berglunds snabbköp 8/12/1996
SQL INNER JOIN Keyword
The INNER JOIN keyword selects all rows from both tables as long as there is a
match between the columns in both tables.

SQL INNER JOIN Syntax


SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;

or:

SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;

PS! INNER JOIN is the same as JOIN.

Demo:

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Country


P a g e 35 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
1 Aliou Balde Maria Anders Germany
2 Moussa Camara Ana Mexico
3 Kaba Abou Antonio Mexico
And a selection from the "Orders" table:

OrderID CustomerID OrderDate


10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20

SQL INNER JOIN Example


The following SQL statement will return all customers with orders:

Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

Note: The INNER JOIN keyword selects all rows from both tables as long as
there is a match between the columns. If there are rows in the "Customers"
table that do not have matches in "Orders", these customers will NOT be listed.

SQL LEFT JOIN Keyword


The LEFT JOIN keyword returns all rows from the left table (table1), with the
matching rows in the right table (table2). The result is NULL in the right side
when there is no match.

SQL LEFT JOIN Syntax


SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;

or:

SELECT column_name(s)
FROM table1
P a g e 36 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;

PS! In some databases LEFT JOIN is called LEFT OUTER JOIN.

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Country


1 Aliou Balde Maria Anders Germany
2 Moussa Camara Ana Mexico
3 Kaba Abou Antonio Mexico

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID


10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
SQL LEFT JOIN Example
The following SQL statement will return all customers, and any orders they
might have:

Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

Note: The LEFT JOIN keyword returns all the rows from the left table
(Customers), even if there are no matches in the right table (Orders).

SQL RIGHT JOIN Keyword


The RIGHT JOIN keyword returns all rows from the right table (table2), with the
matching rows in the left table (table1). The result is NULL in the left side when
there is no match.
P a g e 37 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
SQL RIGHT JOIN Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;

or:
SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;

PS! In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Country


1 Aliou Balde Maria Anders Germany
2 Moussa Camara Ana Mexico
3 Kaba Abou Antonio Mexico

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID


10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
SQL RIGHT JOIN Example
The following SQL statement will return all customers, and any orders they
might have:

Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
RIGHT JOIN Orders

P a g e 38 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

Note: The RIGHT JOIN keyword returns all the rows from the right table
(Employees), even if there are no matches in the left table (Orders).

SQL FULL OUTER JOIN Keyword


The FULL OUTER JOIN keyword returns all rows from the left table (table1) and
from the right table (table2).

The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT
joins.

SQL FULL OUTER JOIN Syntax


SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Country


1 Aliou Balde Maria Anders Germany
2 Moussa Camara Ana Mexico
3 Kaba Abou Antonio Mexico

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID


10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
SQL FULL OUTER JOIN Example
The following SQL statement selects all customers, and all orders:

P a g e 39 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

Note: The FULL OUTER JOIN keyword returns all the rows from the left table
(Customers), and all the rows from the right table (Orders). If there are rows in
"Customers" that do not have matches in "Orders", or if there are rows in
"Orders" that do not have matches in "Customers", those rows will be listed as
well.

The SQL UNION Operator


The UNION operator is used to combine the result-set of two or more SELECT
statements.

Notice that each SELECT statement within the UNION must have the same
number of columns. The columns must also have similar data types. Also, the
columns in each SELECT statement must be in the same order.

SQL UNION Syntax


SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

Note: The UNION operator selects only distinct values by default. To allow
duplicate values, use the ALL keyword with UNION.

SQL UNION ALL Syntax


SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;

PS: The column names in the result-set of a UNION are usually equal to the
column names in the first SELECT statement in the UNION.

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

P a g e 40 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
CustomerID CustomerName City ContactName Country
1 Aliou Balde Conakry Maria Anders Germany
2 Moussa Camara Dakar Ana Mexico
3 Kaba Abou Accra Antonio Mexico

And a selection from the "Suppliers" table:

SupplierID SupplierName ContactName Address City


1 Exotic Liquid Charlotte Cooper 49 Gilbert St. London
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans
3 Grandma Kelly's Homestead Regina Murphy 707 Oxford Rd. Ann Arbor

SQL UNION Example


The following SQL statement selects all the different cities (only distinct
values) from the "Customers" and the "Suppliers" tables:

Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

Note: UNION cannot be used to list ALL cities from the two tables. If several
customers and suppliers share the same city, each city will only be listed once.
UNION selects only distinct values. Use UNION ALL to also select duplicate
values!

SQL UNION ALL Example


The following SQL statement uses UNION ALL to select all (duplicate values
also) cities from the "Customers" and "Suppliers" tables:

Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;

P a g e 41 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
SQL UNION ALL with WHERE
The following SQL statement uses UNION ALL to select all (duplicate values
also) German cities from the "Customers" and "Suppliers" tables:

Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

SQL MORE THAN TWO TABLES JOIN With WHERE


‘Creating Database’
Create database MultipleDatabase;

‘Creating Department Table’


create table Department (
Dept_no int not null primary key,
Dept_Name varchar(30),
Manager varchar(30));

‘inserting Data into Department’

insert into Department(Dept_no,Dept_Name,Manager)


values(1, 'Programming', 'Abou');

insert into Department(Dept_no,Dept_Name,Manager)


values(2, 'Database', 'Ali');

insert into Department(Dept_no,Dept_Name,Manager)


values(3, 'Programming', 'Moussa');

‘Creating Employee Table’

Create table Employee(


Emp_No int not null primary key,
Dept_No int not null foreign key (dept_No) references department
(dept_no),
First_N varchar(30),
Last_N varchar(30),
Telephone varchar(30));

‘inserting Data into Employee’


P a g e 42 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

insert into Employee (Emp_No, Dept_No, First_N, Last_N,Telephone)


Values (10, 1 , 'Mamadou', 'Balde', '0552536253');
insert into Employee (Emp_No, Dept_No, First_N, Last_N,Telephone)
Values (11, 2 , 'Aliou', 'Toure', '0545865232');
insert into Employee (Emp_No, Dept_No, First_N, Last_N,Telephone)
Values (12, 3 , 'Abou', 'Traore', '0458623255');

‘Creating Work_On Table’


Create table work_On (
work_No int not null primary key,
Emp_No int not null foreign key (Emp_No) references Employee (Emp_No),
Starting_date datetime,
Ending_Date datetime);

‘inserting Data into Work_On’


insert into work_On( work_No, Emp_No, Starting_date, Ending_Date )
values (15, 10, '01-02-2018', '02-03-2019');
insert into work_On( work_No, Emp_No, Starting_date, Ending_Date )
values (16, 11, '01-02-2014', '02-03-2015');
insert into work_On( work_No, Emp_No, Starting_date, Ending_Date )
values (17, 12, '01-02-2010', '02-03-2011');

‘Displaying Data from three table such as Department, work_On and


Employee by using the Join and the Inner join’
select Employee.First_N, Employee.Last_N, department.dept_Name ,
work_on.Starting_date, work_On.Ending_Date
from Employee
join Work_on
on Employee.Emp_No = work_On.Emp_No
join Department
on Employee.Dept_No = Department.Dept_no
where work_No = '16';

SQL Functions
SQL has many built-in functions for performing calculations on data.

SQL Aggregate Functions


SQL aggregate functions return a single value, calculated from values in a
column.
P a g e 43 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
Useful aggregate functions:

• AVG() - Returns the average value


• COUNT() - Returns the number of rows
• FIRST() - Returns the first value
• LAST() - Returns the last value
• MAX() - Returns the largest value
• MIN() - Returns the smallest value
• SUM() - Returns the sum

SQL Scalar functions


SQL scalar functions return a single value, based on the input value.

Useful scalar functions:

• UCASE() - Converts a field to upper case


• LCASE() - Converts a field to lower case
• ROUND() - Rounds a numeric field to the number of decimals specified

CREATING LOGINS AND USERS IN SQL SERVER

Creating individual logins and users for SQL gives you a great security
advantage. A login is used for authentication into a SQL instance while a
User is used for authorization into a SQL Database. Note that Logins are
used at the instance level and users are used at the database level.
Here is how to create a new login and User in SQL server.
What is difference between SQL and T SQL?

SQL and T-SQL are the query languages used to manipulate the database
and are an important part of the DBMS. The prior difference
between the SQL and T-SQL is that the SQL is non-procedural while T-
SQL is a procedural language. T-SQL is an extension to SQL, developed
by Sybase and Microsoft.

P a g e 44 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
How to Create a Login?
To create a login, Navigate to Security > Logins

In the next screen, Enter

1. Login Name
2. Select SQL Server authentication
3. Enter Password

P a g e 45 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
4. Click Ok

Login is created

You can also create a login using the T-SQL command.

P a g e 46 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
CREATE LOGIN MyLogin WITH PASSWORD = '123';

How to create a User?


A user is an account that you can use to access the SQL server. To create users,
you can use any of the following two ways:

• Using T-SQL
• Using SQL Server Management Studio

Create User using SQL Server Management Studio


You will be creating a user for the EDU_TSQL database.

1. Connect to SQL Server then expand the Databases folder from the Object
Explorer.
2. Identify the database for which you need to create the user and expand it.
3. Expand its Security folder.
4. Right-click the Users folder then choose "New User…"

You will get the following screen,

1. Enter desired User name


2. Enter the Login name (created earlier)
3. Click OK

P a g e 47 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

User is created

Create User using T-SQL


You can create a new USER using the T-SQL's create user command. The
command takes the following syntax:
P a g e 48 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
create user <user-name> for login <login-name>
create user Guru99 for login MyLogin
Note: That the query should be executed within the query window. If a user is
already created for a Login, SQL Server will throw an error if you create a user
for the same login.

Assigning Permission to a User


Permissions refer to the rules that govern the levels of access that users have on
the secured SQL Server resources. SQL Server allows you to grant, revoke and
deny such permissions. There are two ways to assign permissions in SQL Server:

• Using T-SQL
• Using SQL Server Management Studio

Assign Permission Using SQL Server Management Studio


Step 1) Connect to your SQL Server instance and expand the folders from the
Object Explorer as shown below. Right click on the name of the user, that is,
Guru99 then choose Properties.

P a g e 49 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

Step 2) In the next screen,

1. Click the Securables option from the left.


2. Click on Search

P a g e 50 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

Step 3) In the next window,

1. Select "All Objects belonging to the Schema."


2. Select Schema name as "dbo"
3. Click OK

Step 4)

1. Identify Table you want to Grant Permission


P a g e 51 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
2. In Explicit Permission select Grant
3. Click Okay

Step 5) The user Guru99 is granted SELECT permission on table Course.

Grant Permission using T-SQL


To grant permission to a user using T-SQL, you first select the database using the
use statement. You then assign the permission to the user using the grant
statement. Here is the syntax:

use <database-name>
grant <permission-name> on <object-name> to <username\principle>
For example, the following command shows how you can grant the select
permission to the user Guru99 on the object (table) named Course within the
Database EDU_TSQL:

USE EDU_TSQL
GO
Grant select on Course to Guru99
The permission will be granted!

P a g e 52 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
Logins and Users are vital for SQL server to work and now you know
how to create them.
If you want to connect to your User Account, you need to open the
Server Manage.

Troubleshooting Microsoft SQL Server Error 18456, Login


failed for user
Login errors with Microsoft SQL Server (MSSQL) are a fairly common issue and can be
easily solved with some basic troubleshooting steps. Before we dig in, let’s take a look
at the details of the error to try and determine the cause.

Solutions to Microsoft SQL Server Error 18456


Sometimes, the error presents as “login failed for user ‘<username>’,” this information
will help us as we identify the user we need to troubleshoot. From the message, we’ll
know the error number as a reference to search for next steps. In this case, it is
Microsoft SQL Server, Error: 18456.

Other times, we may only see “Microsoft SQL Server Error 18456” along with the
severity and state number. On its own, a state number might not mean much, yet it can
offer more details as to what is wrong and where to look next.

These states of the error, 18456, are the most common. The descriptions and potential
solutions offer a quick explanation and potential troubleshooting guide.

P a g e 53 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

Step 1: Log In with Remote Desktop


The troubleshooting and solutions require you to login to the server or at least be able to
make a Windows Authentication connection to MSSQL using Microsoft SQL Server
Management Studio. The most common and easiest method is to connect directly to the
server with a Remote Desktop Connection. If you need more information about Remote
Desktop Connection, these Knowledge Base articles will help you get connected:

Step 2: Run Microsoft SQL Server Management


Once you are logged into the server, you’ll want to run Microsoft SQL Server
Management Studio (SSMS). SSMS is the tool best suited to configure, manage, and
administer MSSQL.

P a g e 54 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

When you start SSMS, you will be asked to log in to the server. By default, most
MSSQL servers have Windows Authentication enabled, meaning you must log in with
the Windows Administrator or the account specified as the SQL Administrator when
MSSQL was installed and configured.

In addition to Windows Authentication, MSSQL supports SQL Server Authentication.


Depending on the version of MSSQL and how it was installed and configured, you may
or may not have SQL Server Authentication enabled by default.

Step 3: Checking the Server Authentication Mode


Once we login to SSMS using Windows Authentication, we need to check the security
settings to confirm whether MSSQL is set up to allow both Windows and SQL
Authentication.

In SSMS, right-click the Server Name at the top of the Object Explorer window and
choose Properties.

Next, click the Security page.

P a g e 55 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

If you find Windows Authentication is the only mode configured, this is the likely
cause of Error 18456, Login failed for user ‘<username>’.

Setting the Server authentication mode to allow SQL Server and Windows
Authentication, you will be able to login to MS-SQL with a SQL user and password or
a Windows user and password. After making this change, you will need to restart the
SQL Server service.

Step 4: Restart the SQL Service


In SSMS, right-click the Server Name at the top of the Object Explorer window and
choose Restart to apply the new authentication mode settings.

In the above example, Windows Authentication mode was the only mode configured,
and the Error 18456 occurred because the user ‘sa’ is a SQL user and SQL Server
Authentication was not permitted.

Step 5: Checking SQL User Permissions


As we check the SQL user permissions, we need to answer the following questions:

• Is the user allowed to log in?


• Does the user have a valid password set up?
• Does the user have the needed permissions for access to the desired database?

In SSMS Object Explorer, expand Security, Logins. Locate the user that was failing
to log in. A red x on the user indicates this user has login disabled.

P a g e 56 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

To allow the user to login, right-click the user and choose Properties, then click
the Status page. Enabling login for the user and click OK.

After refreshing the list user logins, we can confirm the user no longer has a red x
present. This should allow the user to log in. In this example, the SQL user ‘sa’ failed to
log in because there was no permission to log in.

Continuing with user troubleshooting, right-click the user and choose Properties, then
click the General page. Here you can enter a new password and then enter

P a g e 57 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
the confirmation password. Click OK to save the new password. We set a new
password for the user so that we are certain of the password when we attempt to log in.

Step 6: Mapping the User to the Database


Our last step in troubleshooting a user is to check user mapping to verify the user has
access to the desired database and to set or verify their role for the database. Right-
click the user and choose Properties, then click the User Mapping page. Select
the Database from the list of databases. From the database role memberships, select
the desired/required memberships. Click OK.

P a g e 58 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

In this example, we mapped the user ‘ProdX709’ to the database Production


X709.2019 and granted them database role db_owner. In many cases, you only need a
user to have db_datareader and db_datawriter roles to be able to read and write to
the database.

In this troubleshooting article, we learned how to identify specifics of Error 18456 to help
us track down the root cause of the issue. Still looking for support? Our MSSQL
database solutions come with assistance from our technical support team. Find out how
our high-availability database can work for you!

Backup by using SQL Server Management Studio


Open your SQL server Management Studio

P a g e 59 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

Once you start creating a backup task with SQL Server Management Studio or SSMS,
there is also an option to generate the corresponding T-SQL backup with the help of
Script button. Also, select the Script destination for process completion.

Backup a database

1. Connect to the proper instance of MS SQL Server database engine. Next, go to


Object Explorer and click the Server Name to expand the Server tree.
2. Open the Database and select a User Database.

P a g e 60 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

3. Right Click on the database, go to Tasks and click on Backup to open Backup
Database dialog box.

P a g e 61 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

There are different options for relational database backup, and all involve exclusive
SSMS steps. Refer to the site for the list of the available set of SSMS commands and
restore the database from a. back file.

How to restore database from .BAK file using SSMS

▪ Right Click on the Database, select Task -> Restore -> Database

P a g e 62 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

▪ After clicking on database option, a Restore Database window opens

▪ You can choose the database to restore, or you can

create a new database during restore process. I selected the From


device option

P a g e 63 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

▪ Specify the backup

P a g e 64 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
▪ Select the .BAK file and click OK

▪ Click OK

▪ The .BAK file will be list on the Database restore window

P a g e 65 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

▪ Before restoring the backup, select Options as shown in the figure:

P a g e 66 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

▪ You will get the following Restore options:

Am I overwriting the existing database?

If you don't want to overwrite the existing database then, you could create a new
database and in that case, you would have to move the physical file to the new location.
P a g e 67 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
The most important part of Restore operation is Recovery State:

RESTORE WITH RECOVERY vs RESTORE WITH NORECOVERY

If you are doing differential restore after full restore, If you are doing log restore after full
restore you cannot leave your database in recovered state, you leave it in non-
recovered state ready for more backups to be applied.

I am selecting the first option "Leave the database ready to use by rolling back
uncommitted transactions. Additional transaction log cannot be restored. (RESTORE
WITH RECOVERY)"

Database restored successfully


P a g e 68 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

However, the long list of commands may not be a feasible option for any SQL
Administrator to perform at the time of crisis. Today, downtime in any form is not
acceptable. The process of restore database in SQL server 2014 from .BAK file, using
T-SQL or SSMS Commands is lengthy and time-consuming. Downtime to restore the
database from the .bak file is inevitable, but you can reduce the duration with the help of
a specialized SQL database recovery software. Such software requires selection of the
database to scan, repair, and finally save it at a preferred location.

Using the T-SQL Statement


Explanation

The BACKUP DATABASE command gives you many options for creating
backups. Following are different examples.

Create a full SQL Server backup to disk


The command is BACKUP DATABASE databaseName. The "TO DISK" option
specifies that the backup should be written to disk and the location and filename to
create the backup is specified.

BACKUP DATABASE AdventureWorks


TO DISK = 'C:\AdventureWorks.BAK'
GO

Create a full SQL Server backup to multiple disk files


This command uses the "DISK" option multiple times to write the backup to three
equally sized smaller files instead of one large file.

BACKUP DATABASE AdventureWorks


TO DISK = 'C:\AdventureWorks_1.BAK',
DISK = 'E:\AdventureWorks_3.BAK'
GO

P a g e 69 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
Create a full SQL Server backup with a password
This command creates a backup with a password that will need to be supplied when
restoring the database.

BACKUP DATABASE AdventureWorks


TO DISK = 'C:\AdventureWorks.BAK'
WITH PASSWORD = '1234'
GO

Create a SQL Server backup and give it a description


This command uses the description option to give the backup a name. This can later be
used with some of the restore commands to see what is contained with the
backup. The maximum size is 255 characters.

BACKUP DATABASE AdventureWorks


TO DISK = 'C:\AdventureWorks.BAK'
WITH DESCRIPTION = 'Full backup for AdventureWorks'
GO

How to restore database from .BAK file using SSMS

▪ Right Click on the Database, select Task -> Restore -> Database

▪ After clicking on database option, a Restore Database window opens

P a g e 70 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

▪ You can choose the database to restore, or you can create a new database
during restore process. I selected the From device option

P a g e 71 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
▪ Specify the backup

▪ Select the .BAK file and click OK

P a g e 72 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

▪ Click OK

▪ The .BAK file will be list on the Database restore window

P a g e 73 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

▪ Before restoring the backup, select Options as shown in the figure:

P a g e 74 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

▪ You will get the following Restore options:

P a g e 75 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE

Am I overwriting the existing database?

If you don't want to overwrite the existing database then, you could create a new
database and in that case, you would have to move the physical file to the new
location.

The most important part of Restore operation is Recovery State:

RESTORE WITH RECOVERY vs RESTORE WITH NORECOVERY

If you are doing differential restore after full restore, If you are doing log restore
after full restore you cannot leave your database in recovered state, you leave it in
non-recovered state ready for more backups to be applied.

P a g e 76 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
I am selecting the first option "Leave the database ready to use by rolling back
uncommitted transactions. Additional transaction log cannot be restored. (RESTORE
WITH RECOVERY)"

Database restored successfully

However, the long list of commands may not be a feasible option for any SQL
Administrator to perform at the time of crisis. Today, downtime in any form is not
acceptable. The process of restore database in SQL server 2014 from .BAK file, using
T-SQL or SSMS Commands is lengthy and time-consuming. Downtime to restore the
database from the .bak file is inevitable, but you can reduce the duration with the
help of a specialized SQL database recovery software. Such software requires
selection of the database to scan, repair, and finally save it at a preferred location.

You can create a database by restoring a database you had backed up earlier. It
can be done by running the restore database command which takes the following
syntax:
Restore Database <database name>
P a g e 77 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877
ADEPTS INSTITUTE
From Disk = ‘<Backup file location + filename>’;

The query should be executed within the query window just like out previous
command.
For example:
Restore database Guinea
From Disk = ‘C:\Backup\Guinea_Backup.bak’

P a g e 78 | 78
Powered by Mr. Kaba Abou/Contact: +233 235 906 915/WhatsApp: +224 628 986 877

You might also like