0% found this document useful (0 votes)
37 views53 pages

SQL Basics For Beginners

SQL is a standard language for querying, manipulating and managing data in relational databases. This tutorial will teach how to use SQL in many common database systems like MySQL, SQL Server, Oracle and more. It covers basic SQL statements for retrieving, inserting, updating, and deleting data as well as more advanced topics like joins, subqueries and more.

Uploaded by

magi
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)
37 views53 pages

SQL Basics For Beginners

SQL is a standard language for querying, manipulating and managing data in relational databases. This tutorial will teach how to use SQL in many common database systems like MySQL, SQL Server, Oracle and more. It covers basic SQL statements for retrieving, inserting, updating, and deleting data as well as more advanced topics like joins, subqueries and more.

Uploaded by

magi
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/ 53

SQL Tutorial

SQL is a standard language for storing, manipulating and retrieving data in databases.
Our SQL tutorial will teach you how to use SQL in: MySQL, SQL Server, MS Access, Oracle, Sybase, Informix,
Postgres, and other database systems.
SQL Tutorial
SQL is a standard language for storing, manipulating and retrieving data in databases.

Our SQL tutorial will teach you how to use SQL in: MySQL, SQL Server, MS Access, Oracle,
Sybase, Informix, Postgres, and other database systems.

Example
SELECT * FROM Customers;

Introduction to SQL

What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in 1987

What Can SQL do?


SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views

SQL is a Standard - BUT....


Although SQL is an ANSI/ISO 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.

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.

Look at the "Customers" table:


Example
SELECT * FROM Customers;

Every table is broken up into smaller entities called fields. The fields in the Customers table
consist of CustomerID, CustomerName, ContactName, Address, City, PostalCode and Country.
A field is a column in a table that is designed to maintain specific information about every record
in the table.

A record, also called a row, is each individual entry that exists in a table. For example, there are
91 records in the above Customers table. A record is a horizontal entity in a table.

A column is a vertical entity in a table that contains all information associated with a specific
field in a table.

Keep in Mind That...


SQL keywords are NOT case sensitive: select is the same as SELECT

Some of The Most Important SQL Commands


● SELECT - extracts data from a database
● UPDATE - updates data in a database
● DELETE - deletes data from a database
● INSERT INTO - inserts new data into a database
● CREATE DATABASE - creates a new database
● ALTER DATABASE - modifies a database
● CREATE TABLE - creates a new table
● ALTER TABLE - modifies a table
● DROP TABLE - deletes a table
● CREATE INDEX - creates an index (search key)
● DROP INDEX - deletes an index
The SQL SELECT Statement

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

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

SELECT Syntax

SELECT column1, column2, ...FROM table_name;{ SELECT * FROM table_name;}

Example SELECT CustomerName, City FROM Customers;

The SQL WHERE Clause


The WHERE clause is used to filter records.

It is used to extract only those records that fulfill a specified condition.

WHERE Syntax
SELECT column1, column2, ...

FROM table_name

WHERE condition;

Example
SELECT * FROM Customers

WHERE Country='Mexico';
Operators in The WHERE Clause
The following operators can be used in the WHERE clause:

Operator Description

= Equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

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

BETWEEN Between a certain range

LIKE Search for a pattern

IN To specify multiple possible values for a column

The SQL AND, OR and NOT Operators


The WHERE clause can be combined with AND, OR, and NOT operators.

The AND and OR operators are used to filter records based on more than one
condition:

● The AND operator displays a record if all the conditions separated by AND
are TRUE.
● The OR operator displays a record if any of the conditions separated by OR
is TRUE.

The NOT operator displays a record if the condition(s) is NOT TRUE.


AND Syntax
Example
SELECT * FROM Customers

WHERE Country='Germany' AND City='Berlin';

OR Syntax
Example
SELECT * FROM Customers

WHERE City='Berlin' OR City='München';

NOT Syntax
Example
SELECT * FROM Customers

WHERE NOT Country='Germany';

The SQL INSERT INTO Statement


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

INSERT INTO Syntax


It is possible to write the INSERT INTO statement in two ways:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)

VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006',


'Norway');

What is a NULL Value?


A field with a NULL value is a field with no value.

If a field in a table is optional, it is possible to insert a new record or update a


