Advanced Database DDL

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 49

The FIRST() Function

The FIRST() function returns the first value of the selected column.

SQL FIRST() Syntax

SELECT FIRST(column_name) FROM table_name

SQL FIRST() 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.


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.
SELECT LAST(column_name) FROM table_name
SQL LAST() Example
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

SELECT LAST(OrderPrice) AS LastOrderPrice FROM Orders

LastOrderPrice
100

SQL Concatenate

Sometimes it is necessary to combine together (concatenate) the


results from several different fields.

The syntax for CONCAT() is as follows:

CONCAT(str1, str2, str3, ...):


Concatenate str1, str2, str3, and any
other strings together.
SELECT CONCAT(region_name, store_name) FROM Geography
WHERE store_name = 'Boston';

Result:

'EastBoston'
The HAVING Clause
The HAVING clause was added to SQL because the WHERE
keyword could not be used with aggregate functions.

SQL HAVING Syntax


SELECT column_name,
aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator
value
SQL HAVING 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 if any of the customers have a total order of less than
2000.
We use the following SQL statement:
SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000
The result-set will look like this:
Customer SUM(OrderPrice)
Nilsen 1700
Now we want to find if the customers "Hansen" or "Jensen" have a total
order of more than 1500.
We add an ordinary WHERE clause to the SQL statement:
SELECT Customer,SUM(OrderPrice) FROM Orders
WHERE Customer='Hansen' OR Customer='Jensen'
GROUP BY Customer
HAVING SUM(OrderPrice)>1500

The result-set will look like this:

Customer SUM(OrderPrice)
Hansen 2000
Jensen 2000
The GROUP BY Statement

The GROUP BY statement is used in conjunction with the aggregate


functions to group the result-set by one or more columns.

SQL GROUP BY Syntax


SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
SQL GROUP BY 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 total sum (total order) of each customer.
We will have to use the GROUP BY statement to group the
customers.
We use the
SELECT following SQL statement: FROM Orders
Customer,SUM(OrderPrice)
GROUP BY Customer Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000
The TOP Clause
The TOP clause is used to specify the number of records to return.
The TOP clause can be very useful on large tables with thousands of
records. Returning a large number of records can impact on
performance.
Note: Not all database systems support the TOP clause.

MySQL Syntax My Access Syntax


SELECT column_name(s) SQL TOP Example
FROM table_name SELECT TOP 2 * FROM Persons
LIMIT number
The result-set will look like this:
SELECT *
FROM Persons LastNam FirstNam
LIMIT 5 P_Id Address City
e e
Timoteiv
1 Hansen Ola Sandnes
n 10
Borgvn
2 Svendson Tove Sandnes
23
SQL TOP PERCENT Example
The "Persons" table
FirstNam
P_Id LastName Address City
e
Timoteiv
1 Hansen Ola Sandnes
n 10
Borgvn
2 Svendson Tove Sandnes
23
Stavange
3 Pettersen Kari Storgt 20
r
Vingvn Stavange
4 Nilsen Tom
23 r
Now we want to select only 50% of
the records in the table above.
We use the following SELECT
SELECT TOP 50 PERCENT * FROM Persons statement:
FirstNam
The result-set will look P_Id LastName Address City
e
like this:
Timoteiv
1 Hansen Ola Sandnes
n 10
Borgvn
2 Svendson Tove Sandnes
23
The UCASE() Function
The UCASE() function converts the value of a field to
uppercase.
SQL UCASE() Syntax
SELECT UCASE(column_name) FROM table_name

The LCASE() Function

The LCASE() function converts the value of a field to


