Course 8 SQL
Course 8 SQL
• SQL is a data definition language (LDD), it allows you to create, modify or delete
tables in a DB.
• SQL is a language for data manipulation (LDM), it allows you to select, insert, adjust
or delete data in a DB table.
• SQL is a query language. It allows you to perform queries on several tables and
calculate results.
2- Manipulation of tables
2.1 creating tables
Tables are created using the CREATE TABLE keyword pair. The simplified table
definition syntax is as follows:
CREATE TABLE Table_name (Column_name1 Data_type1, Column_name2 Data_type2,
..., Column_nameN Data_typeN);
The name given to the table must generally (on most DBMS) start with a letter, and the
maximum number of columns per table is 254.
Data types
1
INFORMATIQUE SECOND YEAR ESMT
For each column that you create, you must specify the data type that the field will
contain. This can be one of the following types:
……………etc
2
INFORMATIQUE SECOND YEAR ESMT
CREATE TABLE Product (BarCode CHAR(8) PRIMARY KEY, Price MONEY, Name
VARCHAR(40), Color VARCHAR(15), Quantity SMALLINT, Weight REAL)
2.2 Deleting tables
To delete a “table_name” table, simply use the following syntax:
DROP TABLE table_name
To delete all data from a table without deleting the table itself. We use the following
syntax:
TRUNCATE TABLE table_name
Note: Access does not support the TRUNCATE statement.
2.3 modifying tables
The ALTER TABLE command in SQL allows you to modify an existing table. It is possible
to add a column, delete one or modify an existing column (for example to change only
the type)
Basic syntax:
Generally speaking, the command is used as follows:
ALTER TABLE table_name instruction
The keyword “instruction” here is used to designate an additional command depending
on the action you wish to perform: add, delete or modify a column.
Add a column
Adding a column to a table is relatively simple and can be done using a query that looks
like this:
ALTER TABLE name_table
ADD COLUMN name_column Data_type
Example :
To add the “volume” field to the “product” table of the previous example we write:
ALTER TABLE Product ADD COLUMN Volume REAL
And to add the manufacturing date, we write:
ALTER TABLE Product ADD COLUMN dateFab TIMESTAMP
3
INFORMATIQUE SECOND YEAR ESMT
Delete a column
A syntax also allows you to delete a column for a table:
ALTER TABLE nom_table
DROP COLUMN nom_colonne
Edit a column
To modify a column, such as changing the type of a column or changing the maximum
size of the column:
ALTER TABLE table_name
ALTER COLUMN column_name new_data_type
Note : If you want to rename a field in SQL, you must delete the field, then recreate it (i.e.
use DROP COLUMN then ADD COLUMN).
Example: To Change the Quantity type to « byte » (between 0 and 255) we write:
ALTER TABLE Product
ALTER COLUMN Quantity Byte
4
INFORMATIQUE SECOND YEAR ESMT