0% found this document useful (0 votes)
4 views

SQL All Notes

SQL, or Structured Query Language, is a standardized language used to access and manipulate databases, allowing users to execute queries, retrieve, insert, update, and delete records. It includes various commands categorized into Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Transaction Control Language (TCL), and Data Query Language (DQL). Key SQL commands include CREATE, ALTER, DROP, SELECT, and TRUNCATE, each serving specific functions in database management.

Uploaded by

chotuwazir1256
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

SQL All Notes

SQL, or Structured Query Language, is a standardized language used to access and manipulate databases, allowing users to execute queries, retrieve, insert, update, and delete records. It includes various commands categorized into Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Transaction Control Language (TCL), and Data Query Language (DQL). Key SQL commands include CREATE, ALTER, DROP, SELECT, and TRUNCATE, each serving specific functions in database management.

Uploaded by

chotuwazir1256
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

f) . Y.

PATUli
- f'IJ L. J\ H

4:emeo+ s 1�0 cl ud e i ---

c:tema,1e
pe of o
1
2
3
4
5
6
7
8
9
10
11
12
1
2
3
4
5
6
7
8
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

ADVANTAGES:
1. It is an English-like language, easy-to-use yet powerful database query language.
2. It is a non-procedural language (i.e., user needs only to specify the system what
data to get from database, not how to get the information requested by the user.)
3. Standard. It means it is supported by all major RDBMS. Thus skills learned on one
platform may be applied to another platform.
4. Portable: Programs written in SQL are portable, i.e., programs written on one
platform can be transferred to another platform and they work fine.
SQL Commands

Types of SQL

DDL DML DCL TCL DQL

Create
Alter Insert Commit
Grant
Drop Update Rollback Select
Revoke
Truncate Delete SavePoint
Rename

TYPES OF SQL:
1. DDL (Data Definition Language)
2. DML (Data Manipulation Language)
3. DCL (Data Control Language)
4. TCL (Transaction Control Language)
5. DQL (Data Query Language)
DATA DEFINITION LANGUAGE (DDL):-
 Data definition language (DDL) is used for creating and modifying the database
objects such as tables, indices, views and users.
 DDL commands are used to define structure and schema of the database.
 All the command of DDL are auto-committed that means it permanently save all
the changes in the database.
There are five main commands in DDL.
1. CREATE : - to create new table or database.
2. ALTER : - to alter or modify the structure of table.
3. DROP : - to delete a table from database.
4. Truncate : - to delete all records from table.
5. Rename : - to rename a table.

1. CREATE COMMAND:
1. Create statement is used to create database schema to define the type and
structure of the data to be stored in the database.
2. Create statement can be used for
o Creating a database
o Creating a table, etc.
3. Create database statement is used to create a database in RDBMS.
Syntax:-
Create database database_name;
Example:-
Create database my_db;
Note: - show statements – To see existing databases and tables
Show databases;
Show tables;
Create Table: -
Create table statement is used to create a new table in a database.
It specifies column names of the table, its data types (e.g. varchar, integer, date, etc.)
and can also specify integrity constraints (e.g. Primary Key, not null, unique).
Used for Creation of a table
Syntax:
CREATE TABLE table-name (Column_name1 datatype(size) constraint,
Column_name2 datatype(size) constraint,

);

Basic components necessary to create a table:


A table must have the following components:
• The key words CREATE TABLE
• A name for the table you want to create
• Opening bracket
• At least one column with its data type.
• Optional size of the data type and constraints on the column
• Closing bracket
• SQL statement terminator –a semicolon

Syntactical and naming conventions to be followed when creating a table:


• Each column must be separated by a comma (,) except the last column.
• Table and column names must start with an alphabet, but they can include
alphabets, numerals, and underscores.
• Blank spaces cannot be used in a table name. In order to separate the table
name, the only character allowed is an underscore.
• Table name cannot exceed 30 characters in length
• Table name must be unique in the Schema.
• Column names in a table must be unique.
Constraints:
The purpose of constraints is to enforce some checks and balances to maintain the
integrity of the database e.g. primary key, foreign key etc. These constraints will also
reduce the work at the application level by letting the database handle the work of
maintaining the integrity of the data. Constraints can be specified either at the
column level (Column constraint) or at the table level (Table constraint).
Note: Constraints on multiple columns e.g. composite primary keys are defined using
table constraints. Single column constraints can be defined using either table
constraints or column constraints.
SQL Constraint
Constraints are used to limit the type of data that can go into a table.
Types of Constraints:-
 Not Null
 Unique
 Primary Key
 Foreign Key
 Cheque
 Default

