Microsoft SQL Server


This draft deletes the entire topic.

inline side-by-side expand all collapse all

Examples

  • 20

    DML operations such as INSERT, UPDATE and DELETE:

    -- Create a table variable, which can be treated like a normal table
    
    DECLARE @HelloWorld TABLE (
        ID INT IDENTITY,
        Description VARCHAR(1000)
    )
    
    
    -- DML Operation - Insert, Inserting a row into the table
    INSERT INTO @HelloWorld (Description) VALUES ('Hello, World!')
    
    
    -- Displaying the table 
    SELECT * FROM @HelloWorld  
    
    -- Select a specific column from table
    SELECT Description FROM @HelloWorld
    
    
    -- Display number of records in the table
    SELECT Count(*) FROM @HelloWorld
    
    
    -- DML Operation - Update, Updating a specific row in the table
    UPDATE @HelloWorld SET Description = 'Hello World!' WHERE ID = 1
    
    
    -- Selecting the table. See how the DESCRIPTION changed after the UPDATE?
    SELECT * FROM @HelloWorld
    
    
    -- DML Operation - Delete, Deleting a row from the table
    DELETE FROM @HelloWorld WHERE ID = 1
    
    
    -- Selecting the table 
    SELECT * FROM @HelloWorld
    

    In this script we're creating a table variable, which resides in memory only, not in a database, to demonstrate some basic queries.

    The @ symbol in the example above needs to be used as a prefix for all variables you declare in T-SQL. Its purpose is to distinguish between a variable and a table, e.g.

    Use Northwind;
    go
    SELECT TOP 10 * FROM Customers 
    ORDER BY CompanyName
    

    will select the first 10 records of the Customer table, ordered by the column CompanyName from the database Northwind:

    enter image description here

    Note that Use Northwind; changes the default database for all subsequent queries. You can still reference the database by using the fully qualified syntax:

    SELECT TOP 10 * FROM Northwind.dbo.Customers 
    ORDER BY CompanyName
    
    SELECT TOP 10 * FROM Pubs.dbo.Authors
    ORDER BY City
    

    This is useful, if you're querying data from different databases. Note that dbo, specified "in between" is called a schema and needs to be specified always when using the fully qualified syntax.

    If the database table contains columns which are named like reserved words, e.g. Date, you need to enclose the column name in brackets, like so:

    -- descending order
    Select top 10 [Date] from dbo.MyLogTable
    order by [Date] desc 
    

    The same applies if the column name contains spaces in its name (which is not recommended).

  • 3

    Syntax:

    SELECT *
    FROM table_name
    

    Using the asterisk operator * serves as a shortcut for selecting all the columns in the table. All rows will also be selected because this SELECT statement does not have a WHERE clause, to specify any filtering criteria.

    This would also work the same way if you added an alias to the table, for instance e in this case:

    SELECT *
    FROM Employees AS e
    

    Or if you wanted to select all from a specific table you can use the alias + " .* ":

    SELECT e.*, d.DepartmentName
    FROM Employees AS e
        INNER JOIN Department AS d 
            ON e.DepartmentID = d.DepartmentID
    

    Database objects may also be accessed using fully qualified names:

    SELECT * FROM [server_name].[database_name].[schema_name].[table_name]
    

    This is not necessarily recommended, as changing the server and/or database names would cause the queries using fully-qualified names to no longer execute due to invalid object names.

    Note that the fields before table_name can be omitted in many cases if the queries are executed on a single server, database and schema, respectively. However, it is common for a database to have multiple schema, and in these cases the schema name should not be omitted when possible.

  • 3
    UPDATE HelloWorlds
    SET HelloWorld = 'HELLO WORLD!!!'
    WHERE Id = 5
    

    In this case when you use UPDATE like this, we will update value of column HelloWorld for record with Id = 5, after you execute this statement new value for record with Id = 5 will be: "HELLO WORLD!!!"

  • 0

    Whenever you change data, in a Data Manipulation Language(DML) command, you can wrap your changes in a transaction. DML includes UPDATE, TRUNCATE, INSERT and DELETE. One of the ways that you can make sure that you're changing the right data would be to use a transaction.

    DML changes will take a lock on the rows affected. When you begin a transaction, you must end the transaction or all objects being changed in the DML will remain locked by whoever began the transaction. You can end your transaction with either ROLLBACK or COMMIT. ROLLBACK returns everything within the transaction to its original state. COMMIT places the data into a final state where you cannot undo your changes without another DML statement.

    Example:

    --Create a test table
    
    USE [your database]
    GO
    CREATE TABLE test_transaction (column_1 varchar(10))
    GO
    
    INSERT INTO 
     dbo.test_transaction
            ( column_1 )
    VALUES
            ( 'a' )
    
    BEGIN TRANSACTION --This is the beginning of your transaction
    
    UPDATE dbo.test_transaction
    SET column_1 = 'B'
    WHERE column_1 = 'A'
    
    SELECT * FROM dbo.test_transaction  --This line will show you what changed
    
    ROLLBACK TRANSACTION  --Rollback will undo your changes
               --Alternatively, use COMMIT to save your results
    
    SELECT * FROM dbo.test_transaction   --View the table after your changes have been run
    
    DROP TABLE dbo.test_transaction
    

