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

2nd - SQL Helpbook

The document discusses various SQL statements used for data definition, data manipulation, and querying a database. It provides examples of using CREATE TABLE to define a table structure, INSERT statements to add data to tables, SELECT statements to query and filter data with WHERE and LIKE clauses, and JOINs to combine data from multiple tables. Aggregate functions like COUNT, MIN, MAX and scalar functions like UPPER, LOWER are also covered.

Uploaded by

Meenal Gupta
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)
80 views

2nd - SQL Helpbook

The document discusses various SQL statements used for data definition, data manipulation, and querying a database. It provides examples of using CREATE TABLE to define a table structure, INSERT statements to add data to tables, SELECT statements to query and filter data with WHERE and LIKE clauses, and JOINs to combine data from multiple tables. Aggregate functions like COUNT, MIN, MAX and scalar functions like UPPER, LOWER are also covered.

Uploaded by

Meenal Gupta
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/ 31

SQL Data Definition Language (DDL)

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.

The most important DDL statements in SQL are:

 CREATE TABLE - creates a new database table


 ALTER TABLE - alters (changes) a database table
 DROP TABLE - deletes a database table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index
SQL Data Manipulation Language (DML)

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:

 SELECT - extracts data from a database table


 UPDATE - updates data in a database table
 DELETE - deletes data from a database table
 INSERT INTO - inserts new data into a database table
Create Command
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)

create table batch


(
batch_no int PRIMARY KEY,
name char(10),
startdate date,
email char(10),
subject char(10)
);

create table employees


(
name char(20),
dept char(20) NOT NULL,
emp_id int PRIMARY KEY,
city char(20),
batch_id int,
Constraint fk_key foreign key(batch_id) REFERENCES batch(batch_no)
);
Insert
 Insert into table(col1,col 2,…col n)
values(val1,val2,…,val n)

 insert into batch


values(5,‘B5',‘2005/2/2','[email protected]','BA')

 insert into batch(batch_no,name,startdate,email,subject)