Column constraint:
CREATE TABLE employee
( empno NUMBER (4) PRIMARY KEY, ename VARCHAR2(10),
job CHAR(9) NOT NULL,
mgr_id NUMBER(4) REFERENCES employee(empno),
hiredate DATE,
salary NUMBER(7,2),
commission NUMBER(7,2),
deptno NUMBER(2) REFERENCES DEPT(DEPTNO)
);
Table constraint:
CREATE TABLE employee ( empno NUMBER(4),
ename VARCHAR2(10),

deptno NUMBER(2) NOT NULL,
PRIMARY KEY (empno, ename)
);
CREATE TABLE employee ( empno NUMBER(4),
ename VARCHAR2(10),

deptno NUMBER(2) NOT NULL,
FOREIGN KEY (deptno) REFERENCES dept (deptno)
);
Note: The FOREIGN KEY reserved word should be used only for table constraints.
CONSTRAINT clause:
Constraints can be named by users using the CONSTRAINT clause as shown below.
CREATE TABLE employee ( empno NUMBER(4),
ename VARCHAR2(10),

deptno NUMBER(2) NOT NULL,
CONSTRAINT pk_emp PRIMARY KEY (empno, ename)
);
The primary key constraint is named as pk_emp in the above example. In the
following example, the foreign key constraint is named fk_deptno.
CREATE TABLE employee ( empno NUMBER(4),
ename VARCHAR2(10),

deptno NUMBER(2) NOT NULL,
CONSTRAINT fk_deptno FOREIGN KEY (deptno) REFERENCES dept (deptno)
);
Note: - Desc (or Describe) statements to create the details of the table structure.
Syntax:-
desc table_name;
Example:-
desc employee;

Primary Key
Primary key constraint uniquely identifies each record in a database table.
Primary key must contain unique values.
Primary key column can’t contain null values.
Each table should have a primary key & each table can have only one primary key.

Foreign Key
A foreign key in one table points to primary key in another table.

Difference between Primary Key & Foreign Key


Sr. No. Primary Key Foreign Key
1 Primary key used to uniquely Foreign key is a field in the table that
identifies a record in the table. is primary key in another table.
2 We can have only one primary key in We can have more than one foreign
a table. key in a table.
3 Primary key can’t accept null value. Foreign Key can accept multiple null
values.
4 Primary key will not allowed Foreign key will allowed duplicate
duplicate value. value.
5 Automatically generated index. Not automatically generated index.
6 Table – Parent Table Table – Child Table
ALTER COMMAND:
 Alter Table statement is used to modify the structure of the existing table.
 It is used to add, delete, modify or rename column in an existing table.
 It is also used to add and drop various constraints on an existing table.
Tables can be altered in one of two ways: by changing a column’s definition, or by
adding a column.
Adding a column: Alter Table – add column – for adding new column in a table.
Syntax:
ALTER TABLE table_name ADD ([column] / [constraint]);
Example:
ALTER TABLE employee ADD (deptno NUMBER(2) );

Rules for adding a column:


• When adding a column, NOT NULL cannot be specified with the column (if some
data already exists in table).
• NOT NULL column can be added in three steps:
1. Add the column without NOT NULL specified
2. Fill every row in that column with data
3. Modify the column to be NOT NULL
Modifying a column: Alter Table – modify column – To modify existing column in a
table.
Syntax:
ALTER TABLE table_name MODIFY ([column] / [constraint]);
Example:
ALTER TABLE employee MODIFY (last_name VARCHAR2(15),
first_nam VARCHAR2(20) NOT NULL);
Rules to modify a column:
 Increase a character column’s width at any time
 Increase the number of digits in a NUMBER columns at any time
 Increase or decrease the number of decimal places in a NUMBER column at any
time
Delete or drop Column: Alter Table – drop column – for removing existing column
in a table.
For removing existing column in table.
Syntax:-
Alter Table table_name Drop Column_name(s);
Example:-
Alter Table Emp Drop Email;
Rename Column: Alter Table – rename column – To rename an existing column in a
table.
Syntax:-
Alter Table table_name Rename old_column_name To new_column_name;
Example:-
Alter Table Emp Rename Address To Location;

