How do you create and use synonyms in SQL?
Posted by DavidLee
Last Updated: June 12, 2024
In SQL, a synonym is an alternative name or alias for a database object such as a table, view, sequence, or stored procedure. Synonyms allow you to simplify access to these objects and can help in managing changes in database structures without affecting the applications that rely on them.
Creating Synonyms
The syntax to create a synonym varies slightly between different database management systems (DBMS). However, the most common syntax is as follows:
For Oracle:
CREATE SYNONYM synonym_name FOR object_name;
Example:
CREATE SYNONYM emp FOR employees; -- Creates a synonym "emp" for the "employees" table
For SQL Server:
In SQL Server, the syntax is a bit different:
CREATE SYNONYM synonym_name FOR schema.object_name;
Example:
CREATE SYNONYM emp FOR dbo.employees; -- Creates a synonym "emp" for the "employees" table in the dbo schema
Using Synonyms
After creating a synonym, you can use it in your SQL queries just like you would use the original object name. Example:
SELECT * FROM emp; -- This will select all records from the "employees" table using the synonym
Advantages of Using Synonyms
1. Simplification: It simplifies SQL statements, especially when using long object names or when dealing with complex schema names. 2. Data Abstraction: If the underlying object name changes (for example, if a table is renamed), you only need to update the synonym instead of updating all the application queries. 3. Cross-Database Access: In some cases, synonyms can be used to access objects across different databases.
Dropping Synonyms
If you no longer need a synonym, you can drop it using the following syntax:
For Oracle and SQL Server:
DROP SYNONYM synonym_name;
Example:
DROP SYNONYM emp; -- This will remove the synonym "emp"
Example Scenario
1. Create a Table:
CREATE TABLE employees (
    emp_id INT PRIMARY KEY,
    emp_name VARCHAR(100)
);
2. Create a Synonym:
CREATE SYNONYM emp FOR employees;
3. Use the Synonym:
SELECT * FROM emp; -- Uses the synonym instead of the actual table name
4. Delete the Synonym:
DROP SYNONYM emp;
Conclusion
Synonyms are a useful feature in SQL that can simplify database interactions and provide a level of abstraction. They can be easily created, used, and removed as needed, helping to manage database structures and maintain application compatibility effectively.
Related Content