Chapter 5 SQL PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

SQL Tutorial

I. Reminders
What is table?

The data in RDBMS is stored in database objects called tables. The table is a collection of
related data entries and it consists of columns and rows.

Remember, a table is the most common and simplest form of data storage in a relational
database. Following is the example of a CUSTOMERS table:

ID NAME AGE ADDRESS SALARY

1 TOUNSI 32 Tunis 20000

2 Kilani 25 Beja 1500

3 Sayari 60 Bizerte 56532

4 Chaibi 45 Nabeul 600

5 Abid 30 Sousse 10000

6 Mahdoui 22 Kef 45000

What is field?

Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS
table consist of ID, NAME, AGE, ADDRESS and SALARY.

A field is a column in a table that is designed to maintain specific information about every
record in the table.

What is record or row? A record is a horizontal entity in a table.

A record, also called a row of data, is each individual entry that exists in a table. For example
there are 6 records in the above CUSTOMERS table. Following is a single row of data or
record in the CUSTOMERS table:

1 TOUNSI 32 Tunis 20000

Page 1
What is column?

A column is a vertical entity in a table that contains all information associated with a specific
field in a table. For example, a column in the CUSTOMERS table is ADDRESS, which
represents location description and would consist of the following:

ADDRESS

Tunis

Beja

Bizerte

Nabeul

Sousse

Kef

What is NULL value?

A NULL value in a table is a value in a field that appears to be blank, which means a field
with a NULL value is a field with no value.

It is very important to understand that a NULL value is different than a zero value or a field
that contains spaces. A field with a NULL value is one that has been left blank during record
creation.

II. SQL
Structured Query Language (SQL) is a standard language for describing database definition,
manipulation, and applications.
The language includes statements that specify and modify database schemas as well as
statements that manipulate database content:
Data Definition Language (DDL) of SQL supports the definition of the physical
structures of databases. The create table statement specifies a table schema; it describes
the attributes, their types, default values, and constraints. It can also be used to define
key and foreign key constraints.

Page 2
The most used DDL statements in SQL are:
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies an existing database
CREATE TABLE - creates a new table
ALTER TABLE - modifies an existing table
DROP TABLE - deletes an existing table

Data Manipulation Language (DML) of SQL supports queries that extract data from
databases (select statements), add new rows to tables (insert statements), and modify
attribute values of existing rows (update statements).
The different commands defined by the DML part of SQL are:
SELECT - extracts data from an existing table
UPDATE - updates data in an existing table
DELETE - deletes data from an existing table
INSERT INTO - inserts new data into the table
SQL Constraints
Constraints are the rules enforced on data columns or tables. They are used to limit the type of
data that can go into a table. They ensures the accuracy and reliability of the data in the
database.

Constraints can be at a column level or at a table level. Column level constraints are applied
only to one column whereas table level constraints are applied to the whole table.

Here some commonly used constraints available in SQL:

NOT NULL Constraint: Ensures that a column cannot have NULL value.
DEFAULT Constraint: Provides a default value for a column when none is specified.
UNIQUE Constraint: Ensures that all values in a column are different.
PRIMARY Key: Unique identifier of each row/record in a database table.
FOREIGN Key: Unique identifier of a row/record in any another database table.
CHECK Constraint: The CHECK constraint ensures that all values in a column
satisfy certain conditions.
INDEX: Used to create and retrieve data from the database very quickly.

Page 3
II. DDL statements
DDL allows changes on database tables like creation, delete or modification, etc.

A. Create and Drop database Statements


To create a new database, we use:

CREATE DATABASE database_name

To remove an existing database, we use:

DROP DATABASE database_name

B. Creating Tables and Defining Attributes


A create table statement specifies a table name and a list of attributes for a new table. The
statement must specify a name and type for each attribute.

The SQL data types are extensive and somewhat interchangeable. For instance, a varchar type
has a varying number of characters, up to some limit, and a char type has a specific fixed
number of characters.

SQL supports a specific collection of attribute types, listed in pages 9, 10 and 11, and has
several names for some types:

Numeric attribute types include integers (such as int, smallint, and long), floating point
types of various lengths (for example, float and double), and formatted numbers (such
as decimal)

Date types include a date and a time (datetime), a date with no time (date), and a time
with no date (time)

Character and string types include varchar type having a varying number of characters,
up to some limit, and a char type that has a specific fixed number of characters

Page 4
CREATE TABLE movie (
movie_id int(11) NOT NULL ,
title varchar(30) DEFAULT NULL,
genre varchar(30) DEFAULT NULL,
length int(11) DEFAULT NULL,

PRIMARY KEY (movie_id)


)

Attributes have characteristics other than simply a name and a type. To declare a primary key
(that is, a field that uniquely identifies a row), we use the primary key constraint and to
specify a foreign key (a representation of a relationship type as a reference to the primary key
of another table), we create foreign key with a references clause.