DROP COMMAND:
Drop table statement completely removes a table from the database.
This command will destroy the table structure and the data stored in it.
It is used to drop tables when they are no longer needed.
Syntax:
DROP Table table_name;
Example:
DROP Table employee;
Drop command is also be used on databases.
Drop database statement is used to delete the complete databse.
Syntax:
DROP Database database_name;
Example:
DROP database my_db;
TRUNCATE COMMAND:
Truncate table statement is used to remove all rows (Complete data) from a table. It
is similar to the DELETE statements with no WHERE clause.
Syntax:
Truncate Table table_name;
Example:
Truncate Table employee;

TRUNCATE TABLE Vs. DROP TABLE


Drop table command can also be used to delete complete table but it deletes
table structure too.
RENAME COMMAND:
Rename table statement is used to change the name of a table.
Syntax:-
Rename Table old_table_name To new_table_name;
Example:-
Rename Table Emp To Employee;
Difference between delete, truncate and drop command in SQL
No. Delete Command Truncate Command Drop Command
1 Delete is a DML command Truncate is a DDL Drop is a DDL
Command command
2 Delete is used to delete the Truncate is used to delete Drop is used to drop
records in the table the data and keep the table the table data as well
structure as it is. as table structure.
3 Delete statements use the Truncate can’t use where Drop can’t use where
where clause to delete clause to delete particular clause.
particular records. data.
4 Delete statements can be Truncate statement can’t Drop statement can’t
rollback before the rollback. rollback.
commit.
5 Delete is slower as Truncate is faster. Drop removes the table
compare to Truncate. from the database.
6 Syntax:- Syntax:- Syntax:-
Delete Table Table_Name; Truncate Table Drop Table
Table_Name; Table_Name;
7 Example:- Example:- Example:-
Delete Table emp; Truncate Table emp; Drop Table emp;
DATA QUERY LANGUAGE (DQL):
1. SELECT

SELECT COMMAND:
SELECT command is used to retrieve the information from a table or tables. Format:
SELECT column1, column2…
FROM table_name
WHERE conditions;

SELECT clause
The SELECT clause is used to specify which columns are to be selected. In the
following statement ‘*’ retrieves all the columns from the table employee.
Ex: SELECT *
FROM employee;

FROM clause
FROM is used to specify the names of the table or tables from which the data is
retrieved.
Database Tables
A database most often contains one or more tables. Each table is identified by a name
(e.g."Customers" or "Orders"). Tables contain records (rows) with data.
Below is an example of a table called "Persons":
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The table above contains three records (one for each person) and five columns (P_Id,
LastName,FirstName, Address, and City).

SQL Statements
Most of the actions you need to perform on a database are done with SQL
statements.The following SQL statement will select all the records in the
"Persons" table:
SELECT * FROM Persons;
SQL is not case sensitive. 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.
We are using MS Access and SQL Server 2000 and we do not have to put a semicolon
after eachSQL statement, but some database programs force you to use it.

SQL DML and DDL


SQL can be divided into two parts: The Data Manipulation Language (DML) and the
DataDefinition Language (DDL).

The query and update commands form the DML part of SQL:

 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

The DDL part of SQL permits database tables to be created or deleted. It also define
indexes (keys), specify links between tables, and impose constraints between tables.
The most importantDDL statements in SQL are:

 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
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.
SQL SELECT Syntax
SELECT column_name(s)
FROM table_name
and
SELECT * FROM table_name
An SQL SELECT Example
The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the content of the columns named "LastName" and
"FirstName" from thetable above.
We use the following SELECT statement:
SELECT LastName,FirstName FROM Persons
The result-set will look like thi
LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari

SELECT * Example
Now we want to select all the columns from the "Persons"
table.We use the following SELECT statement:
SELECT * FROM Persons
Tip: The asterisk (*) is a quick way of selecting all
columns!The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

SQL SELECT DISTINCT Statement


In a table, some of the columns may contain duplicate values. This is not a problem,
however,sometimes you will want to list only the different (distinct) values in a table.
The DISTINCT keyword can be used to return only distinct (different) values.
SQL SELECT DISTINCT Syntax
SELECT DISTINCT
column_name(s) FROM
table_name
SELECT DISTINCT Example
The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select only the distinct values from the column named "City" from
the tableabove.
We use the following SELECT statement:
SELECT DISTINCT City FROM Persons
The result-set will look like this:
City
Sandnes
Stavanger

WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified
criterion.
SQL WHERE Syntax
SELECT
column_name(s)
FROM table_name
WHERE column_name operator value
WHERE Clause Example
The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select only the persons living in the city "Sandnes" from the
table above.We use the following SELECT statement:
SELECT * FROM
Persons WHERE
City='Sandnes'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
Quotes around Text Fields
SQL uses single quotes around text values (most database systems will also accept
doublequotes).
Although, numeric values should not be enclosed in
quotes.For text values:
This is correct:
SELECT * FROM Persons WHERE
FirstName='Tove' This is wrong:
SELECT * FROM Persons WHERE FirstName=Tove

For numeric values:


This is correct:
SELECT * FROM Persons WHERE
Year=1965 This is wrong:
SELECT * FROM Persons WHERE Year='1965'

Operators Allowed in the WHERE Clause


With the WHERE clause, the following operators can be used:
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN If you know the exact value you want to return for at least one of the
columns

Note: In some versions of SQL the <> operator may be written as !=


AND & OR Operators
The AND operator displays a record if both the first condition and the second
condition is true.The OR operator displays a record if either the first condition or
the second condition is true.

AND Operator Example


The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select only the persons with the first name equal to "Tove" AND the
last nameequal to "Svendson":
We use the following SELECT statement:
SELECT * FROM Persons WHERE FirstName='Tove' AND LastName='Svendson'
The result-set will look like this:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes

OR Operator Example
Now we want to select only the persons with the first name equal to "Tove" OR the
first nameequal to "Ola":
We use the following SELECT statement:
SELECT * FROM PersonsWHERE FirstName='Tove'OR FirstName='Ola'
The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

Combining AND & OR


You can also combine AND and OR (use parenthesis to form complex expressions).
Now we want to select only the persons with the last name equal to "Svendson" AND
the firstname equal to "Tove" OR to "Ola":
We use the following SELECT statement:
SELECT * FROM Persons WHERELastName='Svendson'
AND (FirstName='Tove' OR FirstName='Ola')The result-set will look like this:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes

ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set by a specified
column.The ORDER BY keyword sort the records in ascending
order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.
SQL ORDER BY Syntax
SELECT column_name(s) FROM table_name
ORDER BY column_name(s) ASC|DESC

ORDER BY Example
The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Tom Vingvn 23 Stavanger

Now we want to select all the persons from the table above, however, we want to sort
the personsby their last name.
We use the following SELECT statement:
SELECT * FROM Persons ORDER BY LastName
The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
4 Nilsen Tom Vingvn 23 Stavanger
3 Pettersen Kari Storgt 20 Stavanger
2 Svendson Tove Borgvn 23 Sandnes

ORDER BY DESC Example


Now we want to select all the persons from the table above, however, we want to sort
the personsdescending by their last name.
We use the following SELECT statement:
SELECT * FROM Persons ORDER BY LastName DESC
The result-set will look like this:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Tom Vingvn 23 Stavanger
1 Hansen Ola Timoteivn 10 Sandnes
The INSERT INTO Statement
The INSERT INTO statement is used to insert a new row in a table.
SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't 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,...)
SQL INSERT INTO Example
We have the following "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to insert a new row in the


"Persons" table.We use the following SQL
statement:
INSERT INTO Persons VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')
The "Persons" table will now look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
The UPDATE Statement
The UPDATE statement is used to update existing records in a table.
SQL UPDATE Syntax
UPDATE table_name SET column1=value, column2=value2,... WHERE
some_column=some_value
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause
specifies whichrecord or records that should be updated. If you omit the
WHERE clause, all records will be updated!
SQL UPDATE Example
The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob

Now we want to update the person "Tjessem, Jakob" in the


"Persons" table.We use the following SQL statement:
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
WHERE LastName='Tjessem' AND FirstName='Jakob'

The "Persons" table will now look like this:


P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob Nissestien 67 Sandnes
The DELETE Statement
The DELETE statement is used to delete rows in a table.

SQL DELETE Syntax


DELETE FROM table_name WHERE some_column=some_value

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies
whichrecord or records that should be deleted. If you omit the WHERE clause, all
records will be deleted!
SQL DELETE Example
The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob Nissestien 67 Sandnes

Now we want to delete the person "Tjessem, Jakob" in the


