1
SQL
CREATING AND MANAGING TABLES
Edited by :Nouf almunyif
DatabaseObjects
DatabaseObjects
Object Description
Table Basic unit of storage; composed of
rows and columns
View Logically represents subsets of data
from one or more tables
Sequence Numeric value generator
Index Improves the performance of some
queries
Synonym Gives alternative names to the other
objects
All the database objects can be created using CREATE sql statement
Tables
• Creating tables
• The alter statement
• Dropping table
Creating table: Syntax
 Database tables created using (CREATE TABLE
statement)
 The Minimal Syntax is:
 You Specify:
 tablename : The name you chooses for the table
 column : Column name , It can also be up to 30 characters.
 data type : column data type which specifies the type of data to be stored in this column and column
size
 DEFAULT expr: specifies a default value if a value is omitted in the INSERT statement
CREATE TABLE tablename (column data type [DEFAULT expr], …..)
;
Creating table: Naming Rules
 Table names and column names:
 Must begin with a letter
 Must contain only A–Z, a–z, 0–9, _, $, and #
 Must not duplicate the name of another object owned by the same user
 Must not be an Oracle Server reserved word
 Use a descriptive names for table as well the other database objects
 Note: Names are not case sensitive. (For example, EMPLOYEES is treated as the same name
as eMPloyees or eMpLOYEES.)
• The length of a table name depends on the database you’re using:
• Oracle (before v12.2): 30 characters
• Oracle (after v12.2): 128 characters
• SQL Server: 128 characters
• MySQL: 64 characters
• PostgreSQL: 63 characters
Creating table: Data Types
CHAR Datatype : Oracle guarantees that:
•When you insert or update a row in the table, the value for the CHAR column has the
fixed length.
•If you give a shorter value, then the value is blank-padded to the fixed length.
•If a value is too large, Oracle Database returns an error.
VARCHAR2 Datatypes : Oracle guarantees that:
• For each row, Oracle Database stores each value in the column as a variable-length
field
• If the value exceeds the column's maximum length, in which case Oracle Database
returns an error.
Using VARCHAR2 saves on space used by the table.
Creating table: Data Types
The NUMBER datatype stores fixed and floating-point numbers.
For numeric columns, you can specify the column as:
column_name NUMBER
Optionally, you can also specify a
column_name NUMBER (precision, scale)
If a precision is not specified, the column stores values as given. If no
scale is specified, the scale is zero.
You can specify a scale and no precision
column_name NUMBER (*, scale)
In this case, the precision is 38, and the specified scale is
maintained.
For input and output of numbers, the standard Oracle Database default decimal
character is a period, as in the number 1234.56
How Scale Factors Affect Numeric Data Storage
Creating table: Data Types
The DATE datatype stores point-in-time values (dates and times) in a table. The
DATE datatype stores the year (including the century), the month, the day, the
hours, the minutes, and the seconds (after midnight).
For input and output of dates, the standard Oracle date format is DD-MON-YY, as
follows:
'13-NOV-92'
Apex MM/DD/YYYY
Creating table: Data Types (Cont.)
Creating table: DEFAULT
• Specify default value for the column during the INSERT operation  Prevents NULL
values from entering the columns if the row entered inserted without a value for the
column
• For the DEFAULT :
 Literal values, expressions, or SQL functions are legal values
 Another column’s name or pseudocolumn are illegal values
 The DEFAULT value data type must match the column data type
