SQL Reminder
SQL Reminder
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:
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.
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:
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
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
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.
• 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.
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 6
3. To change the data type of an exisitng column:
D. Drop statement
Drop table statement is used to remove a table from a database
C. Insert Statement
To insert a row into a table, an SQL programmer needs to specify attributes’ values of the
table.
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
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.
Note: With the LIKE operator, two patterns (% and _ ) are used:
% allows you to match any string of any length (including zero length)
Operator Description
= Equal
> Greaterthan
< Lessthan
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’.
AND movie.movie_id=video.movie_id
SQL Alias:
Page 12
Aliases are useful with JOINs and aggregates: SUM, COUNT, etc.
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.
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:
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.
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?
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:
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
Page 15
SQL data types: Numerical type
Page 16
SQL data types: Character and string type
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
BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 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.
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
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
Page 20