SQL Server Cheat Sheet A3
SQL Server Cheat Sheet A3
SQL Server Cheat Sheet A3
Use the ALTER TABLE or the EXEC statement to modify a table This deletes all rows satisfying the WHERE condition.
To list all databases on a server: structure. To count the rows in the table: To delete all data from a table, use the TRUNCATE TABLE
SELECT * SELECT COUNT(*) statement:
FROM sys.databases; FROM Animal; TRUNCATE TABLE Animal;
To change a table name:
EXEC sp_rename 'AnimalSchema.Animal', 'Pet'
To count the non-NULL values in a column:
To use a specified database: SELECT COUNT(Name) SQL SERVER CONVENTIONS
USE Zoo; To add a column to a table:
FROM Animal; In SQL Server, use square brackets to handle table or column
ALTER TABLE Animal
names that contain spaces, special characters, or reserved
ADD COLUMN Name VARCHAR(64);
keywords. For example:
To delete a specified database: To count unique values in a column:
SELECT
DROP DATABASE Zoo; To change a column name: SELECT COUNT(DISTINCT Name)
[First Name],
EXEC sp_rename 'AnimalSchema.Animal.Id', FROM Animal;
[Age]
'Identifier', 'COLUMN'; FROM [Customers];
To create a schema:
CREATE SCHEMA AnimalSchema; GROUP BY
To change a column data type: To count the animals by species: Often, you refer to a table by its full name that consists of the
ALTER TABLE Animal SELECT Species, COUNT(Id) schema name and the table name (for example,
DISPLAYING TABLES ALTER COLUMN Name VARCHAR(128); FROM Animal
GROUP BY Species;
AnimalSchema.Habitat, sys.databases). For simplicity,
we use plain table names in this cheat sheet.
To list all tables in a database:
To delete a column:
SELECT *
ALTER TABLE Animal To get the average, minimum, and maximum ages by habitat:
FROM sys.tables;
DROP COLUMN Name; SELECT HabitatId, AVG(Age), THE GO SEPARATOR
MIN(Age), MAX(Age) In SQL Server, GO is a batch separator used to execute multiple
To get information about a specified table: To delete a table: FROM Animal SQL statements together. It is typically used in SQL Server
exec sp_help 'Animal' DROP TABLE Animal; GROUP BY HabitatId; Management Studio and similar tools.