SQL DDL Syntax Example
SQL DDL Syntax Example
SQL DDL Syntax Example
In such situations, we can use the CREATE DATABASE IF NOT EXISTS statement to
create a database only if there is no existing database with the same name.
For example,
Here, the SQL command creates a database named my_db only if there is no
existing database with the same name.
SHOW DATABASES;
Here, the SQL command lists all the available databases in the DBMS.
Switch Databases
We often have to work with multiple databases. To switch between available
databases, we can run the following statement.
USE my_db;
This code selects the my_db database, and all SQL operations will be
performed inside this database.
For more information on roles, see "Using SQL roles" in the Java DB Developer's
Guide.
Syntax
CREATE ROLE roleName
You cannot create a role name if there is a user by that name. An attempt to create a
role name that conflicts with an existing user name raises the SQLException X0Y68.
If user names are not controlled by the database owner (or administrator), it may be a
good idea to use a naming convention for roles to reduce the possibility of collision
with user names.
Derby tries to avoid name collision between user names and role names, but this is not
always possible, because Derby has a pluggable authorization architecture. For
example, an externally defined user may exist who has never yet connected to the
database, created any schema objects, or been granted any privileges. If Derby knows
about a user name, it will forbid creating a role with that name. Correspondingly, a
user who has the same name as a role will not be allowed to connect. Derby built-in
users are checked for collision when a role is created.
A role name cannot start with the prefix SYS (after case normalization). The purpose
of this restriction is to reserve a name space for system-defined roles at a later point.
Use of the prefix SYS raises the SQLException 4293A.
You cannot create a role with the name PUBLIC (after case
normalization). PUBLIC is a reserved authorization identifier. An attempt to create a
role with the name PUBLIC raises SQLException 4251B.
IDENTIFIED BY psw4visits;
Externally and Globally Clauses
Besides identifying by password, you may use one of the two other means of user authentication. It
will be configuring an external user or a global user. To do it, you need to include
the EXTERNALLY or GLOBALLY clause in the CREATE USER Oracle command.
EXTERNALLY allows for creating an external user. In this case, the user is authenticated by an
external system, such as the operating system. For instance, an Oracle database user is a Windows
user. Thus, they can access the database after getting authenticated by Windows without entering
other passwords. Working under the external user is a standard option for regular database users. But
such users only have standard roles (CONNECT and RESOURCE), without administrator or
database operator privileges.
IDENTIFIED EXTERNALLY
PROFILE external_user_profile1;
This way, we have made a new external user for our database. The name is external_user1. No
additional password is needed. We assigned this user the default tablespace tbs_new_10 with a quota
of 10 Mb. Other limitations are defined by the external_user_profile1 applied to this user.
As we mentioned earlier, different external systems can maintain and manage external users in the
Oracle database. Using the capabilities of the operating system is the most common option. Thus, if
we want to create an external database user accessible by the system account in the operating system,
we only need to modify our statement slightly. We’ll add the ops$ prefix to the username:
IDENTIFIED EXTERNALLY
PROFILE external_user_profile1;
GLOBALLY allows for creating global users. It means that their logins and passwords are stored on
the Central Oracle Security Server instead of the specific database. Besides, roles assigned to global
users on that central Server apply to this user in any database. It won’t be necessary to configure the
user role in a separate database. Note that you need to enable the single sign-on option for global
users.
IDENTIFIED BY password
Default Tablespace
This clause specifies the default tablespace for objects created by the user. Otherwise, such objects
are stored in the default tablespace of the database. If there are not any default tablespaces specified
for this particular database, the objects will get into the system tablespace.
Restriction: don’t specify the locally managed temporary tablespace (such as undo tablespace or
dictionary-managed temporary tablespace) to be the Oracle create user default tablespace.
Temporary Tablespace
This clause specifies the tablespace/tablespace group meant to contain the temporary segments of the
user. Without it, those users’ temporary segments are stored in the default temporary tablespace of
the database of the system tablespace. When you specify the tablespace group including the
tablespace_group_name value in the script, users’ temporary segments can be saved in any
tablespace of that group.
Note:
Make sure to specify the temporary tablespace with standard block size. It cannot be the undo
tablespace or the tablespace with automatic segment-space management.
Quota
This clause specifies how much space this user can allocate in the tablespace.
Multiple QUOTA clauses in one Oracle CREATE USER command can be present if you need to
specify several tablespaces.
The clause can include the UNLIMITED definition to allow this definite user to allocate the
tablespace as much as needed, without bounds.
IDENTIFIED BY password
[PROFILE profile]
[PASSWORD EXPIRE]
Profile
This optional clause lets you limit the database resources for this specific user at once when the
limitations are defined in the particular profile. Without this clause, a new user automatically comes
under the default profile.
Password Expire
The clause is optional, but many database administrators set it for more effective security. If
included, this clause will determine the forced change of the password on the user’s side. Usually, it
happens when the user tries to log into the database for the first time.
Account Lock/Account Unlock
You may use one of these clauses. With LOCK applied, Oracle creates the user account, but that
account won’t have access to the database. If you apply the UNLOCK clause or don’t specify any of
these two clauses, the account will be usable at once. The unlocked status is the default.
The CREATE USER statement with these additional parameters would be as follows:
IDENTIFIED BY migzw23ter
QUOTA 5M ON system
PROFILE qualified_user
PASSWORD EXPIRE;
ACCOUNT UNLOCK
Here, the statement creates a new Oracle database user named visitor, with the password migzw23ter.
This user is assigned the default tablespace tbs_new_10 with a quota of 50Mb. This user is also
allowed to use the temporary tablespace tbs_temp_10.
Working with Oracle databases inevitably includes the task of creating database users. There are the
system user accounts that Oracle creates itself – hr, OE, sys, etc. These accounts have predefined
configurations with rights and limitations. However, daily work will always require other users.
One of the DBA’s duties is to create additional database users. The job includes configuring the user
accounts, setting privileges, and managing users according to the business goals.
Granting Permission in Oracle
By using the GRANT command, you can provide the users with certain privileges and configure their
roles according to your needs. In Oracle, you can grant your permission to others so that they can
manipulate and manage the data in your database. GRANT is a very powerful statement with many
possible options, but the core functionality is to manage the privileges of both users and roles
throughout the database.
Oracle has more than 100 system privileges that can be found in the SYSTEM_PRIVILEGE_MAP
table.
Usually, the administrator of a database grants the privileges to the users. However, there are cases
when the administrator needs to transfer their Oracle user privileges. This is when DBA privileges
come in. If a DBA needs to provide system privilege to another person, it has to be done with the
admin option:
You can apply other privileges one by one, each by a separate statement. Or, it is possible to combine
these permissions into one, as shown below:
Let us take a closer look at how to grant CREATE TABLE privilege to a user in Oracle. If we are
willing to allow our user – visitor – to create tables in the database, we will use the following query:
GRANT CREATE TABLE to visitor;
However, there are several restrictions that you need to pay attention to before dropping the user:
You can’t remove users without deleting all the related objects. Thus, you must drop all tables,
views, procedures, etc. that this user created before proceeding to the DROP command.
You can’t remove users that are connected to the database. First, you have to clear up all
sessions that the user had. After that, you can drop the user itself.
There is a special command that allows for dropping the user with all its database objects in one shot:
In Oracle, CREATE TABLE statement is used to create a new table in the database.
To create a table, you have to name that table and define its columns and datatype for
each column.
Syntax:
Note: If you create the table in this way, the new table will contain records from the
existing table.
Syntax:
This table is named as "newcustomers" and having the same columns of "customers"
table.
The above example will create a new table called "newcustomers2". This table includes
the specified columns customer_id and customer_name from the customers table.
Let's take an example: Consider that you have already created two tables
"regularcustomers" and "irregularcustomers".
In the following example, we will create a table name "newcustomers3" form copying
columns from both tables.
Example:
To lock a table, you must either be the database owner or the table owner.
Avoid the overhead of multiple row locks on a table (in other words, user-
initiated lock escalation)
Avoid deadlocks
Syntax
LOCK TABLE table-Name IN { SHARE | EXCLUSIVE } MODE
After a table is locked in either mode, a transaction does not acquire any subsequent
row-level locks on a table. For example, if a transaction locks the
entire Flights table in share mode in order to read data, a particular statement
might need to lock a particular row in exclusive mode in order to update the row.
However, the previous table-level lock on the Flights table forces the exclusive
lock to be table-level as well.
If the specified lock cannot be acquired because another connection already holds a
lock on the table, a statement-level exception is raised (SQLState X0X02) after the
deadlock timeout period.
Examples
To lock the entire Flights table in share mode to avoid a large number of row
locks, use the following statement:
LOCK TABLE Flights IN SHARE MODE;
SELECT *
FROM Flights
WHERE orig_airport > 'OOO';
You have a transaction with multiple UPDATE statements. Since each of the
individual statements acquires only a few row-level locks, the transaction will not
automatically upgrade the locks to a table-level lock. However, collectively the
UPDATE statements acquire and release a large number of locks, which might result
in deadlocks. For this type of transaction, you can acquire an exclusive table-level
lock at the beginning of the transaction. For example:
LOCK TABLE FlightAvailability IN EXCLUSIVE MODE;
UPDATE FlightAvailability
SET economy_seats_taken = (economy_seats_taken + 2)
WHERE flight_id = 'AA1265' AND flight_date = DATE('2004-03-31');
UPDATE FlightAvailability
SET economy_seats_taken = (economy_seats_taken + 2)
WHERE flight_id = 'AA1265' AND flight_date = DATE('2004-04-11');
UPDATE FlightAvailability
SET economy_seats_taken = (economy_seats_taken + 2)
WHERE flight_id = 'AA1265' AND flight_date = DATE('2004-04-12');
UPDATE FlightAvailability
SET economy_seats_taken = (economy_seats_taken + 2)
WHERE flight_id = 'AA1265' AND flight_date = DATE('2004-04-15');
If a transaction needs to look at a table before updating the table, acquire an
exclusive lock before selecting to avoid deadlocks. For example:
LOCK TABLE Maps IN EXCLUSIVE MODE;
SELECT MAX(map_id) + 1 FROM Maps;
-- INSERT INTO Maps . . .
Create VIEW
Oracle View
In Oracle, view is a virtual table that does not physically exist. It is stored in Oracle data
dictionary and do not store any data. It can be executed when called.
Example:
Let's take an example to create view. In this example, we are creating two tables
suppliers and orders first.
Suppliers table:
1.
2. CREATE TABLE "SUPPLIERS"
3. ( "SUPPLIER_ID" NUMBER,
4. "SUPPLIER_NAME" VARCHAR2(4000),
5. "SUPPLIER_ADDRESS" VARCHAR2(4000)
6. )
7. /
8.
Orders table:
Syntax:
Example:
Execute the following query to update the definition of Oracle VIEW called sup_orders
without dropping it.
Output:
Syntax:
Example:
Alter
In Oracle, ALTER TABLE statement specifies how to add, modify, drop or delete columns
in a table. It is also used to rename a table.
Example:
Consider that already existing table customers. Now, add a new column customer_age
into the table customers.
Example
Example:
Example:
Example:
Example:
Drop
Oracle DROP TABLE statement is used to remove or delete a table from the Oracle
database.
Syntax
table_name: It specifies the name of the table which you want to remove from the
Oracle database.
PURGE: It is also optional. If specified, the table and its dependent objects are placed in
the recycle bin and can’t be recovered.
If there are referential integrity constraints on table_name and you do not specify the
CASCADE CONSTRAINTS option, the DROP TABLE statement will return an error
and Oracle will not drop the table.
This statement will drop the table called customers and issue a PURGE so that the space
associated with the customers table is released and the customers table is not placed in
recycle bin. So, it is not possible to recover that table if required.
Grant
Use the GRANT statement to give privileges to a specific user or role, or to all users,
to perform actions on database objects. You can also use the GRANT statement to
grant a role to a user, to PUBLIC, or to another role.
Privileges are granted to users and/or roles, where any user can be assigned to one
or more roles. The public and admin roles have special meaning:
The public role includes all users. This role can be used in a GRANT statement to assign
a privilege to every user.
The admin role is required to run certain commands, such as the ADD JAR command,
and it also allows access to certain objects even where access may not have been
explicitly granted to the user.
Syntax: GRANT
priv_type [, priv_type ] ...
ON table_or_view_name
TO principal_specification [, principal_specification] ...
The syntax that you use for the GRANT statement depends on whether you are
granting privileges to a schema object or granting a role.
For more information on using the GRANT statement, see "Using SQL standard
authorization" in the Java DB Developer's Guide.
In order to use a sequence generator, you must have the USAGE privilege on it. This
privilege can be granted to users and to roles. See CREATE SEQUENCE
statement for more information.
In order to use a user-defined type, you must have the USAGE privilege on it. This
privilege can be granted to users and to roles. See CREATE TYPE statement for more
information.
Before you can grant a role to a user or to another role, you must create the role using
the CREATE ROLE statement. Only the database owner can grant a role.
A role A contains another role B if role B is granted to role A, or is contained in a role
C granted to role A. Privileges granted to a contained role are inherited by the
containing roles. So the set of privileges identified by role A is the union of the
privileges granted to role A and the privileges granted to any contained roles of role
A.
privilege-types
ALL PRIVILEGES |
privilege-list
privilege-list
table-privilege {, table-privilege }*
table-privilege
DELETE |
INSERT |
REFERENCES [column list] |
SELECT [column list] |
TRIGGER |
UPDATE [column list]
column list
( column-identifier {, column-identifier}* )
Use the ALL PRIVILEGES privilege type to grant all of the privileges to the user or
role for the specified table. You can also grant one or more table privileges by
specifying a privilege-list.
Use the DELETE privilege type to grant permission to delete rows from the specified
table.
Use the INSERT privilege type to grant permission to insert rows into the specified
table.
Use the REFERENCES privilege type to grant permission to create a foreign key
reference to the specified table. If a column list is specified with the REFERENCES
privilege, the permission is valid on only the foreign key reference to the specified
columns.
Use the TRIGGER privilege type to grant permission to create a trigger on the
specified table.
Use the UPDATE privilege type to grant permission to use the UPDATE statement on
the specified table. If a column list is specified, the permission applies only to the
specified columns. To update a row using a statement that includes a WHERE clause,
you must have the SELECT privilege on the columns in the row that you want to
update.
grantees
{ AuthorizationIdentifier | roleName | PUBLIC }
[, { AuthorizationIdentifier | roleName | PUBLIC } ] *
You can grant privileges or roles to specific users or roles or to all users. Use the
keyword PUBLIC to specify all users. When PUBLIC is specified, the privileges or
roles affect all current and future users. The privileges granted to PUBLIC and to
individual users or roles are independent privileges. For example, a SELECT privilege
on table t is granted to both PUBLIC and to the authorization ID harry. The
SELECT privilege is later revoked from the authorization ID harry, but Harry can
access the table t through the PUBLIC privilege.
Either the object owner or the database owner can grant privileges to a user or to a
role. Only the database owner can grant a role to a user or to another role.
routine-designator
{
function-name | procedure-name
}
Examples
To grant the SELECT privilege on table t to the authorization IDs maria and harry,
use the following syntax:
GRANT SELECT ON TABLE t TO maria,harry
To grant the UPDATE and TRIGGER privileges on table t to the authorization
IDs anita and zhi, use the following syntax:
GRANT UPDATE, TRIGGER ON TABLE t TO anita,zhi
To grant the SELECT privilege on table s.v to all users, use the following syntax:
GRANT SELECT ON TABLE s.v to PUBLIC
Revoke
REVOKE statement
Use the REVOKE statement to remove privileges from a specific user or role, or from
all users, to perform actions on database objects. You can also use the REVOKE
statement to revoke a role from a user, from PUBLIC, or from another role.
principal_specification
: USER user
| ROLE role
priv_type
The derby.database.sqlAuthorization property must be set to true before you can use
the GRANT statement or the REVOKE statement.
The derby.database.sqlAuthorization property enables SQL
Authorization mode.
You can revoke privileges for an object if you are the owner of the object or
the database owner.
The syntax that you use for the REVOKE statement depends on whether you are
revoking privileges to a schema object or revoking a role.
For more information on using the REVOKE statement, see "Using SQL standard
authorization" in the Java DB Developer's Guide.
Revoking a privilege without specifying a column list revokes the privilege for all of
the columns in the table.
You must use the RESTRICT clause on REVOKE statements for routines. The
RESTRICT clause specifies that the EXECUTE privilege cannot be revoked if the
specified routine is used in a view, trigger, or constraint, and the privilege is being
revoked from the owner of the view, trigger, or constraint.
In order to use a sequence generator, you must have the USAGE privilege on it. This
privilege can be revoked from users and roles. Only RESTRICTed revokes are
allowed. This means that the REVOKE statement cannot make a view, trigger, or
constraint unusable by its owner. The USAGE privilege cannot be revoked from the
schema owner. See CREATE SEQUENCE statement for more information.
In order to use a user-defined type, you must have the USAGE privilege on it. This
privilege can be revoked from users and roles. Only RESTRICTed revokes are
allowed. This means that the REVOKE statement cannot make a view, trigger, or
constraint unusable by its owner. The USAGE privilege cannot be revoked from the
schema owner. See CREATE TYPE statement for more information.
privilege-types
ALL PRIVILEGES |
privilege-list
privilege-list
table-privilege {, table-privilege }*
table-privilege
DELETE |
INSERT |
REFERENCES [column list] |
SELECT [column list] |
TRIGGER |
UPDATE [column list]
column list
( column-identifier {, column-identifier}* )
Use the ALL PRIVILEGES privilege type to revoke all of the privileges from the user
or role for the specified table. You can also revoke one or more table privileges by
specifying a privilege-list.
Use the DELETE privilege type to revoke permission to delete rows from the
specified table.
Use the INSERT privilege type to revoke permission to insert rows into the specified
table.
Use the REFERENCES privilege type to revoke permission to create a foreign key
reference to the specified table. If a column list is specified with the REFERENCES
privilege, the permission is revoked on only the foreign key reference to the specified
columns.
Use the SELECT privilege type to revoke permission to perform SELECT statements
on a table or view. If a column list is specified with the SELECT privilege, the
permission is revoked on only those columns. If no column list is specified, then the
privilege is valid on all of the columns in the table.
Use the TRIGGER privilege type to revoke permission to create a trigger on the
specified table.
Use the UPDATE privilege type to revoke permission to use the UPDATE statement
on the specified table. If a column list is specified, the privilege is revoked only on the
specified columns.
grantees
{ AuthorizationIdentifier | roleName | PUBLIC }
[,{ AuthorizationIdentifier | roleName | PUBLIC } ] *
You can revoke the privileges from specific users or roles or from all users. Use the
keyword PUBLIC to specify all users. The privileges revoked from PUBLIC and from
individual users or roles are independent privileges. For example, a SELECT privilege
on table t is granted to both PUBLIC and to the authorization ID harry. The
SELECT privilege is later revoked from the authorization ID harry, but the
authorization ID harry can access the table t through the PUBLIC privilege.
You can revoke a role from a role, from a user, or from PUBLIC.
routine-designator
{
qualified-name [ signature ]
}
sequenceName
[ schemaName. ] SQL92Identifier
Once a result set has been returned to the application (by executing a prepared
statement or by direct execution), it will remain accessible even if privileges or roles
are revoked in a way that would cause another execution of the same statement to fail.
Limitations
The following limitations apply to the REVOKE statement:
Table-level privileges
All of the table-level privilege types for a specified grantee and table ID are
stored in one row in the SYSTABLEPERMS system table. For example,
when user2 is granted the SELECT and DELETE privileges on
table user1.t1, a row is added to the SYSTABLEPERMS table. The GRANTEE
field contains user2 and the TABLEID contains user1.t1. The SELECTPRIV
and DELETEPRIV fields are set to Y. The remaining privilege type fields are set
to N.
When a grantee creates an object that relies on one of the privilege types,
the Derby engine tracks the dependency of the object on the specific row in the
SYSTABLEPERMS table. For example, user2 creates the view v1 by using
the statement SELECT * FROM user1.t1, the dependency manager tracks
the dependency of view v1 on the row in SYSTABLEPERMS for
GRANTEE(user2), TABLEID(user1.t1). The dependency manager
knows only that the view is dependent on a privilege type in that specific row,
but does not track exactly which privilege type the view is dependent on.
Column-level privileges
Only one type of privilege for a specified grantee and table ID are stored in
one row in the SYSCOLPERMS system table. For example, when user2 is
granted the SELECT privilege on table user1.t1 for columns c12 and c13, a
row is added to the SYSCOLPERMS. The GRANTEE field contains user2, the
TABLEID contains user1.t1, the TYPE field contains S, and the COLUMNS
field contains c12, c13.
When a grantee creates an object that relies on the privilege type and the subset
of columns in a table ID, the Derby engine tracks the dependency of the object
on the specific row in the SYSCOLPERMS table. For example, user2 creates
the view v1 by using the statement SELECT c11 FROM user1.t1, the
dependency manager tracks the dependency of view v1 on the row in
SYSCOLPERMS for GRANTEE(user2), TABLEID(user1.t1), TYPE(S).
The dependency manager knows that the view is dependent on the SELECT
privilege type, but does not track exactly which columns the view is dependent
on.
Roles
Derby tracks any dependencies on the definer's current role for views,
constraints, and triggers. If privileges were obtainable only via the current role
when the object in question was defined, that object depends on the current
role. The object will be dropped if the role is revoked from the defining user or
from PUBLIC, as the case may be. Also, if a contained role of the current role in
such cases is revoked, dependent objects will be dropped. Note that dropping
may be too pessimistic. This is because Derby does not currently make an
attempt to recheck if the necessary privileges are still available in such cases.
Revoke examples
To revoke the SELECT privilege on table t from the authorization
IDs maria and harry, use the following syntax:
REVOKE SELECT ON TABLE t FROM maria,harry
To revoke the UPDATE and TRIGGER privileges on table t from the authorization
IDs anita and zhi, use the following syntax:
REVOKE UPDATE, TRIGGER ON TABLE t FROM anita,zhi
To revoke the SELECT privilege on table s.v from all users, use the following syntax:
REVOKE SELECT ON TABLE s.v FROM PUBLIC
To revoke the UPDATE privilege on columns c1 and c2 of table s.v from all users,
use the following syntax:
REVOKE UPDATE (c1,c2) ON TABLE s.v FROM PUBLIC
To revoke the USAGE privilege on the sequence generator order_id from the
role sales_role, use the following syntax:
REVOKE USAGE ON SEQUENCE order_id FROM sales_role;
To revoke the USAGE privilege on the user-defined type price from the
role finance_role, use the following syntax:
REVOKE USAGE ON TYPE price FROM finance_role;