CREATE TABLE …..( …..
employment_status VARCHAR2(20) DEFAULT 'Hired‘,
……)
To add a DEFAULT constraint to a column in a table when you create it in Oracle,
add it to the Create Table statement:
For example, to set a person’s employment status to a default of “Hired”:
CREATE TABLE tablename (
columnname datatype DEFAULT defaultvalue
);
Creating table: Example
CREATE TABLE dept (
deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13),
create_date DATE DEFAULT SYSDATE
);
Table created  Appears when you run the query
DESCRIBE dept ;
Crete a Table
To Confirm the creation
CREATE TABLE AS SELECT (CTAS)
SQL allows you to create a table based on a SELECT statement.
This is a very useful feature of the database. It’s great for
development – if you want to copy an existing table and use it for
testing or development purposes without changing the real table.
Or, if you want a similar table with the same structure.
The syntax for using this command is:
CREATE TABLE table_name AS ( SELECT select_query );
If you want all records to be copied to the new table, you could specify
SELECT * FROM old_table.
14
CREATE TABLEAS SELECT Without Copying Data
• You can also use the CREATE TABLE AS SELECT to copy a table’s
structure without any of the data.
To do this, you just adjust your WHERE clause in the SELECT query to
ensure there are no rows returned. By adding something that is clearly
evaluated to FALSE ,A common example is WHERE 1=0. Or WHERE
1=2. Really, anything involving two numbers that are not equal will
work.So, the SELECT statement will return the column names and data
types, but no data
• The syntax for this would be:
CREATE TABLE table_name AS
(SELECT * FROM old_table WHERE 1=0 );
15
Oracle CREATE TABLE Errors and Exceptions
• These are some of the errors and exceptions that may
appear when you’re creating a table. As a database
developer, you’ll get these kinds of errors all the time!
Exception: ORA-00955: name is already used by an existing object
Reason: You’re attempting to create a table with a name that is already being used.
Resolution: Use a different name for your table, or drop the table with the existing name.
Or, use a different schema for your table if that’s applicable.
Exception: ORA-00904: : invalid identifier
Reason: There are many reasons for this error, but it’s usually a syntax error.
Resolution: Check that you have all of your commas and brackets in the right places in
your statement.
Exception: ORA-00957: duplicate column name
Reason: You have two columns with the same name.
Resolution: Rename one of your columns to make sure it is not a duplicate.
Also, check that your commas and brackets are all in the right places
The ALTER TABLE Statement
The SQL ALTER TABLE statement lets you change a table
that has already been created.
• There are many things you can do with the SQL ALTER
TABLE statement and some that you can’t.
• Add one or more columns to a table
• Change the data type of one or more columns
• Add a constraint to a column
• Drop a column from a table
• Rename a column
• Rename a table
ALTER TABLE table
ADD (column datatype [DEFAULT expr]
[, column datatype]...);
ALTER TABLE table
MODIFY (column datatype [DEFAULT expr]
[, column datatype]...);
ALTER TABLE table
DROP COLUMN column;
The ALTER TABLE Statement: Syntax
• There are many different clauses , Use the ALTER TABLE statement to
add, modify or drop columns.
The syntax of the SQL ALTER TABLE command is:
ALTER TABLE tablename alter_table_clause;
The ALTER TABLE Statement: Syntax
ALTER TABLE dept80
ADD (job_id VARCHAR2(9));
The ALTER TABLE Statement: (Add)
•Note That
• You cannot specify where the new column appear The new
column becomes the last column directly.
• If the table already contains rows when the new column added,
then the new column is initialized to NULL (as in this example) or
default value (if specified) for all the rows
The ALTER TABLE syntax to ADD column is:
ALTER TABLE table_name
ADD [COLUMN] column_name column_definition;
Example:
The ALTER TABLE Statement: (Add)
21
The ALTER TABLE Statement: (Add)
• Example:
ALTER TABLE dept80
ADD (rating NUMBER(2) NOT NULL );
What happens to the existing values in a table, if you add a column with NOT NULL
?
You will get an exception because the existing rows will have a value of NULL.
To avoid this, specify a default value.
ALTER TABLE dept80
ADD (rating NUMBER(2) NOT NULL DEFAULT 99 );
The ALTER TABLE Statement: (DROP)
• Note that:
• You can’t drop a column that’s part of the primary key
• The column may or may not contain data.
• The table must have at least one column remaining in it after it is altered.
• Once a column is dropped, it cannot be recovered
• If there are columns that refer to the dropped columns using constraints, then you need
to specify CASCADE CONSTRAINTS at the end of the statement. If this is not done, you
will get an error. If you don’t have any columns that have these referential constraints,
then you don’t need the CASCADE CONSTRAINTS clause.
The syntax for dropping a column is
:
ALTER TABLE tablename
DROP [COLUMN] column_1 [, column_n] [CASCADE CONSTRAINTS] ;
ALTER TABLE dept80
DROP COLUMN job_id;
 Use the DROP COLUMN clause to drop columns you no longer need from the table.