"Persons" table.We use the following SQL statement:
DELETE FROM Persons
WHERE LastName='Tjessem' AND FirstName='Jakob'

The "Persons" table will now look like this:


P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
Delete All Rows
It is possible to delete all rows in a table without deleting the table. This means that
the tablestructure, 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 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
LIKE Operator Example
The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the persons living in a city that starts with "s" from the
table above.We use the following SELECT statement:
SELECT * FROM
Persons WHERE
City LIKE 's%'

The "%" sign can be used to define wildcards (missing letters in the pattern)
both before andafter the pattern.
The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Next, we want to select the persons living in a city that ends with an "s" from the
"Persons" table.
We use the following SELECT statement:
SELECT * FROM
Persons WHERE
City LIKE '%s'

The result-set will look like this:


P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

Next, we want to select the persons living in a city that contains the pattern "tav"
from the"Persons" table.
We use the following SELECT statement:
SELECT * FROM
Persons WHERE
City LIKE '%tav%'
The result-set will look like this:
P_Id LastName FirstName Address City
3 Pettersen Kari Storgt 20 Stavanger
It is also possible to select the persons living in a city that NOT contains the pattern
"tav" fromthe "Persons" table, by using the NOT keyword.

We use the following SELECT statement:


SELECT * FROM
Persons WHERE City
NOT LIKE '%tav%'
The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

SQL Wildcards
SQL wildcards can substitute for one or more characters when searching for data in a
database.SQL wildcards must be used with the SQL LIKE operator.
With SQL, the following wildcards can be used:

Wildcard Description
% A substitute for zero or more characters
_ A substitute for exactly one character
[charlist] Any single character in charlist
[^charlist]or Any single character not in charlist
[!charlist]

SQL Wildcard Examples


We have the following "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Using the % Wildcard
Now we want to select the persons living in a city that starts with "sa" from the
"Persons" table.We use the following SELECT statement:
SELECT * FROM
PersonsWHERE City
LIKE 'sa%'
The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

Next, we want to select the persons living in a city that contains the pattern "nes"
from the"Persons" table.
We use the following SELECT statement:
SELECT * FROM
Persons WHERE City
LIKE '%nes%'
The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

Using the _ Wildcard


Now we want to select the persons with a first name that starts with any character,
followed by"la" from the "Persons" table.
We use the following SELECT
statement:SELECT * FROM Persons
WHERE FirstName LIKE '_la'

The result-set will look like this:


P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Next, we want to select the persons with a last name that starts with "S", followed
by any character, followed by "end", followed by any character, followed by "on"
from the "Persons"table.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE LastName LIKE
'S_end_on'The result-set will
look like this:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes

Using the [charlist] Wildcard


Now we want to select the persons with a last name that starts with "b" or "s" or "p"
from the"Persons" table.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE LastName LIKE
'[bsp]%'
The result-set will look like this:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Next, we want to select the persons with a last name that do not start with "b" or
"s" or "p" fromthe "Persons" table.
We use the following SELECT
statement:SELECT * FROM Persons
WHERE LastName LIKE '[!bsp]%'

The result-set will look like this:


P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
Syntax
SELECT column_name(s) FROM table_name
WHERE column_name IN (value1,value2,...)
Example
The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the persons with a last name equal to "Hansen" or
"Pettersen" from thetable above.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE LastName IN ('Hansen','Pettersen')
The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The BETWEEN Operator


The BETWEEN operator selects a range of data between two values. The
values can benumbers, text, or dates.
SQL BETWEEN Syntax
SELECT
column_name(s)
FROM table_name
WHERE
column_name
BETWEEN value1 AND value2
SQL Alias
You can give a table or a column another name by using an alias. This can be a good
thing to doif you have very long or complex table names or column names.

An alias name could be anything, but usually it is short.


SQL Alias Syntax for Tables
SELECT
column_name(s)
FROM table_name
AS alias_name

SQL Alias Syntax for Columns


SELECT column_name AS
alias_name FROM table_name

The CREATE DATABASE Statement


The CREATE DATABASE statement is used to create a database.

SQL CREATE DATABASE Syntax


CREATE DATABASE database_name

CREATE DATABASE Example


Now we want to create a database called "my_db".
We use the following CREATE DATABASE statement:

CREATE DATABASE my_db


