SQL All Notes
SQL All Notes
PATUli
- f'IJ L. J\ H
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
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
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,
…
);
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.
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;
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.
The query and update commands form the DML part of SQL:
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:
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
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:
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'
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
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:
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
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 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'
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.
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]
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
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]%'
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 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
Note:COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with
Microsoft Access.
The result of the SQL statement above will be 2, because the customer Nilsen has
made 2 ordersin total:
CustomerNilsen
2
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