2nd - SQL Helpbook
2nd - SQL Helpbook
The Data Definition Language (DDL) part of SQL permits database tables to be created or
deleted. We can also define indexes (keys), specify links between tables, and impose constraints
between database tables.
SQL (Structured Query Language) is a syntax for executing queries. But the SQL language also
includes a syntax to update, insert, and delete records.
These query and update commands together form the Data Manipulation Language (DML) part of
SQL:
EMPLOYEE TABLE
Name dept emp_id city batch_id
Bob HR 1002 San Jose 7
sales 1004 San Jose 8
Raj sales 1001 6
Tim sales 1003 Fremont 6
BATCH TABLE
batch_no name startdate email subject
6 BA
update batch
set batch_no=001
where batch_no = 1
Select Command
SELECT * FROM table_name
WHERE column_name = 'criteria’
EXAMPLES:
select * from batch
select name,batch_no from batch
select distinct subject from batch
select name from batch
where subject = 'QA‘
select name from batch
where name like '%a‘
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] Any single character not in charlist
or
[!charlist]
EXAMPLES
WHERE FirstName LIKE '_im' finds all three-letter first names that end with 'im' (e.g. Jim, Tim).
WHERE LastName LIKE '%stein' finds all employees whose last name ends with 'stein'
WHERE LastName LIKE '%stein%' finds all employees whose last name includes 'stein' anywhere in
the name.
WHERE FirstName LIKE '[JT]im' finds three-letter first names that end with 'im' and begin with
either 'J' or 'T' (that is, only Jim and Tim)
WHERE LastName LIKE 'm[^c]%' finds all last names beginning with 'm' where the following
(second) letter is not 'c'.
The IN Operator
Output
Prod Month Qty
Mars Feb 4.0
Lion Jan 3.0
Twix Jan 2.0
Mars Jan 1.0
o Sorting a result set using SQL is achieved by the ORDER BY clause. This goes at the
end of a SQL query, i.e. following the WHERE block and everything else.
o The example in the slide shows the output being ordered by two columns, Month in
ascending order (ASC) and Qty in descending order.
o If you omit either ASC or DESC the default is ASC
select <col-list> from <table-name>
[where <cond>]
[group by <col> having <cond>]
[order by <col-name>];
Alter
To add a column:
ALTER TABLE table_name
ADD column_name datatype
To drop a column:
ALTER TABLE table_name
DROP COLUMN column_name
EXAMPLES:
alter table batch
add country char(20)
• To delete a database:
DROP DATABASE database_name
• Truncate a Table
What 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):
TRUNCATE TABLE table_name
- You cannot rollback after using the TRUNCATE statement.
Joins
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a
relationship between certain columns in these tables.
INNER JOIN
EQUI JOIN
Return rows when there is at least one match in both tables
select batch.batch_no,batch.name,employees.emp_id,employees.name
from batch,employees
where batch.batch_no=employees.batch_id
OUTER JOINS
LEFT JOIN
Return all rows from the left table, even if there are no matches in the right table
select * from batch
LEFT JOIN employees
ON batch.batch_no=employees.batch_id
RIGHT JOIN
Return all rows from the right table, even if there are no matches in the left table
select * from batch
RIGHT JOIN employees
ON batch.batch_no=employees.batch_id
SQL Functions
Count
To count the number of records in the ‘batch’ table
SELECT COUNT(batch_no ) from batch
To count the number of distinct batch_ids in the employees table (duplicates counted only once)
SELECT COUNT(DISTINCT batch_id ) from employees
UNION
The UNION operator is used to combine the result-set of two or more SELECT statements.
Each SELECT statement within the UNION must have the same number of columns.
The columns must also have similar data types of the columns in each.
SELECT statement must be in the same order.
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use
UNION ALL.
select name from batch
UNION
select name from employees
SQL – SELECT/INSERT INTO Statement.
The INSERT INTO using SELECT statement is most often used to create backup copies of tables
or for archiving records. (* Statement creates a new table)
Syntax
INSERT into newtable(column_name(s)
SELECT column_name(s) FROM source
If you only want to copy a few fields, you can do so by listing them after the SELECT statement:
INSERT INTO Backup(LastName, FirstName)
Select lname,fname from Friend
SQL –INSERT INTO
You can also add a WHERE clause. The following example creates a “Friend_backup" table with
two columns (FirstName and LastName) by extracting the persons who lives in “NY" from the
“Friend" table:
INSERT INTO Friend_Backup
SELECT LastName,Firstname FROM Friend
WHERE City=‘NY’
Selecting data from more than one table is also possible. The following example creates a new
table “FriendInfo_GiftReg_backup" that contains data from the two tables FriendInfo and
GiftRegistry:
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.
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.
VIEWs
Using Views
A view could be used from inside a query, a stored procedure, or from inside another view. By
adding functions, joins, etc., to a view, it allows you to present exactly the data you want, to
the user.
Cannot use:
….WHERE Price = NULL
Must use
….WHERE Price IS NULL
BookID Price
3 NULL
Another anomaly with nulls is that if you try in a WHERE block:
..WHERE AColumn = NULL
it will not work as expected, you will not get any output even if there are nulls in the
column
AColumn. To correctly find nulls you should use this expression:
..WHERE AColumn IS NULL
.
Thank You!