I am downvoting this example because it is...

Remarks

This is a set of examples highlighting basic usage of SQL Server.

Versions

VersionRelease Date
SQL Server 20162016-06-01
SQL Server 20142014-03-18
SQL Server 20122011-10-11
SQL Server 2008 R22010-04-01
SQL Server 20082008-08-06
SQL Server 20052005-11-01
SQL Server 20002000-11-01
Still have question about Getting started with Microsoft SQL Server? Ask Question

Basic DML Operations in MS SQL Server

20

DML operations such as INSERT, UPDATE and DELETE:

-- Create a table variable, which can be treated like a normal table

DECLARE @HelloWorld TABLE (
    ID INT IDENTITY,
    Description VARCHAR(1000)
)


-- DML Operation - Insert, Inserting a row into the table
INSERT INTO @HelloWorld (Description) VALUES ('Hello, World!')


-- Displaying the table 
SELECT * FROM @HelloWorld  

-- Select a specific column from table
SELECT Description FROM @HelloWorld


-- Display number of records in the table
SELECT Count(*) FROM @HelloWorld


-- DML Operation - Update, Updating a specific row in the table
UPDATE @HelloWorld SET Description = 'Hello World!' WHERE ID = 1


-- Selecting the table. See how the DESCRIPTION changed after the UPDATE?
SELECT * FROM @HelloWorld


-- DML Operation - Delete, Deleting a row from the table
DELETE FROM @HelloWorld WHERE ID = 1


-- Selecting the table 
SELECT * FROM @HelloWorld

In this script we're creating a table variable, which resides in memory only, not in a database, to demonstrate some basic queries.

The @ symbol in the example above needs to be used as a prefix for all variables you declare in T-SQL. Its purpose is to distinguish between a variable and a table, e.g.

Use Northwind;
go
SELECT TOP 10 * FROM Customers 
ORDER BY CompanyName

will select the first 10 records of the Customer table, ordered by the column CompanyName from the database Northwind:

enter image description here

Note that Use Northwind; changes the default database for all subsequent queries. You can still reference the database by using the fully qualified syntax:

SELECT TOP 10 * FROM Northwind.dbo.Customers 
ORDER BY CompanyName

SELECT TOP 10 * FROM Pubs.dbo.Authors
ORDER BY City

This is useful, if you're querying data from different databases. Note that dbo, specified "in between" is called a schema and needs to be specified always when using the fully qualified syntax.

If the database table contains columns which are named like reserved words, e.g. Date, you need to enclose the column name in brackets, like so:

-- descending order
Select top 10 [Date] from dbo.MyLogTable
order by [Date] desc 

The same applies if the column name contains spaces in its name (which is not recommended).

SELECT all rows and columns from a table

3

Syntax:

SELECT *
FROM table_name

Using the asterisk operator * serves as a shortcut for selecting all the columns in the table. All rows will also be selected because this SELECT statement does not have a WHERE clause, to specify any filtering criteria.

This would also work the same way if you added an alias to the table, for instance e in this case:

SELECT *
FROM Employees AS e

Or if you wanted to select all from a specific table you can use the alias + " .* ":

SELECT e.*, d.DepartmentName
FROM Employees AS e
    INNER JOIN Department AS d 
        ON e.DepartmentID = d.DepartmentID

Database objects may also be accessed using fully qualified names:

SELECT * FROM [server_name].[database_name].[schema_name].[table_name]

This is not necessarily recommended, as changing the server and/or database names would cause the queries using fully-qualified names to no longer execute due to invalid object names.

Note that the fields before table_name can be omitted in many cases if the queries are executed on a single server, database and schema, respectively. However, it is common for a database to have multiple schema, and in these cases the schema name should not be omitted when possible.

UPDATE Specific Row

3
UPDATE HelloWorlds
SET HelloWorld = 'HELLO WORLD!!!'
WHERE Id = 5

In this case when you use UPDATE like this, we will update value of column HelloWorld for record with Id = 5, after you execute this statement new value for record with Id = 5 will be: "HELLO WORLD!!!"

Comments in code

2

Transact-SQL supports two forms of comment writing. Comments are ignored by the database engine, and are meant for people to read.

Comments are preceded by -- and are ignored until a new line is encountered:

-- This is a comment
SELECT *
FROM MyTable -- This is another comment
WHERE Id = 1;

Slash star comments begin with /* and end with */. All text between those delimiters is considered as a comment block.