CREATE TABLE video (

video_id int(11) NOT NULL,

date_acquired date DEFAULT NULL,

movie_id int(11) DEFAULT NULL,

PRIMARY KEY (video_id),

FOREIGN KEY (movie_id) REFERENCES movie (movie_id)

C. Adding, Removing, and Modifying Attributes


The alter table statement can also be used to add, modify, and remove attributes.

1. To add an extra column to an existing table:

ALTER TABLE table_name ADD column_name datatype

Page 5
2. To remove an exisitng column:

ALTER TABLE table_name DROP COLUMN column_name

3. To change the data type of an exisitng column:

ALTER TABLE table_name MODIFY column_name datatype

D. Drop statement
Drop table statement is used to remove a table from a database

DROP TABLE table _name

III. DML statements


DML defines the instructions to manage the table records.

A. Insert Statement
To insert a row into a table, an SQL programmer needs to specify attributes values of the
table.

INSERT INTO movie (movie_id, title, genre, length)

VALUES (123,'Annie Hall', 'Romantic Comedy',110)

These tables shows movies and videos recorded

Page 6
B. Update statement
An update statement in SQL lets us change one or more rows of an existing table. An update
statement has three clauses:

The update clause specifies which table to update.

The set clause contains one or more assignments that specify which attributes to
change and what their new values are.

The where clause specifies which rows to change.

UPDATE movie

SET length=120

WHERE movie_id=123

Page 7
C. Delete Statement
To delete rows in a table, we must write a delete statement that specifies the table and a
selection condition. Each row of the table that satisfies the condition is deleted when the
statement is executed. For instance, the following statement deletes every row of the Movie
table where length is less than 50.
DELETE FROM movie

WHERE length<30

D. Select statement
SQL select statements let you extract information from a relational database. A single such
statement can incorporate selection, projection and join operations. As with all relational
queries, the select query produces a table as its result. The basic select statement includes
three clauses:

The select clause specifies the attributes that go in the results table.

The from clause specifies the source tables that the database will access in order to
execute the query.

The where clause specifies the selection conditions, including the join condition.
The selection operation is included in SQLs where clause, and the projection
operation is specified by SQLs select clause.

1. Projection operations
Statements (a) and (b) represent a projection operation. The select clause lists a sequence of
the attributes that will appear in the results table. Note, however, that statement (b) uses the
keyword distinct.
Note: The asterisk (*) is a quick way of selecting all columns!

a)
SELECT title, genre FROM movie

Page 8
b) SELECT DISTINCT genre FROM movie

2. Selection operations
The selection operation is included in SQLs where clause to filter records. It is used to
extract only the records that fulfill a specified condition.

SQL uses single quotes around text values. However, numeric values should not be enclosed
in quotes.

The AND & OR operators are used to filter records based on more than one condition.

The AND operator displays a record if both the first condition and the second
condition are true.

The OR operator displays a record if either the first condition or the second
condition is true.

The following query selects the movies which their genre ends with the word comedy and
their length is superior to 90.

Page 9
SELECT * FROM movie

WHERE genre LIKE '%comedy' AND length>90

Note: With the LIKE operator, two patterns (% and _ ) are used:

% allows you to match any string of any length (including zero length)

_ allows you to match on a single character

With the WHERE clause, the following operators can be used:

Operator Description

= Equal

<> Not equal

> Greaterthan

< Lessthan

>= Greaterthan or equal

<= Lessthan or equal

BETWEEN Between an inclusive range

LIKE Search for a pattern

NOT LIKE

IN To specify multiple possible values for a column

Page 10
3. join operations
Thus far, we have only been getting data from one table at a time. However in most real world
MySQL usage, you will often need to get data from multiple tables in a single query.

You can use multiple tables in your single SQL query. The act of joining in MySQL refers to
smashing two or more tables into a single table.

This statement displays videos informations (video_id and date_acquired) of the movie
Sleepless Night.

SELECT video_id AS 'video identifier', date_acquired AS 'date of purchase' FROM


movie , video

WHERE title=Sleepless Night'

AND movie.movie_id=video.movie_id

Page 11
SQL data types: Numerical type

Page 12
SQL data types: Character and string type

Data type Description

CHAR(size) Holds a fixed length string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to
255 characters

VARCHAR(size Holds a variable length string (can contain letters, numbers, and special
) characters). The maximum size is specified in parenthesis. Can store up
to 255 characters. Note: If you put a greater value than 255 it will be
converted to a TEXT type

TINYTEXT Holds a string with a maximum length of 255 characters

TEXT Holds a string with a maximum length of 65,535 characters

BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data

MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters

MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of


data

LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters

LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes


of data

Page 13
ENUM(x,y,z,etc Let you enter a list of possible values. You can list up to 65535 values
.) in an ENUM list. If a value is inserted that is not in the list, a blank
value will be inserted.

Note: The values are sorted in the order you enter them.

You enter the possible values in this format: ENUM('X','Y','Z')

SET Similar to ENUM except that SET may contain up to 64 list items and
can store more than one choice

Page 14
SQL data types: Date/Time type

Data type Description

DATE() A date. Format: YYYY-MM-DD

Note: The supported range is from '1000-01-01' to '9999-12-31'

DATETIME() *A date and time combination. Format: YYYY-MM-DD HH:MM:SS

Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31


23:59:59'

TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number of seconds


since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-
DD HH:MM:SS

Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-


09 03:14:07' UTC

TIME() A time. Format: HH:MM:SS

Note: The supported range is from '-838:59:59' to '838:59:59'

YEAR() A year in two-digit or four-digit format.

Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in


two-digit format: 70 to 69, representing years from 1970 to 2069

Page 15
SQL Aggreagte functions

Page 16

You might also like