values(8,‘B8',NULL,'[email protected]','QA')

 insert into employees(name,dept,emp_id,city,batch_id)


values('Raj','sales',1001,'San Jose',6)

 insert into batch(batch_no)


values(0010)
Insert into table(col1,col 2,col n)
values(val1,val2,,val n)

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

5 tina 2004/2/2 [email protected] BA

6 BA

7 max 2005/3/5 [email protected] QA

8 richy 2009/3/7 [email protected] QA


Delete rows from a table
 delete from batch where name='tina'
 delete from batch

Update values in a table


 UPDATE batch SET subject = 'BA'
WHERE name= 'ken‘

 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

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


SELECT column_name(s) FROM table_name
WHERE column_name IN (value1,value2,...)

The BETWEEN Operator


The BETWEEN operator selects a range of data between two values. The values can be numbers,
text, or dates.
SELECT column_name(s) FROM
table_name WHERE column_name
BETWEEN value1 AND value2
SQL – GROUP BY and HAVING
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.

The syntax for the GROUP BY function is:


SELECT column1, SUM(column2)
FROM table
GROUP BY column1

*Discuss an example of Company and Revenue per min.


Ebay, 7,000 ..
Yahoo, 14,000 ..
Amazon, 7,000
Ebay, 7,000 ..
Google, 28,000 ..
Half.com, 5,000
SQL – GROUP BY and HAVING
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.

The syntax for the HAVING function is:


SELECT column1, SUM(column2)
FROM table
GROUP BY column1
HAVING SUM(column2) condition value

* Discuss previous example with HAVING SUM(Revenue) > 10,000


 ORDER BY

SELECT * FROM Sweets


ORDER BY Month ASC , Qty DESC
Prod Month Qty
Mars Jan 1.0
Twix Jan 2.0
Lion Jan 3.0
Mars Feb 4.0

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 change type of a column:


 ALTER TABLE table_name
MODIFY column_name datatype

To drop a column:
 ALTER TABLE table_name
DROP COLUMN column_name

EXAMPLES:
 alter table batch
add country char(20)

 alter table batch


modify name varchar(25)

 alter table batch


drop column country
SQL – DDL – DROP Table and Database
• To delete a table (the table structure, attributes, and indexes will also be deleted):
DROP TABLE table_name

• 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

 SQL Aggregate Functions


SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
AVG() - Returns the average value
SELECT AVG(column_name) FROM table_name

FIRST() - Returns the first value


SELECT FIRST(column_name) FROM table_name

LAST() - Returns the last value


SELECT LAST(column_name) FROM table_name

MAX() - Returns the largest value


SELECT MAX(column_name) FROM table_name

MIN() - Returns the smallest value


SELECT MIN(column_name) FROM table_name

SUM() - Returns the sum


SELECT SUM(column_name) FROM table_name
 SQL Scalar functions
SQL scalar functions return a single value, based on the input value.
Useful scalar functions:

upper() - Converts a field to upper case


SELECT upper(column_name) FROM table_name

lower() - Converts a field to lower case


SELECT lower(column_name) FROM table_name

mid() - Extract characters from a text field


SELECT mid(column_name,start[,length]) FROM table_name
[ column_name: Required. The field to extract characters from.
start : Required. Specifies the starting position (starts at 1).
Length :Optional. The number of characters to return. If omitted, the MID() function returns the rest of the text.]
SELECT mid(City,1,4) as SmallCity FROM Persons

length() - Returns the length of a text field


SELECT length(column_name) FROM table_name
SELECT length(Address) as LengthOfAddress FROM Persons

ROUND() - Rounds a numeric field to the number of decimals specified


SELECT ROUND(column_name,decimals) FROM table_name
SELECT ProductName, ROUND(UnitPrice,0) as UnitPrice FROM Persons

NOW() - Returns the current system date and time


SELECT NOW() [FROM table_name]
INDEXES

 CREATE INDEX index_name ON table_name (column_name)

To create an index on the ‘batch’ table on the ‘batch_no’ column


 CREATE INDEX idx_batch
ON batch(batch_no)

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

Make a Backup Copy


The following example makes a backup copy of the “Friends" table:
INSERT INTO Friend_backup
SELECT * FROM Friend

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:

SELECT FriendInfo.Name, GiftRegistry.Product FROM FriendInfo,GiftRegistry


WHERE FriendInfo.Friend_ID = GiftRegistry.Friend_ID
VIEWs
 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.

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.

 We can query the view as follows:


SELECT * FROM view_name
STORED PROCEDURES
 Stored procedure is a segment of code which contains declarative or procedural SQL statements.
 A stored procedure is resided in the catalog of the database server and can be called from
 a trigger
 another stored procedure
 client applications
 A Stored procedure can contains any SQL statement like INSERT, UPDATE and DELETE or any SQL
data definition like CREATE TABLE, ALTER TABLE
 Supports procedure statements such as IF ELSE, WHILE...

CREATE PROCEDURE procedure1 /* name */


(IN parameter1 INTEGER) /* parameters */
BEGIN /* start of block */
DECLARE variable1 CHAR(10); /* variables */
IF parameter1 = 17 THEN /* start of IF */
SET variable1 = 'birds'; /* assignment */
ELSE SET variable1 = 'beasts'; /* assignment */
END IF; /* end of IF */
INSERT INTO table1 VALUES (variable1); /* statement */
END
STORED PROCEDURES
Create a new dummy table
create table T1(var int);

Create a new procedure


create procedure HelloProc2(x int)
Begin
SELECT 'HelloProc Executed';
insert into T1(var) values(x);
End;

Call the procedure with different values


Call HelloProc2(10);
Call HelloProc(20);
Call HelloProc2(30);
TRIGGERS
 A trigger is a special kind of stored procedure that automatically executes when an event occurs in the
database server.
 Triggers execute when a user tries to modify data through a data manipulation language (DML) event.
DML events are INSERT, UPDATE, or DELETE statements on a table or view.

 CREATE TRIGGER {name}


{BEFORE | AFTER} {INSERT | DELETE | UPDATE] }
ON {TABLE name | VIEW name}
FOR EACH ROW
BEGIN
.....
END;

CREATE TRIGGER HelloTrigger BEFORE INSERT ON t1


FOR EACH ROW
BEGIN
INSERT INTO t2 SET b1 = NEW.c1;
END;
Null Values in SQL
 Columns can be defined as accepting nulls
 Nullable columns will have a value of null if:
o  no data is explicitly entered for that column
o  and there is not a default for the column
 A value of null means unknown. This is different :
o  to zero for numeric columns
o  to empty string for text columns
 The most important thing to understand about nulls is that they propagate through
expressions. In the example you can see that:
NULL * 2 = NULL.
The reasoning behind this is that if NULL is unknown then NULL * 2 is still just as
unknown as
NULL by itself.
Nulls – COALESCE
 If you are expecting nulls in expressions and you wish to convert them to a specific value
you can use the COALESCE function:
 COALESCE (expression [,...n])
 Returns the first non null expression among its arguments.
 Although COALESCE can take multiple parameters it is commonly used in the form above
where
the first parameter is the column name where you are expecting a NULL and the second
parameter is the replacement parameter to be used should a NULL be encountered.
 SQL Server has a propriety function ISNULL() which works as a cut down form of
COALESCE,
 for example:
o ISNULL(Price,0)

o ISNULL only takes 2 parameters.

(Works for SQL Server and NOT MYSQL)


Nulls – how to find them

 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!

You might also like