How do you create and manage synonyms in SQL Server?
Posted by JackBrn
Last Updated: July 16, 2024
In SQL Server, synonyms provide a way to create an alias for a database object such as a table, view, or stored procedure. This can simplify referencing these objects, especially when dealing with complex queries or when objects are in different schemas or databases. Here’s how you can create and manage synonyms in SQL Server:
Creating a Synonym
To create a synonym, use the CREATE SYNONYM statement. The basic syntax is as follows:
CREATE SYNONYM [schema_name.]synonym_name FOR [object_type_name];
- schema_name (optional): The schema under which the synonym is created. - synonym_name: The name of the synonym you want to create. - object_type_name: The fully qualified name of the object for which the synonym is being created. This includes the database name, schema name, and object name.
Example
CREATE SYNONYM mySchema.mySynonym FOR myDatabase.dbo.myTable;
This creates a synonym named mySynonym in the mySchema that points to myTable in the myDatabase's dbo schema.
Using a Synonym
Once the synonym is created, you can reference it in your SQL queries exactly as you would reference the original object:
SELECT * FROM mySchema.mySynonym;
Altering a Synonym
SQL Server does not provide a direct way to alter a synonym. If you need to change the object that a synonym points to, you must drop the existing synonym and create a new one.
Drop and Create Example
DROP SYNONYM mySchema.mySynonym;

CREATE SYNONYM mySchema.mySynonym FOR myDatabase.dbo.anotherTable;
Dropping a Synonym
To remove a synonym, you use the DROP SYNONYM statement:
DROP SYNONYM [schema_name.]synonym_name;
Example
DROP SYNONYM mySchema.mySynonym;
Considerations
1. Permissions: To create or drop a synonym, the user must have the appropriate permissions on the schema where the synonym is created. 2. Schema Binding: Synonyms are not schema-bound, meaning that altering the underlying object (e.g., renaming a table) does not affect the synonym. However, if the original object is dropped, the synonym becomes invalid. 3. Synonyms in Different Databases: You can create synonyms that refer to objects in other databases or even on other servers, but you'll need to ensure that the appropriate linked server setup is in place. Using synonyms can simplify SQL code and make it easier to manage, especially in larger systems with multiple schemas and cross-database queries.