The ALTER TABLE Statement: (Modify)
• Note That:
• A change to the default value affects only subsequent insertions to the table
• You can decrease the width of a column only if the column contains only null values or
if the table has no rows.
• You can change the data type only if the column contains null values.
ALTER TABLE tablename
MODIFY column_name data_type;
The syntax for modifying a column is
:
 You can change a column’s data type, size, and default value.
ALTER TABLE dept80
MODIFY (last_name VARCHAR2(30));
The ALTER TABLE Statement: (RENAME COLUMN)
ALTER TABLE tablename
RENAME COLUMN column1 TO column2;
The syntax for renaming a column is
:
 Example:
ALTER TABLE dept80
RENAME COLUMN last_name TO Lname;
The ALTER TABLE Statement: (RENAME TABLE)
ALTER TABLE tablename
RENAME TO new_tablename;
The syntax for renaming a Table is
:
 Example:
ALTER TABLE dept80
RENAME TO departments;
Dropping a Table
• All data and structure in the table is deleted.
• You cannot roll back the DROP TABLE statement.
DROP TABLE tablename [CASCADE CONSTRAINTS] ;
The syntax for the DROP TABLE command is pretty simple:
DROP TABLE dept80;
Truncating a Table
• The TRUNCATE TABLE statement:
• Removes all rows from a table
• Releases the storage space used by that table
TRUNCATE TABLE dept80;
•Note That
• You cannot roll back row removal when using TRUNCATE.
• Alternatively, you can remove rows by using the DELETE statement.
• If the table is the parent of a referential integrity constraint, you cannot
truncate the table. Disable the constraint before issuing the TRUNCATE
statement.
28
Delete statments
• There is no need to specify the columns here – we’re working on
deleting rows so the columns don’t matter.
The DELETE query in SQL has some simple syntax:
DELETE FROM [ table ]
[WHERE condition];
DELETE FROM dept80
WHERE rating = 1;
29
References
:
• https://www.databasestar.com
• https://
docs.oracle.com/cd/B28359_01/server.111/b28318/dataty
pe.htm#CNCPT1824

