Purpose
You can use this statement to create a synonym.
Syntax
CREATE [ OR REPLACE ] [ PUBLIC ] SYNONYM [ synonym_schema. ]synonym_name
FOR [ object_schema. ]object_name;
Parameters
| Parameter | Description |
|---|---|
| OR REPLACE | Specifies to use a new definition to recreate the view if the name of the view to be created already exists. |
| PUBLIC | Specifies to create a public synonym, which can be used by all users. Only users with the corresponding privileges on the underlying object can use this synonym. A public synonym is used in parsing the reference to an object only when no schema is specified for the object. If PUBLIC is not specified, the synonym is private and accessible only within its schema. The name of a private synonym must be unique in its schema. |
| synonym_schema | The schema where the synonym is located. If schema. is omitted, the synonym is in your own schema by default. If PUBLIC is specified, schema cannot be specified for the synonym. |
| synonym_name | The name of the synonym. |
| object_schema | The schema that contains the object for which the synonym is created. If schema. is omitted, the object for which the synonym is created is in your own schema by default. |
| object_name | The name of the object for which the synonym is created. |
Examples
Create a synonym for a table.
obclient> CREATE TABLE tbl1(col1 INT,col2 INT); Query OK, 0 rows affected obclient> CREATE SYNONYM syn1 FOR tbl1; Query OK, 0 rows affected obclient> INSERT INTO syn1 VALUES(1,1); Query OK, 1 row affected obclient> SELECT * FROM syn1; +------+------+ | COL1 | COL2 | +------+------+ | 1 | 1 | +------+------+ 1 row in setCreate a public synonym.
obclient> CREATE PUBLIC SYNONYM syn2 FOR tbl1; Query OK, 0 rows affected
Considerations
The following part describes the privileges required for creating different types of synonyms:
To create a private synonym in your own schema, you must have the
CREATE SYNONYMprivilege.To create a private synonym in another user's schema, you must have the
CREATE ANY SYNONYMprivilege.To create a public synonym, you must have the
CREATE PUBLIC SYNONYMprivilege.The object for which the synonym is created does not need to exist and you do not need to have privileges to access the object.
/*Create a user named synonym_user.*/
obclient> CREATE USER synonym_user IDENTIFIED BY synonym_user;
Query OK, 0 rows affected
obclient> GRANT CREATE ON *.* TO synonym_user;
Query OK, 0 rows affected
obclient> GRANT SELECT ON *.* TO synonym_user;
Query OK, 0 rows affected
/*Connect to user synonym_user.*/
obclient> CREATE OR REPLACE SYNONYM syn1 FOR tbl1;
ERROR-00600: internal error code, arguments: -5036, Access denied; you need (at least one of) the CREATE SYNONYM privilege(s) for this operation
/*Grant the CREATE SYNONYM privilege to user synonym_user.*/
obclient> GRANT CREATE SYNONYM TO synonym_user;
Query OK, 0 rows affected
obclient> CREATE OR REPLACE SYNONYM syn1 FOR tbl1;
Query OK, 0 rows affected