Database tables can be added with the CREATE TABLE statement.
The CREATE TABLE Statement
The CREATE TABLE statement is used to create a table in a database.
Syntax
CREATE TABLE table_name (
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
);
The data type specifies what type of data the column can hold. For a complete
reference of all the data types available in MS Access, MySQL, and SQL Server, go to
our complete Data Types reference.
CREATE TABLE Example
Now we want to create a table called "Persons" that contains five columns: P_Id,
LastName,FirstName, Address, and City.
We use the following CREATE TABLE statement:
CREATE TABLE Persons (
P_Id int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
The P_Id column is of type int and will hold a number. The LastName, FirstName,
Address, andCity columns are of type varchar with a maximum length of 255
characters.
The empty "Persons" table will now look like this:
P_Id LastName FirstName Address City

The empty table can be filled with data with the INSERT INTO statement.
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a
column.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
The AVG() Function
The AVG() function returns the average value of a numeric column.
Syntax
SELECT AVG(column_name) FROM table_name
Example
We have the following "Orders" table:
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Now we want to find the average value of the


"OrderPrice" fields.We use the following SQL statement:
SELECT AVG(OrderPrice) AS ‘OrderAverage’ FROM Orders

The result-set will look like this:


OrderAverage
950
SQL COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values (NULL values will
not becounted) of the specified column:

SELECT COUNT(column_name) FROM table_name


SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table:

SELECT COUNT(*) FROM table_name


SQL COUNT(DISTINCT column_name) Syntax
The COUNT(DISTINCT column_name) function returns the number of distinct values
of thespecified column:

SELECT COUNT(DISTINCT column_name) FROM table_name

Note:COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with
Microsoft Access.

SQL COUNT(column_name) Example


We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer


1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
Now we want to count the number of orders from "Customer
Nilsen".We use the following SQL statement:
SELECT COUNT(Customer) AS CustomerNilsen FROM
Orders WHERE Customer='Nilsen'

The result of the SQL statement above will be 2, because the customer Nilsen has
made 2 ordersin total:

CustomerNilsen
2

SQL COUNT(*) Example


If we omit the WHERE clause, like this:

SELECT COUNT(*) AS NumberOfOrders FROM Orders


The result-set will look like this:
NumberOfOrders
6

SQL COUNT(DISTINCT column_name) Example


Now we want to count the number of unique customers in the
"Orders" table.We use the following SQL statement:
SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Orders

The result-set will look like this:


NumberOfCustomers
3

which is the number of unique customers (Hansen, Nilsen, and Jensen) in the
"Orders" table.
The FIRST() Function
The FIRST() function returns the first value of the selected column.
Syntax
SELECT FIRST(column_name) FROM table_name
Example
We have the following "Orders" table:
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Now we want to find the first value of the "OrderPrice"


column.We use the following SQL statement:
SELECT FIRST(OrderPrice) AS FirstOrderPrice FROM Orders
The result-set will look like this:
FirstOrderPrice
1000

The LAST() Function


The LAST() function returns the last value of the selected column.
Syntax
SELECT LAST(column_name) FROM table_name
Example
We have the following "Orders" table:
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Now we want to find the last value of the "OrderPrice"


column.We use the following SQL statement:
SELECT LAST(OrderPrice) AS LastOrderPrice FROM Orders
The result-set will look like this:
LastOrderPrice
100

The MAX() Function


The MAX() function returns the largest value of the selected column.
Syntax
SELECT MAX(column_name) FROM table_name
Example
We have the following "Orders" table:
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
Now we want to find the largest value of the "OrderPrice"
column.We use the following SQL statement:
SELECT MAX(OrderPrice) AS LargestOrderPrice FROM Orders
The result-set will look like this:
LargestOrderPrice
2000

The MIN() Function


The MIN() function returns the smallest value of the selected column.
Syntax
SELECT MIN(column_name) FROM table_name
Example
We have the following "Orders" table:
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Now we want to find the smallest value of the "OrderPrice"


column.We use the following SQL statement:
SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Orders

The result-set will look like this:


SmallestOrderPrice
100
The SUM() Function
The SUM() function returns the total sum of a numeric column.
Syntax
SELECT SUM(column_name) FROM table_name
Example
We have the following "Orders" table:
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Now we want to find the sum of all "OrderPrice"


fields".We use the following SQL statement:
SELECT SUM(OrderPrice) AS ‘OrderTotal’ FROM Orders
The result-set will look like this:
OrderTotal
5700

You might also like