data base programming chapter2 29 slides

  • 1.
    1 SQL CREATING AND MANAGINGTABLES Edited by :Nouf almunyif
  • 2.
    DatabaseObjects DatabaseObjects Object Description Table Basicunit of storage; composed of rows and columns View Logically represents subsets of data from one or more tables Sequence Numeric value generator Index Improves the performance of some queries Synonym Gives alternative names to the other objects All the database objects can be created using CREATE sql statement
  • 3.
    Tables • Creating tables •The alter statement • Dropping table
  • 4.
    Creating table: Syntax Database tables created using (CREATE TABLE statement)  The Minimal Syntax is:  You Specify:  tablename : The name you chooses for the table  column : Column name , It can also be up to 30 characters.  data type : column data type which specifies the type of data to be stored in this column and column size  DEFAULT expr: specifies a default value if a value is omitted in the INSERT statement CREATE TABLE tablename (column data type [DEFAULT expr], …..) ;
  • 5.
    Creating table: NamingRules  Table names and column names:  Must begin with a letter  Must contain only A–Z, a–z, 0–9, _, $, and #  Must not duplicate the name of another object owned by the same user  Must not be an Oracle Server reserved word  Use a descriptive names for table as well the other database objects  Note: Names are not case sensitive. (For example, EMPLOYEES is treated as the same name as eMPloyees or eMpLOYEES.) • The length of a table name depends on the database you’re using: • Oracle (before v12.2): 30 characters • Oracle (after v12.2): 128 characters • SQL Server: 128 characters • MySQL: 64 characters • PostgreSQL: 63 characters
  • 6.
    Creating table: DataTypes CHAR Datatype : Oracle guarantees that: •When you insert or update a row in the table, the value for the CHAR column has the fixed length. •If you give a shorter value, then the value is blank-padded to the fixed length. •If a value is too large, Oracle Database returns an error. VARCHAR2 Datatypes : Oracle guarantees that: • For each row, Oracle Database stores each value in the column as a variable-length field • If the value exceeds the column's maximum length, in which case Oracle Database returns an error. Using VARCHAR2 saves on space used by the table.
  • 7.
    Creating table: DataTypes The NUMBER datatype stores fixed and floating-point numbers. For numeric columns, you can specify the column as: column_name NUMBER Optionally, you can also specify a column_name NUMBER (precision, scale) If a precision is not specified, the column stores values as given. If no scale is specified, the scale is zero. You can specify a scale and no precision column_name NUMBER (*, scale) In this case, the precision is 38, and the specified scale is maintained. For input and output of numbers, the standard Oracle Database default decimal character is a period, as in the number 1234.56
  • 8.
    How Scale FactorsAffect Numeric Data Storage
  • 9.
    Creating table: DataTypes The DATE datatype stores point-in-time values (dates and times) in a table. The DATE datatype stores the year (including the century), the month, the day, the hours, the minutes, and the seconds (after midnight). For input and output of dates, the standard Oracle date format is DD-MON-YY, as follows: '13-NOV-92' Apex MM/DD/YYYY
  • 10.
    Creating table: DataTypes (Cont.)
  • 11.
    Creating table: DEFAULT •Specify default value for the column during the INSERT operation  Prevents NULL values from entering the columns if the row entered inserted without a value for the column • For the DEFAULT :  Literal values, expressions, or SQL functions are legal values  Another column’s name or pseudocolumn are illegal values  The DEFAULT value data type must match the column data type CREATE TABLE …..( ….. employment_status VARCHAR2(20) DEFAULT 'Hired‘, ……) To add a DEFAULT constraint to a column in a table when you create it in Oracle, add it to the Create Table statement: For example, to set a person’s employment status to a default of “Hired”: CREATE TABLE tablename ( columnname datatype DEFAULT defaultvalue );
  • 12.
    Creating table: Example CREATETABLE dept ( deptno NUMBER(2), dname VARCHAR2(14), loc VARCHAR2(13), create_date DATE DEFAULT SYSDATE ); Table created  Appears when you run the query DESCRIBE dept ; Crete a Table To Confirm the creation
  • 13.
    CREATE TABLE ASSELECT (CTAS) SQL allows you to create a table based on a SELECT statement. This is a very useful feature of the database. It’s great for development – if you want to copy an existing table and use it for testing or development purposes without changing the real table. Or, if you want a similar table with the same structure. The syntax for using this command is: CREATE TABLE table_name AS ( SELECT select_query ); If you want all records to be copied to the new table, you could specify SELECT * FROM old_table.
  • 14.
    14 CREATE TABLEAS SELECTWithout Copying Data • You can also use the CREATE TABLE AS SELECT to copy a table’s structure without any of the data. To do this, you just adjust your WHERE clause in the SELECT query to ensure there are no rows returned. By adding something that is clearly evaluated to FALSE ,A common example is WHERE 1=0. Or WHERE 1=2. Really, anything involving two numbers that are not equal will work.So, the SELECT statement will return the column names and data types, but no data • The syntax for this would be: CREATE TABLE table_name AS (SELECT * FROM old_table WHERE 1=0 );
  • 15.
    15 Oracle CREATE TABLEErrors and Exceptions • These are some of the errors and exceptions that may appear when you’re creating a table. As a database developer, you’ll get these kinds of errors all the time! Exception: ORA-00955: name is already used by an existing object Reason: You’re attempting to create a table with a name that is already being used. Resolution: Use a different name for your table, or drop the table with the existing name. Or, use a different schema for your table if that’s applicable. Exception: ORA-00904: : invalid identifier Reason: There are many reasons for this error, but it’s usually a syntax error. Resolution: Check that you have all of your commas and brackets in the right places in your statement. Exception: ORA-00957: duplicate column name Reason: You have two columns with the same name. Resolution: Rename one of your columns to make sure it is not a duplicate. Also, check that your commas and brackets are all in the right places
  • 16.
    The ALTER TABLEStatement The SQL ALTER TABLE statement lets you change a table that has already been created. • There are many things you can do with the SQL ALTER TABLE statement and some that you can’t. • Add one or more columns to a table • Change the data type of one or more columns • Add a constraint to a column • Drop a column from a table • Rename a column • Rename a table
  • 17.
    ALTER TABLE table ADD(column datatype [DEFAULT expr] [, column datatype]...); ALTER TABLE table MODIFY (column datatype [DEFAULT expr] [, column datatype]...); ALTER TABLE table DROP COLUMN column; The ALTER TABLE Statement: Syntax • There are many different clauses , Use the ALTER TABLE statement to add, modify or drop columns. The syntax of the SQL ALTER TABLE command is: ALTER TABLE tablename alter_table_clause;
  • 18.
    The ALTER TABLEStatement: Syntax
  • 19.
    ALTER TABLE dept80 ADD(job_id VARCHAR2(9)); The ALTER TABLE Statement: (Add) •Note That • You cannot specify where the new column appear The new column becomes the last column directly. • If the table already contains rows when the new column added, then the new column is initialized to NULL (as in this example) or default value (if specified) for all the rows The ALTER TABLE syntax to ADD column is: ALTER TABLE table_name ADD [COLUMN] column_name column_definition; Example:
  • 20.
    The ALTER TABLEStatement: (Add)
  • 21.
    21 The ALTER TABLEStatement: (Add) • Example: ALTER TABLE dept80 ADD (rating NUMBER(2) NOT NULL ); What happens to the existing values in a table, if you add a column with NOT NULL ? You will get an exception because the existing rows will have a value of NULL. To avoid this, specify a default value. ALTER TABLE dept80 ADD (rating NUMBER(2) NOT NULL DEFAULT 99 );
  • 22.
    The ALTER TABLEStatement: (DROP) • Note that: • You can’t drop a column that’s part of the primary key • The column may or may not contain data. • The table must have at least one column remaining in it after it is altered. • Once a column is dropped, it cannot be recovered • If there are columns that refer to the dropped columns using constraints, then you need to specify CASCADE CONSTRAINTS at the end of the statement. If this is not done, you will get an error. If you don’t have any columns that have these referential constraints, then you don’t need the CASCADE CONSTRAINTS clause. The syntax for dropping a column is : ALTER TABLE tablename DROP [COLUMN] column_1 [, column_n] [CASCADE CONSTRAINTS] ; ALTER TABLE dept80 DROP COLUMN job_id;  Use the DROP COLUMN clause to drop columns you no longer need from the table.
  • 23.
    The ALTER TABLEStatement: (Modify) • Note That: • A change to the default value affects only subsequent insertions to the table • You can decrease the width of a column only if the column contains only null values or if the table has no rows. • You can change the data type only if the column contains null values. ALTER TABLE tablename MODIFY column_name data_type; The syntax for modifying a column is :  You can change a column’s data type, size, and default value. ALTER TABLE dept80 MODIFY (last_name VARCHAR2(30));
  • 24.
    The ALTER TABLEStatement: (RENAME COLUMN) ALTER TABLE tablename RENAME COLUMN column1 TO column2; The syntax for renaming a column is :  Example: ALTER TABLE dept80 RENAME COLUMN last_name TO Lname;
  • 25.
    The ALTER TABLEStatement: (RENAME TABLE) ALTER TABLE tablename RENAME TO new_tablename; The syntax for renaming a Table is :  Example: ALTER TABLE dept80 RENAME TO departments;
  • 26.
    Dropping a Table •All data and structure in the table is deleted. • You cannot roll back the DROP TABLE statement. DROP TABLE tablename [CASCADE CONSTRAINTS] ; The syntax for the DROP TABLE command is pretty simple: DROP TABLE dept80;
  • 27.
    Truncating a Table •The TRUNCATE TABLE statement: • Removes all rows from a table • Releases the storage space used by that table TRUNCATE TABLE dept80; •Note That • You cannot roll back row removal when using TRUNCATE. • Alternatively, you can remove rows by using the DELETE statement. • If the table is the parent of a referential integrity constraint, you cannot truncate the table. Disable the constraint before issuing the TRUNCATE statement.
  • 28.
    28 Delete statments • Thereis no need to specify the columns here – we’re working on deleting rows so the columns don’t matter. The DELETE query in SQL has some simple syntax: DELETE FROM [ table ] [WHERE condition]; DELETE FROM dept80 WHERE rating = 1;
  • 29.