lowercase.
SQL LCASE() Syntax
SELECT LCASE(column_name) FROM table_name
MySQL
MySQL ("My Sequel") is a relational database
management system (RDBMS) that runs as a server
providing multi-user access to a number of databases.
A relational database management system
(RDBMS) is a database management system (DBMS)
that is based on the relational model as introduced
by E. F. Codd. Most popular databases currently in
use are based on the relational database model.
a DBMS in which data is stored in tables
and the relationships among the data are
also stored in tables. The data can be
accessed or reassembled in many different
ways without having to change the table
forms.
MySQL was owned and sponsored by a single for-profit firm, the
Swedish company MySQL AB, now owned by Oracle Corporation.
Free-software-open source projects that require a full-featured
database management system often use MySQL. For commercial
use, several paid editions are available, and offer additional
functionality.
Applications which use MySQL databases include: TYPO3,
Joomla, WordPress, phpBB, Drupal and other software built on
the LAMP software stack.
MySQL is also used in many high-profile, large-scale World Wide
Web products, including Wikipedia, Google (though not for
searches), Facebook, and Twitter.

A content management system (CMS) is a system providing a


collection of procedures used to manage work flow in a
collaborative environment.
XAMPP is a free and open source cross-platform web server
solution stack package, consisting mainly of the Apache HTTP Server,
MySQL database, and interpreters for scripts written in the PHP and
Perl programming languages.

XAMPP's name is an acronym for:

* X (to be read as "cross", meaning cross-


platform)(computing methods and concepts that
are implemented and inter-operate on multiple
computer platforms.)
* Apache HTTP Server
* MySQL
* PHP
* Perl
WAMP packages of independently-created programs installed on
computers that use a Microsoft Windows operating system.

WAMP is an acronym formed from the initials of the operating system


Microsoft Windows and the principal components of the package:
Apache, MySQL and one of PHP, Perl or Python.

Apache is a web server. MySQL is an open-source database. PHP is a


scripting language that can manipulate information held in a database and
generate web pages dynamically each time content is requested by a
browser.
 SQL can be divided into two parts: The Data Manipulation
Language (DML) and the Data Definition 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.
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 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 USE keyword is used to select a


database in MySQL USE Database_Name;
TEE Function
By using the --tee option when you invoke mysql, you can log statements and
their output. All the data displayed on the screen is appended into a given
file. This can be very useful for debugging purposes also. mysql flushes
results to the file after each statement, just before it prints its next prompt.

You can enable this feature interactively with the tee command. Without a
parameter, the previous file is used. The tee file can be disabled with the
notee command. Executing tee again re-enables logging.

tee [file_name], \T [file_name]


SQL CREATE TABLE Statement
The CREATE TABLE statement is used to create a table in a
database.
SQL CREATE TABLE Syntax
The data type specifies what
type of data the column can
CREATE TABLE table_name hold.
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
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, and City columns are of type varchar with a
maximum length of 255 characters.
Constraints are used to limit the type of
SQL NOT NULL Constraint data that can go into a table.

The NOT NULL constraint enforces a column to NOT accept NULL


values.
The NOT NULL constraint enforces a field to always contain a value.
This means that you cannot insert a new record, or update a record
without adding a value to this field.
The following SQL enforces the "P_Id" column and the
"LastName" column to not accept NULL values:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
SQL AUTO INCREMENT Field

Auto-increment allows a unique number to be generated when a


new record is inserted into a table.

Syntax for MySQL

CREATE TABLE Persons


(
P_Id int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)

MySQL uses the AUTO_INCREMENT keyword to perform an auto-


increment feature.
By default, the starting value for AUTO_INCREMENT is 1, and it will
increment by 1 for each new record.
SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a


database table.
Primary keys must contain unique values.
A primary key column cannot contain NULL values.
SQL PRIMARY KEY Constraint on CREATE TABLE
The following SQL creates a PRIMARY KEY on the "P_Id" column
when the "Persons" table is created:

MySQL: MS Access:
CREATE TABLE Persons
CREATE TABLE Persons
(
(
P_Id int NOT NULL,
P_Id int NOT NULL PRIMARY
LastName varchar(255) NOT NULL,
KEY,
FirstName varchar(255),
LastName varchar(255) NOT
Address varchar(255),
NULL,
City varchar(255),
FirstName varchar(255),
PRIMARY KEY (P_Id)
Address varchar(255),
)
City varchar(255)
)
The DROP TABLE Statement
The DROP TABLE statement is used to delete a table.

