SQL Sarans
SQL Sarans
SQL Sarans
databases.
A Database Management System (DBMS) is a computer program that can access data in a database.The
DBMS program enables you to extract, modify, or store information in a database.A Relational
Database Management System (RDBMS) is a Database Management System (DBMS) where the
database is organized and accessed according to the relationships between data.
The SELECT DISTINCT keyword is used to return only distinct (different) values.
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
1
SQL uses single quotes around text values (most database systems will also accept
double quotes). Numeric values should not be enclosed in quotes.
A "%" sign can be used to define wildcards (missing letters in the pattern) both
before and after the pattern.
The following SQL statement will return persons with first names that contain the pattern 'la':
SELECT column_name(s)
FROM table_name
You can also specify the columns for which you want to insert data:
UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value
2
SELECT CompanyName, ContactName FROM customers WHERE CompanyName > 'a'
When using SQL on text data, "alfred" is greater than "a" (like in a dictionary).
To display the company names in reverse alphabetical order AND the OrderNumber in numerical
order:
Result:
Company OrderNumber
W3Schools 2312
W3Schools 6798
Sega 3412
ABC Shop 5678
The IN operator may be used if you know the exact value you want to return for at least one of
the columns.
The BETWEEN ... AND operator selects a range of data between two values. These values can
be numbers, text, or dates.
To display the persons alphabetically between (and including) "Hansen" and exclusive
"Pettersen", use the following SQL:
3
"Pettersen" will not be listed (BETWEEN..AND only selects fields that are between
and excluding the test values). With some databases a person with the last name of
"Hansen" or "Pettersen" will be listed (BETWEEN..AND selects fields that are
between and including the test values). With other databases a person with the last
name of "Hansen" will be listed, but "Pettersen" will not be listed (BETWEEN..AND
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....AND
operator!
To display the persons outside the range used in the previous example, use the NOT operator:
Result:
With SQL, aliases can be used for column names and table names.
Employees:
Employee_ID Name
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
4
04 Pettersen, Kari
Orders:
5
Who has ordered a product, and what did they order?
Result
Name Product
Example
SELECT Employees.Name
FROM Employees, Orders
WHERE Employees.Employee_ID=Orders.Employee_ID
AND Orders.Product='Printer'
Result
Name
Hansen, Ola
OR we can select data from two tables with the JOIN keyword, like this:
Syntax
6
Who has ordered a product, and what did they order?
The INNER JOIN returns all rows from both tables where there is a match. If there are rows in
Employees that do not have matches in Orders, those rows will not be listed.
Result
Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair
LEFT JOIN
Syntax
Result
Name Product
Hansen, Ola Printer
Svendson, Tove
Svendson, Stephen Table
Svendson, Stephen Chair
Pettersen, Kari
7
RIGHT JOIN
The RIGHT JOIN returns all the rows from the second table (Orders), even if there are
no matches in the first table (Employees). If there had been any rows in Orders that
did not have matches in Employees, those rows also would have been listed.
Result
Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair
SELECT Employees.Name
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
WHERE Orders.Product = 'Printer'
Result
Name
Hansen, Ola
UNION
The UNION command is used to select related information from two tables, much like the JOIN
command. However, when using the UNION command all selected columns need to be of the
same data type.
8
Note: With UNION, only distinct values are selected.
SQL Statement 1
UNION
SQL Statement 2
UNION ALL
The UNION ALL command is equal to the UNION command, except that UNION ALL selects
all values.
Create a Database
To create a database:
Create a Table
To create a table in a database:
The data type specifies what type of data the column can hold. The table below contains the most
common data types in SQL:
9
special characters). The maximum size is specified in parenthesis.
date(yyyymmdd) Holds a date
Create Index
Indices are created in an existing table to locate rows more quickly and efficiently. It is possible
to create an index on one or more columns of a table, and each index is given a name. The users
cannot see the indexes, they are just used to speed up queries.
Note: Updating a table containing indexes takes more time than updating a table without, this is
because the indexes also need an update. So, it is a good idea to create indexes only on columns
that are often used for a search.
A Unique Index
Creates a unique index on a table. A unique index means that two rows cannot have the same
index value.
Example
This example creates a simple index, named "PersonIndex", on the LastName field of the Person
table:
If you want to index the values in a column in descending order, you can add the reserved word
DESC after the column name:
If you want to index more than one column you can list the column names within the
parentheses, separated by commas:
10
You can delete an existing index in a table with the DROP INDEX statement.
To delete a table (the table structure, attributes, and indexes will also be
deleted):
To delete a database:
DROP DATABASE database_name
if we only want to get rid of the data inside a table, and not the table
itself? Use the TRUNCATE TABLE command (deletes only the data inside the
table):
BINARY_CHECKSUM
CHECKSUM
CHECKSUM_AGG
11
COUNT(DISTINCT column) Returns the number of distinct results
STDEV(column)
STDEVP(column)
VAR(column)
VARP(column)
GROUP BY...
GROUP BY... was added to SQL because aggregate functions (like SUM) return the aggregate of
all column values every time they are called, and without the GROUP BY function it was
impossible to find the sum for each individual group of column values.
12
SELECT column,SUM(column) FROM table GROUP BY column
GROUP BY Example
This "Sales" Table:
Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100
Company SUM(Amount)
W3Schools 17100
IBM 17100
W3Schools 17100
The above code is invalid because the column returned is not part of an aggregate. A GROUP BY
clause will solve this problem:
Company SUM(Amount)
W3Schools 12600
IBM 4500
HAVING...
HAVING... was added to SQL because the WHERE keyword could not be used against
aggregate functions (like SUM), and without HAVING... it would be impossible to test for result
conditions.
13
The syntax for the HAVING function is:
Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100
This SQL:
Company SUM(Amount)
W3Schools 12600
Syntax
SELECT column_name(s) INTO newtable [IN externaldatabase]
FROM source
14
The IN clause can be used to copy tables into another database:
If you only want to copy a few fields, you can do so by listing them after the SELECT statement:
You can also add a WHERE clause. The following example creates a "Persons_backup" table
with two columns (FirstName and LastName) by extracting the persons who lives in "Sandnes"
from the "Persons" table:
Selecting data from more than one table is also possible. The following example creates a new
table "Empl_Ord_backup" that contains data from the two tables Employees and Orders:
SELECT Employees.Name,Orders.Product
INTO Empl_Ord_backup
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
What is a View?
In SQL, a VIEW is a virtual table based on the result-set of a SELECT statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one
or more real tables in the database. You can add SQL functions, WHERE, and JOIN statements
to a view and present the data as if the data were coming from a single table.
Note: The database design and structure will NOT be affected by the functions, where, or join
statements in a view.
15
Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Note: The database does not store the view data! The database engine recreates the data, using
the view's SELECT statement, every time a user queries a view.
Table Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego
Example 1:
MySQL/Oracle:
SELECT CONCAT(region_name,store_name) FROM Geography
WHERE store_name = 'Boston';
Result:
'EastBoston'
Example 2:
Oracle:
SELECT region_name || ' ' || store_name FROM Geography
WHERE store_name = 'Boston';
Result:
'East Boston'
16
The '%' is a so called wildcard character and represents any string in our pattern.
Note that different databases use different characters as wildcard characters, for example '%' is a wildcard
character for MS SQL Server representing any string, and '*' is the corresponding wildcard character used
in MS Access.
The '[]' specifies a range of characters. Have a look at the following SQL statement:
SELECT *
FROM Customers
WHERE Phone LIKE '[4-6]_6%'
This SQL expression will return all customers satisfying the following conditions:
grant create session , create table, create view, create sequence to ECI2_BARCAP_STAG_US
17