/* This is
a multi-line
comment block. */
SELECT Id = 1, [Message] = 'First row'
UNION ALL
SELECT 2, 'Second row'
/* This is a one liner */
SELECT 'More';

Slash star comments have the advantage of keeping the comment usable if the SQL Statement loses new line characters. This can happen when SQL is captured during troubleshooting.

Slash star comments can be nested and a starting /* inside a slash star comment needs to be ended with a */ to be valid. The following code will result in an error

/*
SELECT *
FROM CommentTable
WHERE Comment = '/*'
*/

The slash star even though inside the quote is considered as the start of a comment. Hence it needs to be ended with another closing star slash. The correct way would be

/*
SELECT *
FROM CommentTable
WHERE Comment = '/*'
*/  */

PRINT

2

Display a message to the output console. Using SQL Server Management Studio, this will be displayed in the Messages tab, rather than the Results tab:

PRINT 'Hello World!';

Select rows that match a condition

2

Generally, the syntax is:

SELECT <column names>
FROM <table name>
WHERE <condition>

For example:

SELECT FirstName, Age
FROM Users
WHERE LastName = 'Smith'

Conditions can be complex:

SELECT FirstName, Age
FROM Users
WHERE LastName = 'Smith' AND (City = 'New York' OR City = 'Los Angeles')

DELETE All Rows

1
DELETE
FROM Helloworlds

This will delete all the data from the table. The table will hold no data after you run this code.

Retrieve Basic Server Information

1
SELECT @@VERSION

Returns the version of MS SQL Server running on the instance.

SELECT @@SERVERNAME

Returns the name of the MS SQL Server instance

SELECT @@SERVICENAME

Returns the name of the Windows service MS SQL Server is running as.

UPDATE All Rows

1

A simple form of updating is incrementing all the values in a given field of the table. In order to do so, we need to define the field and the increment value

The following is an example that increments the Score field by 1 (in all rows):

UPDATE Scores
SET score=score+1  

This can be dangerous since you can corrupt your data if you make accidently mistake an UPDATE for a specific Row with an UPDATE for All rows in the table.

Create new table and insert records from old table

0
SELECT * INTO NewTable FROM OldTable

Creates a new table with structure of old table and inserts all rows into the new table.

Getting Table Row Count

0

The following example can be used to find the total row count for a specific table in a database if table_name is replaced by the the table you wish to query:

SELECT COUNT(*) AS [TotalRowCount] FROM table_name;

It is also possible to get the row count for all tables by joining back to the table's partition based off the tables' HEAP (index_id = 0) or cluster clustered index (index_id = 1) using the following script:

SELECT  [Tables].name                AS [TableName],
        SUM( [Partitions].[rows] )    AS [TotalRowCount]
FROM    sys.tables AS [Tables]
JOIN    sys.partitions AS [Partitions]
    ON  [Tables].[object_id]    =    [Partitions].[object_id]
    AND [Partitions].index_id IN ( 0, 1 )
--WHERE    [Tables].name = N'table name' /* uncomment to look for a specific table */
GROUP BY    [Tables].name;

This is possible as every table is essentially a single partition table, unless extra partitions are added to it. This script also has the benefit of not interfering with read/write operations to the tables rows'.

TRUNCATE TABLE

0
TRUNCATE TABLE Helloworlds 

This code will delete all the data from the table helloworlds. Truncate table is almost similar to Delete from Table code. The difference is that you can not use where clauses with Truncate. Truncate table is considered better than delete because it uses less transaction log spaces.

Note that if an identity column exists, it is reset to the initial seed value. This can lead inconsistency if the identity columns is used as a foreign key in another table.

Using Transactions to change data safely

0

Whenever you change data, in a Data Manipulation Language(DML) command, you can wrap your changes in a transaction. DML includes UPDATE, TRUNCATE, INSERT and DELETE. One of the ways that you can make sure that you're changing the right data would be to use a transaction.

DML changes will take a lock on the rows affected. When you begin a transaction, you must end the transaction or all objects being changed in the DML will remain locked by whoever began the transaction. You can end your transaction with either ROLLBACK or COMMIT. ROLLBACK returns everything within the transaction to its original state. COMMIT places the data into a final state where you cannot undo your changes without another DML statement.

Example:

--Create a test table

USE [your database]
GO
CREATE TABLE test_transaction (column_1 varchar(10))
GO

INSERT INTO 
 dbo.test_transaction
        ( column_1 )
VALUES
        ( 'a' )

BEGIN TRANSACTION --This is the beginning of your transaction

UPDATE dbo.test_transaction
SET column_1 = 'B'
WHERE column_1 = 'A'

SELECT * FROM dbo.test_transaction  --This line will show you what changed

ROLLBACK TRANSACTION  --Rollback will undo your changes
           --Alternatively, use COMMIT to save your results

SELECT * FROM dbo.test_transaction   --View the table after your changes have been run

DROP TABLE dbo.test_transaction

Topic Outline