record without adding a value to this field. Then, the field will be saved with a
NULL value.

Example
SELECT CustomerName, ContactName, Address

FROM Customers

WHERE Address IS NULL;

How to Test for NULL Values?


It is not possible to test for NULL values with comparison operators, such as =,
<, or <>.

We will have to use the IS NULL and IS NOT NULL operators instead.

Example
SELECT CustomerName, ContactName, Address

FROM Customers

WHERE Address IS NOT NULL;


The SQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.

UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with
a new contact person and a new city.

Example

UPDATE Customers

SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'

WHERE CustomerID = 1;

Example
UPDATE Customers

SET ContactName='Juan'

WHERE Country='Mexico';

The SQL DELETE Statement


The DELETE statement is used to delete existing records in a table.

SQL DELETE Example


The following SQL statement deletes the customer "Alfreds Futterkiste" from the
"Customers" table:
Example

DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

The SQL LIKE Operator


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

There are two wildcards often used in conjunction with the LIKE operator:

● The percent sign (%) represents zero, one, or multiple characters


● The underscore sign (_) represents one, single character

SQL LIKE Examples


The following SQL statement selects all customers with a CustomerName
starting with "a":

Example

SELECT * FROM Customers

WHERE CustomerName LIKE 'a%';

The SQL IN Operator


The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.

IN Operator Examples
The following SQL statement selects all customers that are located in
"Germany", "France" or "UK":

Example

SELECT * FROM Customers

WHERE Country IN ('Germany', 'France', 'UK');

Example
SELECT * FROM Customers

WHERE Country IN (SELECT Country FROM Suppliers);

The SQL BETWEEN Operator


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

The BETWEEN operator is inclusive: begin and end values are included.

BETWEEN 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;


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

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

Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate

FROM Orders

INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:

● (INNER) JOIN: Returns records that have matching values in both tables
● LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
● RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
● FULL (OUTER) JOIN: Returns all records when there is a match in either
left or right table
SQL INNER JOIN Keyword
The INNER JOIN keyword selects records that have matching values in both
tables.

Example
SELECT Orders.OrderID, Customers.CustomerName

FROM Orders

INNER JOIN Customers ON Orders.CustomerID =


Customers.CustomerID;

SQL LEFT JOIN Keyword


The LEFT JOIN keyword returns all records from the left table (table1), and the
matching records from the right table (table2). The result is 0 records from the
right side, if there is no match.

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

Example
SELECT Customers.CustomerName, Orders.OrderID

FROM Customers

LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID

ORDER BY Customers.CustomerName;

SQL RIGHT JOIN Keyword


The RIGHT JOIN keyword returns all records from the right table (table2), and
the matching records from the left table (table1). The result is 0 records from
the left side, if there is no match.

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

Example
SELECT Orders.OrderID, Employees.LastName,
Employees.FirstName

FROM Orders

RIGHT JOIN Employees ON Orders.EmployeeID =


Employees.EmployeeID

ORDER BY Orders.OrderID;

SQL FULL OUTER JOIN Keyword


The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.

Tip: FULL OUTER JOIN and FULL JOIN are the same.
Note: FULL OUTER JOIN can potentially return very large result-sets!

SQL FULL OUTER JOIN Example


The following SQL statement selects all customers, and all orders:

SELECT Customers.CustomerName, Orders.OrderID

FROM Customers

FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID

ORDER BY Customers.CustomerName;

The SQL GROUP BY Statement


The GROUP BY statement groups rows that have the same values into summary
rows, like "find the number of customers in each country".

The GROUP BY statement is often used with aggregate functions (COUNT(),


MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.

The following SQL statement lists the number of customers in each country,
sorted high to low:

Example
SELECT COUNT(CustomerID), Country

FROM Customers

GROUP BY Country

ORDER BY COUNT(CustomerID) DESC;

The SQL HAVING Clause


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

SQL HAVING Examples


The following SQL statement lists the number of customers in each country.
Only include countries with more than 5 customers:

Example

SELECT COUNT(CustomerID), Country

FROM Customers

GROUP BY Country

HAVING COUNT(CustomerID) > 5;

Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM (Orders

INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID)

GROUP BY LastName

HAVING COUNT(Orders.OrderID) > 10;


Structured Query Language (SQL)

You might also like