DROP TABLE table_name

The DROP DATABASE Statement

The DROP DATABASE statement is used to delete a database.

DROP DATABASE database_name

The TRUNCATE TABLE Statement

What if we only want to delete the data inside the table, and not the table
itself?
Then, use the TRUNCATE TABLE statement:
TRUNCATE TABLE table_name
The ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in
an existing table.

SQL ALTER TABLE Syntax


To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype

To delete a column in a table, use the following syntax (notice that some
database systems don't allow deleting a column):

ALTER TABLE table_name


DROP COLUMN column_name
To change the data type of a column in a table, use the following
syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype

SQL ALTER TABLE Example


Look at the "Persons" table:

P_Id LastName FirstName Address City


Timoteivn
1 Hansen Ola Sandnes
10
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Now we want to add a column named
"DateOfBirth" in the "Persons" table.

We use the following SQL statement:


ALTER TABLE Persons
ADD DateOfBirth date
Notice that the new column, "DateOfBirth", is of type date and is going
to hold a date. The data type specifies what type of data the column
can hold.
The "Persons" table will now like this:

DateOfBirt
P_Id LastName FirstName Address City
h
Timoteivn
1 Hansen Ola Sandnes
10
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Change Data Type Example

Now we want to change the data type of the column named "DateOfBirth"
in the "Persons" table.
ALTER TABLE Persons
ALTER COLUMN DateOfBirth year

Notice that the "DateOfBirth" column is now of type year and is going to
hold a year in a two-digit or four-digit format.
DROP COLUMN Example
Next, we want to delete the column named "DateOfBirth" in the "Persons"
table.
ALTER TABLE Persons
DROP COLUMN DateOfBirth

The "Persons" table will now 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 ALTER TABLE - Renaming a table

To rename a table, the SQL ALTER TABLE syntax is:

ALTER TABLE table_name


RENAME TO new_table_name;

To add multiple columns to an existing table, the SQL ALTER


TABLE syntax is:

ALTER TABLE table_name


ADD (column_1 data type,
column_2 data type,
...
column_n data type);
To modify multiple columns in an existing table, the SQL ALTER
TABLE syntax is:

ALTER TABLE table_name


MODIFY (column_1 data_type,
column_2 data_type,
...
column_n data_typ);

Altering Column Order

ALTER TABLE tablename ADD columnname datatype AFTER


columnname

ALTER TABLE table_name MODIFY COLUMN columnname datatype


AFTER column_name;
Renaming the Column Name

Syntax:

ALTER TABLE table_name Change


current_column new_column datatype;
DESCRIBE provides information about the columns in a
table.
SHOW TABLES lists the non-TEMPORARY tables in a given
database.
SHOW TABLE STATUS works likes SHOW TABLES, but provides a
lot of information about each non-TEMPORARY table.
SHOW DATABASES lists the databases on the MySQL server
host.

SHOW SCHEMAS is a synonym for SHOW DATABASES.


The CREATE VIEW statement creates a new view, or replaces an
existing one if the OR REPLACE clause is given
The select_statement is a SELECT statement that provides the
definition of the view.
(When you select from the view, you select in effect using the SELECT
statement.)
The view definition is “frozen” at creation time, so changes to the
underlying tables afterward do not affect the view definition. For
example, if a view is defined as SELECT * on a table, new columns
added to the table later do not become part of the view.
SYNTAX
SQL Updating a View
CREATE VIEW view_name
CREATE OR REPLACE
AS
VIEW view_name AS
SELECT column_name(s)
SELECT column_name(s)
FROM table_name
FROM table_name
WHERE condition
WHERE condition

SELECT * from
View_Name DROP VIEW view_name
A STORED PROCEDURE is a set of SQL statements that can be stored in the
server.
Once this has been done, clients don't need to keep reissuing the individual
statements but can refer to the stored procedure instead.
Stored routines can provide improved performance because less information
needs to be sent between the server and the client. This also helps in
decreasing the traffic in the networks and also reduces the CPU load.

A stored procedure is a method to encapsulate repetitive tasks.

The Delimiter is the character or string of characters that you’ll use to tell
the mySQL client that you’ve finished typing in an SQL statement.

BEGIN and END statements are used to delimit the stored procedure body

Each statement within statement_list must be terminated by a semicolon (;)


statement delimiter
SYNTAX of STORED PROCEDURE

DELIMITER $$

CREATE PROCEDURE procedure_name ()


BEGIN
Select table_column From table_name;
END $$

DELIMITER ;

Checks if the procedure already exist


DELIMITER $$
DROP PROCEDURE IF EXISTS procedure_name $$
CREATE PROCEDURE procedure_name ()
BEGIN
Select table_column From table_name;
END $$

DELIMITER ;
CALL procedure_name(); - executes the just-created stored
procedure and displays the returned result.

Dropping Stored Procedures

After they are created, stored procedures remain on the server, ready for use,
until dropped. The drop command removes the stored procedure from the
server.
To remove the stored procedure we just created, use the following statement:

DROP PROCEDURE procedure_name;

This removes the just-created stored procedure. Notice that the trailing () is not
used; here just the stored procedure name is specified.

Drop Only If It Exists DROP PROCEDURE will throw an error if the named
procedure does not actually exist. To delete a procedure if it exists (and not throw
an error if it does not), use DROP PROCEDURE IF EXISTS.
SHOW CREATE PROCEDURE procedure_name;
To display the CREATE statement used to create a stored procedure, use the
SHOW CREATE PROCEDURE statement:

ALTER PROCEDURE SYNTAX


This statement can be used to change the characteristics of a stored procedure.
More than one change may be specified in an ALTER PROCEDURE statement.
However, you cannot change the parameters or body of a stored procedure using
this statement; to make such changes, you must drop and re-create the procedure
using DROP PROCEDURE and CREATE PROCEDURE.
Loading Data into a Table

After creating your table, you need to populate it.

The LOAD DATA INFILE statement reads rows from a text file into a table
at a very high speed.
Because you are beginning with an empty table, an easy way to
populate it is to create a text file containing a row

LOAD DATA INFILE SYNTAX

LOAD DATA INFILE '/path/sample.txt' INTO TABLE


table_name;
If you created the file on Windows with an editor that uses \r\n as a line
terminator, you should use this statement instead:
LOAD DATA INFILE '/path/sample.txt' INTO TABLE table_name LINES
TERMINATED BY '\r\n';
You can specify the column value separator and end of line marker
explicitly in the LOAD DATA statement if you wish, but the defaults are tab
and linefeed.
LOAD DATA INFILE interprets all fields in the file as having the same
character set, regardless of the data types of the columns into which field
values are loaded.
LINES TERMINATED BY 'character': This option defines the character
intended to signal the conclusion of a line, and thus the end of a table row.
Although it could conceivably be any thing, this character is most often the
newline (\n) character. In many Windows based files, the newline character
is often represented as \r\n.
FIELDS TERMINATED BY 'character': This option signals how fields will
be terminated. Therefore, TERMINATED BY ',' means that each field will end
with a comma, like so:123,4567,2008-05-19 01:30:45,11.75,9.00,15.75

OPTIONALLY ENCLOSED BY 'character': This option signals that each


field will be enclosed by a particular character. This does not eliminate the
need for a terminating character. Revising the previous example, using the
option FIELDS TERMINATED BY ','ENCLOSED BY '"' implies that each field
is enclosed by a pair of double quotes and delimited by a comma, like
so:"123","4567","2008-05-19 01:30:45","11.75","9.00","15.75"
SYNTAX
LOAD DATA INFILE ‘path/sample.txt‘ INTO TABLE table_name FIELDS
TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED
BY '\r\n'
Load Data Infile using 'csv'
LOAD DATA INFILE ‘path/sample.csv‘ INTO TABLE table_name FIELDS
TERMINATED BY ',' LINES TERMINATED BY '\r\n'
SELECT ... INTO OUTFILE

SELECT ... INTO OUTFILE writes the selected rows to a


file.
Column and line terminators can be specified to produce a specific output
format.
The SELECT ... INTO OUTFILE statement is intended primarily to let you
very quickly dump a table to a text file on the server machine.

SELECT column_name FROM table_name INTO OUTFILE


‘/path/sample.txt' FIELDS TERMINATED BY ',' LINES
TERMINATED BY '\r\n'
A trigger is a named database object that is associated with a table and that
is activated when a particular event occurs for the table.

For example, the following statements create a table and an INSERT trigger.
The trigger sums the values inserted into one of the table's columns:
mysql> CREATE TABLE account (acct_num INT, amount DECIMAL(50));

mysql> CREATE TRIGGER ins_sum BEFORE INSERT ON account


-> FOR EACH ROW SET @sum = @sum + NEW.amount;

mysql> SET @sum = 0;

mysql> INSERT INTO account VALUES(137,14.98),(141,1937.50),(97,-100.00);

mysql> SELECT @sum AS 'Total amount inserted';

+-----------------------+
| Total amount inserted |
+-----------------------+
| 1852.48 |
+-----------------------+
trigger_time is the trigger action time. It can be BEFORE or AFTER to
indicate that the trigger activates before or after the statement that
activated it.

trigger_event indicates the kind of statement that activates the trigger.


The trigger_event can be one of the following:

INSERT: The trigger is activated whenever a new row is


inserted into the table
UPDATE: The trigger is activated whenever a row is
modified;

DELETE: The trigger is activated whenever a row is


deleted from the table. However, a TRUNCATE
statement on the table does not invoke this trigger.

The statement following FOR EACH ROW defines the statement to


execute each time the trigger activates, which occurs once for each
row affected by the triggering statement
The keyword BEFORE indicates the trigger action time. In this case, the
trigger should activate before each row inserted into the table. The other
allowable keyword here is AFTER.

Example: D:\Tutorials\MySQL 5.0-en-saido.chm

DROP TRIGGER Syntax


DROP TRIGGER [schema_name.]trigger_name

This statement drops a trigger. The schema (database) name is optional. If


the schema is omitted, the trigger is dropped from the default schema.
Copying Data Between Tables
INSERT INTO SELECT

INSERT INTO SELECT - The method of copying data is to insert data


using the INSERT command but instead of providing a VALUES clause
containing the information for the new row, a SELECT statement is used
as a subquery. The data generated from the select statement is added
into the table defined in the INSERT. Any existing rows in the target
table are unaffected.

INSERT INTO Table2


SELECT * FROM Table1

The above example will copy all of the information from Table1 into
Table2.
mysqldump — A Database Backup Program
MySQL provides several techniques to keep the backup of our important
data.

The mysqldump client is a backup program originally written by Igor


Romanenko. The mysqldump is console based executable utility. It can be
used to dump a database or a collection of databases for backup or transfer to
another SQL server (not necessarily a MySQL server). The dump typically
contains SQL statements to create the table, populate it, or both. However,
mysqldump can also be used to generate files in CSV, other delimited text, or
XML format.
There are following ways to invoke mysqldump. Use the following command
to take backups:
Steps To Save Data using the
MySQL MYSQLDUMP Command

1.Open the Command Line utility by Clicking on 'Start' and 'Run' and typing
'CMD' and pressing 'ok'
2.Type 'mysqldump'
3.Type –h and your hostname '-h localhost'
4.Type -u and your username '-u root'
5.Type -p and your password '-p password'
6.Type your database name 'mydatabase'
7.Type a greater-than sign to put the results in to a file '>'
8.Type the name of the file to put the results in 'mybackupfile.sql'
Import SQL dump into MySQL

You might also like