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

SQL Reminder

sql

Uploaded by

azizkhezam9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

SQL Reminder

sql

Uploaded by

azizkhezam9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

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

▪ Data Administration: Data Control Language (DCL) includes commands such as


GRANT and REVOKE which mainly deals with the rights, permissions and other
controls of the database system.
DENY - used to explicitly prevent a user from receiving a particular
permission
GRANT - allows specified users to perform specified tasks
REVOKE - cancels previously granted or denied permissions

▪ Transaction Administration: Transaction Control Language (TCL) deals with


the transaction within the database. A transaction symbolizes a unit of work performed
within a database management system (or similar system) against a database, and
treated in a coherent and reliable way independent of other transactions.
A transaction generally represents any change in a database.

Page 3
If you use a SET TRANSACTION statement, then it must be the first statement in
your transaction. However, a transaction need not have
a SETTRANSACTION statement
COMMIT– commits a Transaction.
ROLLBACK– rollbacks a transaction in case of any error occurs.
SAVEPOINT–sets a savepoint within a transaction.
SET TRANSACTION–specifies characteristics for the transaction.

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.

Indexes are used to retrieve data from the database very fast. The users cannot see the
indexes; they are just used to speed up searches/queries.

Note:

Updating a table with indexes takes more time than updating a table without (because the
indexes also need an update). So, only create indexes on columns that will be frequently
searched against.

Page 4
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…

CREATE TABLE movie (


movie_id int(11) NOT NULL ,

Page 5 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

2. To remove an exisitng column:

ALTER TABLE table_name DROP COLUMN column_name

Page 6
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.

C. 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 7
D. 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.

Page 8
UPDATE movie

SET length=120

WHERE movie_id=123

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 SQL’s where clause, and the projection
operation is specified by SQL’s 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!

Page 9
a)
SELECT title, genre FROM movie

b) SELECT DISTINCT genre FROM movie

2. Selection operations
The selection operation is included in SQL’s 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.

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

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

Page 11
IN To specify multiple possible values for a column

3. join operations
Thus far, we have only been getting data from one table at a time. However in most real world
SQL 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 SQL 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

SQL Alias:

 An Alias is a shorthand for a table or column name.

 Aliases reduce the amount of typing required to enter a query.

 Aliases are often used to make column names more readable.

 Complex queries with aliases are generally easier to read.

Page 12
 Aliases are useful with JOINs and aggregates: SUM, COUNT, etc.

 An Alias only exists for the duration of the query.

SELECT column-name AS alias-name


FROM table-name alias-name
WHERE condition

4. Order By clause
The ORDER BY clause orders or sorts the result of a query according to the values in one or
more specific columns. More than one column can be ordered one within another. It depends

on the user that, whether to order them in ascending or descending order. The default order is
ascending.

The SQL ORDER BY clause is used with the SQL SELECT statement.

Note: SQL ORDER BY clause always comes at the end of a SELECT statement.

SELECT * FROM movie


WHERE genre LIKE '%comedy' AND length>90
ORDER BY title, genre

Ordering is ascending, unless you specify the DESC keyword.

SELECT * FROM movie


WHERE genre LIKE '%comedy' AND length>90
5. Grouping
ORDER BYoperation
title DESC
The GROUP BY Statement in SQL is used to arrange identical data into groups with the help
of some functions. i.e if a particular column has same values in different rows then it will
arrange these rows in a group. Two types exist:

a. Group By single column: Group By single column means, to place all the rows with
same value of only that particular column in one group.

Page 13
b. Group By multiple columns: This means to place all the rows with same values of both
the columns column1 and column2 in one group

Important Points:

 GROUP BY clause is used with the SELECT statement.

 In the query, GROUP BY clause is placed after the WHERE clause.

 In the query, GROUP BY clause is placed before ORDER BY clause if used any.

Example:

Display total number video by each movie separately with the acquired date between
11/03/2010 and 08/10/2013.

SELECT movie_id, COUNT (video_id) AS ‘Number of videos’


FROM video, movie
WHERE movie. movie_id = video. movie_id
AND (date_acquired BETWEEN 11-03-2010 AND 08-10-2013)
GROUP BY movie_id

6. Having clause
We know that WHERE clause is used to place conditions on columns but what if we want to
place conditions on groups?

This is where HAVING clause comes into use.

We can use HAVING clause to place conditions to decide which group will be the part of
final result-set. Also we cannot use the aggregate functions like SUM(), COUNT() etc. with
WHERE clause. So we have to use HAVING clause if we want to use any of these functions
in the conditions

Example:

Display the list of movies having at least 3 videos

Page 14
SELECT movie_id, COUNT (video_id) AS ‘number of videos’
FROM movie, video
WHERE movie. movie_id = video. movie_id
GROUP BY movie_id
Having COUNT (video_id) >= 3

SQL Aggreagte functions

Page 15
SQL data types: Numerical type

Page 16
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

Page 17
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

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 18
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'

Page 19
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 20

You might also like