SQL Server Questions
SQL Server Questions
.
Click the Connect button, you should see the SQL Server Management Studio Express window
comes up.
How to run Queries with SQL Server Management Studio Express?
1. Launch and connect SQL Server Management Studio Express to the local SQL Server 2005
Express.
2. Click on the "New Query" button below the menu line. Enter the following SQL statement in the
query window:
SELECT 'Welcome to FYIcenter.com SQL Server!'
3. Click the Execute button in the toolbar area. You should get the following in the result window:
Welcome to FYIcenter.com SQL Server!
See the following picture to know where the query and result windows are:
.
How to download and install SQL Server 2005 Books Online?
1. Go to the SQL Server 2005 Books Online download page.
2. Click the download button, the File Download box shows up. Save the download file to c:\temp.
3. Double click on the downloaded file: c:\temp\SqlServer2K5_BOL_Feb2007.msi. The
installation setup window shows up. Follow the instructions to finish the installation.
4. When the installation is done. You will see a new entry in the Start menu: Start > Programs >
Microsoft SQL Server 2005 > Documentation and Tutorials
How to run SQL Server 2005 Books Online on your local system?
SQL Server 2005 Books Online can be accessed by a Web browser over the Internet. But you
can also download it and read it on your local system. If you have downloaded and installed SQL
Server 2005 Books Online package, you follow this tutorial to run it:
1. Click Start > Programs > Microsoft SQL Server 2005 > Documentation and Tutorials >
Tutorials > SQL Server Tutorials. The SQL Server 2005 Books Online window shows up.
2. Click the plus sign (+) next to "SQL Server 2005 Tutorials in the Contents window".
3. Click the plus sign (+) next to "SQL Server Tools Tutorials".
4. Click "Lesson 1: Basic Navigation in SQL Server Management Studio". The book content
shows up for you to read.
.
How to use Transact-SQL statements to access the database engine?
Transact-SQL statements can be used to access the database engine directly. Here are some
good tutorials provided by the SQL Server 2005 Books Online. See the SQL Server 2005
Tutorials > Database Engine Tutorials > Writing Transact-SQL Statements Tutorial section in the
SQL Server 2005 Books Online document.
This tutorial is intended for users who are new to writing SQL statements. It will help new users
get started by reviewing some basic statements for creating tables and inserting data. This
tutorial uses Transact-SQL, the Microsoft implementation of the SQL standard. This tutorial is
intended as a brief introduction to the Transact-SQL language and not as a replacement for a
Transact-SQL class. The statements in this tutorial are intentionally simple, and are not meant to
represent the complexity found in a typical production database.
How to create new databases with "CREATE DATABASE" statements?
This is the first tutorial of a quick lesson on creating database objects with Transact-SQL
statements. This lesson shows you how to create a database, create a table in the database, and
then access and change the data in the table. Because this lesson is an introduction to using
Transact-SQL, it does not use or describe the many options that are available for these
statements. This tutorial assumes that you are running SQL Server Management Studio Express.
Like many Transact-SQL statements, the CREATE DATABASE statement has a required
parameter: the name of the database. CREATE DATABASE also has many optional parameters,
such as the disk location where you want to put the database files. When you execute CREATE
DATABASE without the optional parameters, SQL Server uses default values for many of these
parameters. This tutorial uses very few of the optional syntax parameters.
To create a database - In a Query Editor window, type but do not execute the following code:
CREATE DATABASE TestData
GO
Use the pointer to select the words CREATE DATABASE, and then press F1. The CREATE
DATABASE topic in SQL Server 2005 Books Online should open. You can use this technique to
find the complete syntax for CREATE DATABASE and for the other statements that are used in
this tutorial.
In Query Editor, press F5 to execute the statement and create a database named TestData.
When you create a database, SQL Server makes a copy of the model database, and renames
the copy to the database name. This operation should only take several seconds, unless you
specify a large initial size of the database as an optional parameter.
How to create new table with "CREATE TABLE" statements?
This is the second tutorial of a quick lesson on creating database objects with Transact-SQL
statements. This lesson shows you how to create a database, create a table in the database, and
then access and change the data in the table. Because this lesson is an introduction to using
Transact-SQL, it does not use or describe the many options that are available for these
statements. This tutorial assumes that you are running SQL Server Management Studio Express.
To create a table, you must provide a name for the table, and the names and data types of each
column in the table. It is also a good practice to indicate whether null values are allowed in each
column.
Most tables have a primary key, made up of one or more columns of the table. A primary key is
always unique. The Database Engine will enforce the restriction that any primary key value
cannot be repeated in the table.
For a list of data types and links for a description of each, see Data Types (Transact-SQL).
Note: The Database Engine can be installed as case sensitive or non-case sensitive. If the
Database Engine is installed as case sensitive, object names must always have the same case.
For example, a table named OrderData is a different table from a table named ORDERDATA. If
the Database Engine is installed as non-case sensitive, those two table names are considered to
be the same table, and that name can only be used one time.
Before you create the table in this tutorial, execute the USE command to change the database
context to the TestData database. Otherwise, you will create the table in the database you were
connected to earlier. That was probably your default database. Unless your default database has
been changed, the default database is the master database. You should not create objects in the
master database.
Switch the Query Editor connection to the TestData database - In a Query Editor window,
type and execute the following code to change your connection to the TestData database.
USE TestData
GO
To create a table - In a Query Editor window, type and execute the following code to create a
simple table named Products. The columns in the table are named ProductID, ProductName,
Price, and ProductDescription. The ProductID column is the primary key of the table. int,
varchar(25), money, and text are all data types. Only the Price and ProductionDescription
columns can have no data when a row is inserted or changed. This statement contains an
optional element (dbo.) called a schema. The schema is the database object that owns the table.
If you are an administrator, dbo is the default schema. dbo stands for database owner.
CREATE TABLE dbo.Products
(ProductID int PRIMARY KEY NOT NULL,
ProductName varchar(25) NOT NULL,
Price money NULL,
ProductDescription text NULL)
GO
How to insert and update data into a table with "INSERT" and "UPDATE" statements?
This is the third tutorial of a quick lesson on creating database objects with Transact-SQL
statements. This lesson shows you how to create a database, create a table in the database, and
then access and change the data in the table. Because this lesson is an introduction to using
Transact-SQL, it does not use or describe the many options that are available for these
statements. This tutorial assumes that you are running SQL Server Management Studio Express.
Now that you have created the Products table, you are ready to insert data into the table by using
the INSERT statement. After the data is inserted, you will change the content of a row by using
an UPDATE statement. You will use the WHERE clause of the UPDATE statement to restrict the
update to a single row. The four statements will enter the following data.
ProductID ProductName Price ProductDescription
1 Clamp 12.48 Workbench clamp
50 Screwdriver 3.17 Flat head
75 Tire Bar Tool for changing tires
3000 3mm Bracket .52
The basic syntax is: INSERT, table name, column list, VALUES, and then a list of the values to
be inserted. The two hyphens in front of a line indicate that the line is a comment and the text will
be ignored by the compiler. In this case, the comment describes a permissible variation of the
syntax.
To insert data into a table - Execute the following statement to insert a row into the Products
table that was created in the previous task. This is the basic syntax.
-- Standard syntax
INSERT dbo.Products (ProductID, ProductName, Price, ProductDescription)
VALUES (1, 'Clamp', 12.48, 'Workbench clamp')
GO
The following statement shows how you can change the order in which the parameters are
provided by switching the placement of the ProductID and ProductName in both the field list (in
parentheses) and in the values list.
-- Changing the order of the columns
INSERT dbo.Products (ProductName, ProductID, Price, ProductDescription)
VALUES ('Screwdriver', 50, 3.17, 'Flat head')
GO
The following statement demonstrates that the names of the columns are optional, as long as the
values are listed in the correct order. This syntax is common but is not recommended because it
might be harder for others to understand your code. NULL is specified for the Price column
because the price for this product is not yet known.
-- Skipping the column list, but keeping the values in order
INSERT dbo.Products
VALUES (75, 'Tire Bar', NULL, 'Tool for changing tires.')
GO
The schema name is optional as long as you are accessing and changing a table in your default
schema. Because the ProductDescription column allows null values and no value is being
provided, the ProductDescription column name and value can be dropped from the statement
completely.
-- Dropping the optional dbo and dropping the ProductDescription column
INSERT Products (ProductID, ProductName, Price)
VALUES (3000, '3mm Bracket', .52)
GO
To update the products table - Type and execute the following UPDATE statement to change
the ProductName of the second product from Screwdriver, to Flat Head Screwdriver.
UPDATE dbo.Products
SET ProductName = 'Flat Head Screwdriver'
WHERE ProductID = 50
GO
How to read data in a table with "SELECT" statements?
This is the fourth tutorial of a quick lesson on creating database objects with Transact-SQL
statements. This lesson shows you how to create a database, create a table in the database, and
then access and change the data in the table. Because this lesson is an introduction to using
Transact-SQL, it does not use or describe the many options that are available for these
statements. This tutorial assumes that you are running SQL Server Management Studio Express.
Use the SELECT statement to read the data in a table. The SELECT statement is one of the most
important Transact-SQL statements, and there are many variations in the syntax. For this tutorial,
you will work with five simple versions.
To read the data in a table - Type and execute the following statements to read the data in the
Products table.
-- The basic syntax for reading data from a single table
SELECT ProductID, ProductName, Price, ProductDescription
FROM dbo.Products
GO
You can use an asterisk to select all the columns in the table. This is often used in ad hoc
queries. You should provide the column list in you permanent code so that the statement will
return the predicted columns, even if a new column is added to the table later.
-- Returns all columns in the table
-- Does not use the optional schema, dbo
SELECT * FROM Products
GO
You can omit columns that you do not want to return. The columns will be returned in the order
that they are listed.
-- Returns only two of the columns from the table
SELECT ProductName, Price
FROM dbo.Products
GO
Use a WHERE clause to limit the rows that are returned to the user.
-- Returns only two of the records in the table
SELECT ProductID, ProductName, Price, ProductDescription
FROM dbo.Products
WHERE ProductID < 60
GO
You can work with the values in the columns as they are returned. The following example
performs a mathematical operation on the Price column. Columns that have been changed in this
way will not have a name unless you provide one by using the AS keyword.
-- Returns ProductName and the Price including a 7% tax
-- Provides the name CustomerPays for the calculated column
SELECT ProductName, Price * 1.07 AS CustomerPays
FROM dbo.Products
GO
How to create a login to access the database engine using "CREATE LOGIN" statements?
This is the first tutorial of a quick lesson on creating login and configure users for databases with
Transact-SQL statements. Granting a user access to a database involves three steps. First, you
create a login. The login lets the user connect to the SQL Server Database Engine. Then you
configure the login as a user in the specified database. And finally, you grant that user permission
to database objects. This lesson shows you these three steps, and shows you how to create a
view and a stored procedure as the object. This tutorial assumes that you are running SQL
Server Management Studio Express.
To access the Database Engine, users require a login. The login can represent the user's identity
as a Windows account or as a member of a Windows group, or the login can be a SQL Server
login that exists only in SQL Server. Whenever possible you should use Windows Authentication.
By default, administrators on your computer have full access to SQL Server. For this lesson, we
want to have a less privileged user; therefore, you will create a new local Windows Authentication
account on your computer. To do this, you must be an administrator on your computer. Then you
will grant that new user access to SQL Server. The following instructions are for Windows XP
Professional.
To create a new Windows account - Click Start, click Run, in the Open box, type %SystemRoot
%\system32\compmgmt.msc /s, and then click OK to open the Computer Management program.
Under System Tools, expand Local Users and Groups, right-click Users, and then click New
User.
In the User name box type Mary.
In the Password and Confirm password box, type a strong password, and then click Create to
create a new local Windows user.
To create a login - In a Query Editor window of SQL Server Management Studio, type and
execute the following code replacing computer_name with the name of your computer. FROM
WINDOWS indicates that Windows will authenticate the user. The optional
DEFAULT_DATABASE argument connects Mary to the TestData database, unless her
connection string indicates another database. This statement introduces the semicolon as an
optional termination for a Transact-SQL statement.
CREATE LOGIN [computer_name\Mary]
FROM WINDOWS
WITH DEFAULT_DATABASE = [TestData];
GO
This authorizes a user name Mary, authenticated by your computer, to access this instance of
SQL Server. If there is more than one instance of SQL Server 2005 on the computer, you must
create the login on each instance that Mary must access.
How to create a user to access a database using "CREATE USER" statements?
This is the second tutorial of a quick lesson on creating login and configure users for databases
with Transact-SQL statements. Granting a user access to a database involves three steps. First,
you create a login. The login lets the user connect to the SQL Server Database Engine. Then you
configure the login as a user in the specified database. And finally, you grant that user permission
to database objects. This lesson shows you these three steps, and shows you how to create a
view and a stored procedure as the object. This tutorial assumes that you are running SQL
Server Management Studio Express.
Mary now has access to this instance of SQL Server 2005, but does not have permission to
access the databases. She does not even have access to her default database TestData until
you authorize her as a database user.
To grant Mary access, switch to the TestData database, and then use the CREATE USER
statement to map her login to a user named Mary.
To create a user in a database - Type and execute the following statements (replacing
computer_name with the name of your computer) to grant Mary access to the TestData database.
USE [TestData];
GO
CREATE USER [Mary] FOR LOGIN [computer_name\Mary];
GO
Now, Mary has access to both SQL Server 2005 and the TestData database
How to create a view and a stored procedure using "CREATE VIEW/PROCEDURE"
statements?
This is the third tutorial of a quick lesson on creating login and configure users for databases with
Transact-SQL statements. Granting a user access to a database involves three steps. First, you
create a login. The login lets the user connect to the SQL Server Database Engine. Then you
configure the login as a user in the specified database. And finally, you grant that user permission
to database objects. This lesson shows you these three steps, and shows you how to create a
view and a stored procedure as the object. This tutorial assumes that you are running SQL
Server Management Studio Express.
Now that Mary can access the TestData database, you may want to create some database
objects, such as a view and a stored procedure, and then grant Mary access to them. A view is a
stored SELECT statement, and a stored procedure is one or more Transact-SQL statements that
execute as a batch.
Views are queried like tables and do not accept parameters. Stored procedures are more
complex than views. Stored procedures can have both input and output parameters and can
contain statements to control the flow of the code, such as IF and WHILE statements. It is good
programming practice to use stored procedures for all repetitive actions in the database.
For this example, you will use CREATE VIEW to create a view that selects only two of the
columns in the Products table. Then, you will use CREATE PROCEDURE to create a stored
procedure that accepts a price parameter and returns only those products that cost less than the
specified parameter value.
To create a view - Execute the following statement to create a very simple view that executes a
select statement, and returns the names and prices of our products to the user.
CREATE VIEW vw_Names
AS
SELECT ProductName, Price FROM Products;
GO
Test the view - Views are treated just like tables. Use a SELECT statement to access a view.
SELECT * FROM vw_Names;
GO
To create a stored procedure - The following statement creates a stored procedure name
pr_Names, accepts an input parameter named @VarPrice of data type money. The stored
procedure prints the statement Products less than concatenated with the input parameter that is
changed from the money data type into a varchar(10) character data type. Then, the procedure
executes a SELECT statement on the view, passing the input parameter as part of the WHERE
clause. This returns all products that cost less than the input parameter value.
CREATE PROCEDURE pr_Names @VarPrice money
AS
BEGIN
-- The print statement returns text to the user
PRINT 'Products less than ' + CAST(@VarPrice AS varchar(10));
-- A second statement starts here
SELECT ProductName, Price FROM vw_Names
WHERE Price < @varPrice;
END
GO
Test the stored procedure - To test the stored procedure, type and execute the following
statement. The procedure should return the names of the two products entered into the Products
table in Lesson 1 with a price that is less than 10.00.
EXECUTE pr_Names 10.00;
GO
How to grant a permission using "GRANT EXECUTE" statements?
This is the fourth tutorial of a quick lesson on creating login and configure users for databases
with Transact-SQL statements. Granting a user access to a database involves three steps. First,
you create a login. The login lets the user connect to the SQL Server Database Engine. Then you
configure the login as a user in the specified database. And finally, you grant that user permission
to database objects. This lesson shows you these three steps, and shows you how to create a
view and a stored procedure as the object. This tutorial assumes that you are running SQL
Server Management Studio Express.
As an administrator, you can execute the SELECT from the Products table and the vw_Names
view, and execute the pr_Names procedure; however, Mary cannot. To grant Mary the necessary
permissions, use the GRANT statement.
Procedure Title - Execute the following statement to give Mary the EXECUTE permission for the
pr_Names stored procedure.
GRANT EXECUTE ON pr_Names TO Mary;
GO
In this scenario, Mary can only access the Products table by using the stored procedure. If you
want Mary to be able to execute a SELECT statement against the view, then you must also
execute GRANT SELECT ON vw_Names TO Mary. To remove access to database objects, use
the REVOKE statement.
Note: If the table, the view, and the stored procedure are not owned by the same schema,
granting permissions becomes more complex. For information about how to configure
permissions on objects with different owners, see Ownership Chains.
About GRANT You must have EXECUTE permission to execute a stored procedure. You must
have SELECT, INSERT, UPDATE, and DELETE permissions to access and change data. The
GRANT statement is also used for other permissions, such as permission to create tables.
How to delete database objects with "DROP" statements?
To remove all database objects created by previous tutorials, you could just delete the database.
However, in this tutorial, you will go through the steps to reverse every action you took doing the
tutorial.
Removing permissions and objects - Before you delete objects, make sure you are in the
correct database:
USE TestData;
GO
Use the REVOKE statement to remove execute permission for Mary on the stored procedure:
REVOKE EXECUTE ON pr_Names FROM Mary;
GO
Use the DROP statement to remove permission for Mary to access the TestData database:
DROP USER Mary;
GO
Use the DROP statement to remove permission for Mary to access this instance of SQL Server
2005:
DROP LOGIN [\Mary];
GO
Use the DROP statement to remove the store procedure pr_Names:
DROP PROC pr_Names;
GO
Use the DROP statement to remove the view vw_Names:
DROP View vw_Names;
GO
Use the DELETE statement to remove all rows from the Products table:
DELETE FROM Products;
GO
Use the DROP statement to remove the Products table:
DROP Table Products;
GO
You cannot remove the TestData database while you are in the database; therefore, first switch
context to another database, and then use the DROP statement to remove the TestData
database:
USE MASTER;
GO
DROP DATABASE TestData;
GO
What is a database?
To find out the location of database files, you can query the "sys.database_files" view as shown in
this tutorial example:
USE FyiCenterData
GO
If you don't like the default behavior of the CREATE DATABASE statement, you can specify the
physical database files with a longer statement:
CREATE DATABASE database_name
ON (NAME = logical_data_name,
FILENAME = physical_data_name,
SIZE = x, MAXSIZE = y, FILEGROWTH = z)
LOG ON (NAME = logical_log_name,
FILENAME = physical_log_name,
SIZE = x, MAXSIZE = y, FILEGROWTH = z)
For example, the following statement will create a database with database files located in the C:\temp
directory:
USE master
GO
If don't like the name of a database, you can change it by using the "ALTER DATABASE" statement
with the following syntax:
ALTER DATABASE database_name
MODIFY NAME = new_database_name
The tutorial example below shows you how change the database name from "FyiCenterData" to
"FyiCenterComData":
ALTER DATABASE FyiCenterData
MODIFY NAME = FyiCenterComData
GO
The database name 'FyiCenterComData' has been set
If you are trying to rename a database that is in use, you will get an error message like this: "The
database could not be exclusively locked to perform the operation."
Before renaming a database, you must stop all client sessions using this database. Otherwise, you
will get an error as shown in this tutorial example:
2. Keep the first instance running and launch another instance of SQL Server Management Studio:
ALTER DATABASE FyiCenterComData
MODIFY NAME = FyiCenterData
GO
Msg 5030, Level 16, State 2, Server LOCALHOST\SQLEXPRESS
The database could not be exclusively locked to perform
the operation.
A database is always in one specific state. For example, these states include ONLINE, OFFLINE, or
SUSPECT. To verify the current state of a database, select the state_desc column in the
sys.databases catalog view. The following table defines the database states.
ONLINE - Database is available for access. The primary filegroup is online, although the undo
phase of recovery may not have been completed.
OFFLINE - Database is unavailable. A database becomes offline by explicit user action and
remains offline until additional user action is taken. For example, the database may be taken
offline in order to move a file to a new disk. The database is then brought back online after the
move has been completed.
RESTORING - One or more files of the primary filegroup are being restored, or one or more
secondary files are being restored offline. The database is unavailable.
RECOVERING - Database is being recovered. The recovering process is a transient state; the
database will automatically become online if the recovery succeeds. If the recovery fails, the
database will become suspect. The database is unavailable.
RECOVERY PENDING - SQL Server has encountered a resource-related error during recovery.
The database is not damaged, but files may be missing or system resource limitations may be
preventing it from starting. The database is unavailable. Additional action by the user is required
to resolve the error and let the recovery process be completed.
SUSPECT - At least the primary filegroup is suspect and may be damaged. The database cannot
be recovered during startup of SQL Server. The database is unavailable. Additional action by the
user is required to resolve the problem.
EMERGENCY - User has changed the database and set the status to EMERGENCY. The
database is in single-user mode and may be repaired or restored. The database is marked
READ_ONLY, logging is disabled, and access is limited to members of the sysadmin fixed server
role. EMERGENCY is primarily used for troubleshooting purposes. For example, a database
marked as suspect can be set to the EMERGENCY state. This could permit the system
administrator read-only access to the database.
You can use the "ALTER DATABASE" to change database update options as shown in the tutorial
below:
USE FyiCenterComData
GO
As you can see from the output, inserting data into a table is not allowed if the database is in
READ_ONLY mode.
How to set database to be SINGLE_USER?
You can use the "ALTER DATABASE" to change database user access options as shown in the
tutorial below:
USE FyiCenterComData
GO
System databases are created by the SQL Server itself during the installation process. System
databases are used by the SQL server to help manage other user databases and client execution
sessions. SQL Server 2005 Express Edition uses 4 system databases:
master - The brain of a SQL server - Stores server configuration, runtime information, and
database metadata.
model - An empty database model - Used to clone new databases.
msdb - The background job scheduler - Used for background jobs and related tasks.
tempdb - The temporary database - Used by the server as a scratch pad.
What is a table?
A table in database is a data object used to store data. Tables have the following features:
Data is stored in a table with a structure of rows and columns.
Columns must be pre-defined with names, types and constrains.
A table object may have other associated data objects like, constrains, triggers, indexes, and
statistics.
For example, a table called Address may have columns defined to store different elements of an
address like, street number, city, country, postal code, etc.
DDL (Data Definition Language) statements are statements to create and manage data objects in the
database. The are three primary DDL statements to create and manage tables:
CREATE TABLE - Creating a new table.
ALTER TABLE - Altering the definition of an existing table.
DROP TABLE - Dropping an existing table.
DML (Data Manipulation Language) statements are statements to change data values in database
tables. The are 3 primary DML statements:
INSERT - Inserting new rows into database tables. For example "INSERT INTO fyi_links
VALUES (101, 'dev.fyicenter.com', NULL, 0, '2006-04-30')" inserts a single new row in the
fyi_links table.
UPDATE - Updating existing rows in database tables .
DELETE - Deleting existing rows from database tables.
If you want to practice DML statements, like INSERT, UPDATE and DELETE statements, you should
create a testing table. The tutorial exercise shows you a good example:
CREATE TABLE fyi_links (id INTEGER PRIMARY KEY,
url VARCHAR(80) NOT NULL,
notes VARCHAR(1024),
counts INT,
created DATETIME NOT NULL DEFAULT(getdate()))
GO
You should keep this table to practice other tutorial exercises presented in this collection.
How To Insert a New Row into a Table with "INSERT INTO" Statements?
To insert a new row into a table, you can use the INSERT INTO statement with values specified for all
columns as in the following syntax:
INSERT INTO table_name VALUES (list_of_values_of_all columns)
Note that the list of values of all columns must be specified in the same order as how columns are
defined in the CREATE TABLE statement. The following tutorial example inserts a row into "fyi_links":
INSERT INTO fyi_links VALUES (101,
'dev.fyicenter.com',
NULL,
0,
'2006-04-30')
GO
(1 row(s) affected)
If a column is defined with a default value in a table, you can use the key word DEFAULT in the
INSERT statement to take the default value for that column. The following tutorial exercise gives a
good example:
INSERT INTO fyi_links VALUES (102,
'dba.fyicenter.com',
NULL,
0,
DEFAULT)
GO
(1 row(s) affected)
The default value, getdate(), is used for "created" column, which gives the current date
If you don't want to specify values for columns that have default values, or you want to specify values
to columns in an order different than how they are defined, you can provide a column list in the
INSERT statement. If a column is omitted in the column, SQL Server applies 3 rules:
If default value is defined for the column, that default value will be used.
If no default value is defined for the column and NULL is allowed, NULL will be used.
If no default value is defined for the column and NULL is not allowed, SQL Server will reject the
insert statement with an error.
The first INSERT statement shows that: the order of the columns is reversed; the default value is
taken for the un-specified column "created"; the NULL value is taken for the un-specified column
"counts", since is has no default value defined and null is allowed.
The second INSERT statement shows the error you get for the un-specified column "url", because it
has no default value, and null is not allowed.
What Happens If You Insert a Duplicate Key for the Primary Key Column?
If your table has a primary key column, and you are trying to insert a new row with duplicate key value
on the primary key column, you will get an error. The reason is simple - Primary key column does not
allow duplicate values. The following tutorial exercise gives you a good example:
SELECT * FROM fyi_links
INSERT INTO fyi_links VALUES (101,
'sql.fyicenter.com',
NULL,
0,
'2006-04-30')
GO
Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint
'PK__fyi_links__03317E3D'. Cannot insert duplicate
key in object 'dbo.fyi_links'.
The statement has been terminated.
You are getting this error, because value "101" has already been used by an existing row.
If you want to insert multiple rows with a single INSERT statement, you can use a subquery instead of
the VALUES clause. Rows returned from the subquery will be inserted the target table. The following
tutorial exercise gives you a good example:
INSERT INTO fyi_links SELECT id+500, REVERSE(url),
notes, counts, created FROM fyi_links
GO
(3 row(s) affected)
As you can see, "INSERT INTO ... SELECT ..." is powerful statement. you can use it build up data in
tables quickly.
If you want to update some values in one row or multiple rows in a table, you can use the UPDATE
statement. The tutorial script below shows a good example:
SELECT * FROM fyi_links WHERE id = 101
GO
id url notes counts created
101 dev.fyicenter.com NULL 0 2006-04-30
As you can see, the SET clause takes column and value pairs to provide new values, while the
WHERE clause defines which row to apply the update
If the WHERE clause in an UPDATE statement matches multiple rows, the SET clause will be applied
to all matched rows. This rule allows you to update values on multiple rows in a single UPDATE
statement. Here is a good example:
SELECT * FROM fyi_links WHERE id >= 500
GO
id url notes counts created
601 moc.retneciyf.ved NULL 0 2006-04-30
602 moc.retneciyf.abd NULL 0 2007-05-19
603 moc.retneciyf.aqs NULL NULL 2007-05-19
The UPDATE statement updated 3 rows with the same new values.
This statement increased values in the id column by 200. It also updated the counts column with the
newly increased id value.
The answer is NO. The order of columns in the SET clause of the UPDATE statement is NOT
important. You probably already noticed from the previous tutorial. There is a BIG DIFFERENCE
among SQL Server, MySQL and Oracle on update multiple columns with previous values:
SQL Server provides you the existing values from the database on columns names used in new
value expressions. So the order of columns in the SET clause is NOT important
MySQL provides you the updated values on columns names used in new value expressions. So
the order of columns in the SET clause is important.
Oracle provides you the existing values from the database on columns names used in new value
expressions. So the order of columns in the SET clause is NOT important
Notice that the "id" in the "counts" new value expression is taking the old value of the "id" column, not
the updated value, even the "id" column is updated before the "counts" column.
Now try this on a MySQL server, you will get different result.
If you want to update values in one table with values from another table, you can use a subquery as
an expression in the SET clause. The subquery should return only one row for each row in the update
table that matches the WHERE clause. The tutorial exercise below shows you a good example:
-- Create another table
CREATE TABLE fyi_rates (id INTEGER,
comment VARCHAR(16))
Go
Note that if column names are confusing between the inner table and the outer table, you need to
prefix column names with table names, like "fyi_rates.id = fyi_links.id".
If you use a subquery to assign new values in the SET clause in an UPDATE statement, and the
subquery returns no rows for an outer row, SQL Server will provide a NULL value to the SET clause.
The tutorial exercise below shows you a good example:
-- insert a new row
INSERT INTO fyi_links (id, url, notes)
VALUES (0, 'www.fyicenter.com', 'Number one')
GO
(1 row(s) affected)
Column "notes" gets updated with NULL if there is no return rows in the subquery
If a subquery is used in a UPDATE statement, it must return exactly one row for each row in the
update table that matches the WHERE clause. If it returns multiple rows, SQL Server will give you an
error message. To test this out, you can try the following tutorial exercise:
-- insert two rows to fyi_rates
INSERT INTO fyi_rates VALUES (0, 'Number 1')
GO
INSERT INTO fyi_rates VALUES (0, 'Number 2')
GO
It is clear that we are using subquery as an expression, and it must return 0 or 1 row. Otherwise, we
will get an error.
How To Delete an Existing Row with DELETE Statements?
If you want to delete an existing row from a table, you can use the DELETE statement with a WHERE
clause to identify that row. Here is good sample of DELETE statements:
-- insert a row for this test
INSERT INTO fyi_links (url, id)
VALUES ('www.myspace.com', 301)
GO
(1 row(s) affected)
You can delete multiple rows from a table in the same way as deleting a single row, except that the
WHERE clause will match multiple rows. The tutorial exercise below deletes 3 rows from the fyi_links
table:
-- view rows to be deleted
SELECT id, url, notes, counts FROM fyi_links
WHERE id > 300
GO
id url notes counts
801 moc.retneciyf.ved Wrong 1202
802 moc.retneciyf.abd Wrong 1204
803 moc.retneciyf.aqs Wrong 1206
If you want to delete all rows from a table, you have two options:
Use the DELETE statement with no WHERE clause.
Use the TRUNCATE TABLE statement.
If you want to delete all rows from a table, you have two options:
Use the DELETE statement with no WHERE clause.
Use the TRUNCATE TABLE statement.
The TRUNCATE statement is more efficient the DELETE statement. The tutorial exercise shows you
a good example of TRUNCATE statement:
SELECT COUNT(*) FROM fyi_rates
GO
5