Data Manipulation Language 5
This following example illustrates how to insert a partial row into the Publishers table
with a column list. The country column had a default value of Canada so it does not
require that you include it in your values.
INSERT INTO Publishers (PubID, PubName, city, province)
VALUES (‘9900’, ‘Acme Publishing’, ‘Vancouver’, ‘BC’)
To insert rows into a table with an IDENTITY column, follow the below example. Do
not supply the value for the IDENTITY nor the name of the column in the column list.
INSERT INTO jobs
VALUES (‘DBA’, 100, 175)
Inserting specific values into an IDENTITY column
By default, data cannot be inserted directly into an IDENTITY column; however, if a
row is accidentally deleted, or there are gaps in the IDENTITY column values, you
can insert a row and specify the IDENTITY column value.
IDENTITY_INSERT option
To allow an insert with a specific identity value, the IDENTITY_INSERT option can
be used as follows.
SET IDENTITY_INSERT jobs ON
INSERT INTO jobs (job_id, job_desc, min_lvl, max_lvl)
VALUES (19, ’DBA2’, 100, 175)
SET IDENTITY_INSERT jobs OFF
Inserting rows with a SELECT statement
We can sometimes create a small temporary table from a large table. For this, we can
insert rows with a SELECT statement. When using this command, there is no
validation for uniqueness. Consequently, there may be many rows with the same
pub_id in the example below.
This example creates a smaller temporary Publishers table using the CREATE
TABLE statement. Then the INSERT with a SELECT statement is used to add
records to this temporary Publishers table from the publis table.
CREATE TABLE dbo.tmpPublishers (
PubID char (4) NOT NULL ,
PubName varchar (40) NULL ,
city varchar (20) NULL ,
province char (2) NULL ,
country varchar (30) NULL DEFAULT (‘Canada’)
)
INSERT tmpPublishers
SELECT * FROM Publishers
In this example, we’re copying a subset of data.
INSERT tmpPublishers (pub_id, pub_name)
SELECT PubID, PubName
FROM Publishers
In this example, the publishers’ data are copied to the tmpPublishers table and the
country column is set to Canada.
INSERT tmpPublishers (PubID, PubName, city, province, country)
SELECT PubID, PubName, city, province, ‘Canada’
FROM Publishers
UPDATE statement
The UPDATE statement changes data in existing rows either by adding new data or
modifying existing data.
This example uses the UPDATE statement to standardize the country field to be
Canada for all records in the Publishers table.
UPDATE Publishers
SET country = ‘Canada’
This example increases the royalty amount by 10% for those royalty amounts between
10 and 20.
UPDATE roysched
SET royalty = royalty + (royalty * .10)
WHERE royalty BETWEEN 10 and 20
Including subqueries in an UPDATE statement
The employees from the Employees table who were hired by the publisher in 2010 are
given a promotion to the highest job level for their job type. This is what the
UPDATE statement would look like.
UPDATE Employees
SET job_lvl =
(SELECT max_lvl FROM jobs
WHERE employee.job_id = jobs.job_id)
WHERE DATEPART(year, employee.hire_date) = 2010
DELETE statement
The DELETE statement removes rows from a record set. DELETE names the table or
view that holds the rows that will be deleted and only one table or row may be listed
at a time. WHERE is a standard WHERE clause that limits the deletion to select
records.
The DELETE syntax looks like this.
DELETE [FROM] {table_name | view_name }
[WHERE clause]
The rules for the DELETE statement are:
1. If you omit a WHERE clause, all rows in the table are removed (except for
indexes, the table, constraints).
2. DELETE cannot be used with a view that has a FROM clause naming more
than one table. (Delete can affect only one base table at a time.)
What follows are three different DELETE statements that can be used.
1. Deleting all rows from a table.
DELETE
FROM Discounts
2. Deleting selected rows:
DELETE
FROM Sales
WHERE stor_id = ‘6380’
3. Deleting rows based on a value in a subquery:
DELETE FROM Sales
WHERE title_id IN
(SELECT title_id FROM Books WHERE type = ‘mod_cook’)
Built-in Functions
There are many built-in functions in SQL Server such as:
1. Aggregate: returns summary values
2. Conversion: transforms one data type to another
3. Date: displays information about dates and times
4. Mathematical: performs operations on numeric data
5. String: performs operations on character strings, binary data or expressions
6. System: returns a special piece of information from the database
7. Text and image: performs operations on text and image data
Below you will find detailed descriptions and examples for the first four functions.
Aggregate functions
Aggregate functions perform a calculation on a set of values and return a single, or
summary, value. Table 16.4 lists these functions.
FUNCTION DESCRIPTION
Returns the average of all the values, or only the DISTINCT values, in the
AVG
expression.
Returns the number of non-null values in the expression. When DISTINCT is
COUNT
specified, COUNT finds the number of unique non-null values.
Returns the number of rows. COUNT(*) takes no parameters and cannot be used
COUNT(*)
with DISTINCT.
Returns the maximum value in the expression. MAX can be used with numeric,
character and datetime columns, but not with bit columns. With character columns,
MAX
MAX finds the highest value in the collating sequence. MAX ignores any null
values.
Returns the minimum value in the expression. MIN can be used with numeric,
MIN character and datetime columns, but not with bit columns. With character columns,
MIN finds the value that is lowest in the sort sequence. MIN ignores any null values.
Returns the sum of all the values, or only the DISTINCT values, in the expression.
SUM
SUM can be used with numeric columns only.
Table 16.4 A list of aggregate functions and descriptions.
Below are examples of each of the aggregate functions listed in Table 16.4.
Example #1: AVG
SELECT AVG (price) AS ‘Average Title Price’
FROM Books
Example #2: COUNT
SELECT COUNT(PubID) AS ‘Number of Publishers’
FROM Publishers
Example #3: COUNT
SELECT COUNT(province) AS ‘Number of Publishers’
FROM Publishers
Example #3: COUNT (*)
SELECT COUNT(*)
FROM Employees
WHERE job_lvl = 35
Example #4: MAX
SELECT MAX (HireDate)
FROM Employees
Example #5: MIN
SELECT MIN (price)
FROM Books
Example #6: SUM
SELECT SUM(discount) AS ‘Total Discounts’
FROM Discounts
Conversion function
The conversion function transforms one data type to another.
In the example below, a price that contains two 9s is converted into five characters.
The syntax for this statement is SELECT ‘The date is ‘ + CONVERT(varchar(12),
getdate()).
SELECT CONVERT(int, 10.6496)
SELECT title_id, price
FROM Books
WHERE CONVERT(char(5), price) LIKE ‘%99%’
In this second example, the conversion function changes data to a data type with a
different size.
SELECT title_id, CONVERT(char(4), ytd_sales) as ‘Sales’
FROM Books
WHERE type LIKE ‘%cook’
Date function
The date function produces a date by adding an interval to a specified date. The result
is a datetime value equal to the date plus the number of date parts. If the date
parameter is a smalldatetime value, the result is also a smalldatetime value.
The DATEADD function is used to add and increment date values. The syntax for this
function is DATEADD(datepart, number, date).
SELECT DATEADD(day, 3, hire_date)
FROM Employees
In this example, the function DATEDIFF(datepart, date1, date2) is used.
This command returns the number of datepart “boundaries” crossed between two
specified dates. The method of counting crossed boundaries makes the result given by
DATEDIFF consistent across all data types such as minutes, seconds, and
milliseconds.
SELECT DATEDIFF(day, HireDate, ‘Nov 30 1995’)
FROM Employees
For any particular date, we can examine any part of that date from the year to the
millisecond.
The date parts (DATEPART) and abbreviations recognized by SQL Server, and the
acceptable values are listed in Table 16.5.
DATE PART ABBREVIATION VALUES
Year yy 1753-9999
Quarter qq 1-4
Month mm 1-12
Day of year dy 1-366
Day dd 1-31
Week wk 1-53
Weekday dw 1-7 (Sun.-Sat.)
Hour hh 0-23
Minute mi 0-59
Second ss 0-59
Millisecond ms 0-999
Table 16.5. Date part abbreviations and values.
Mathematical functions
Mathematical functions perform operations on numeric data. The following example
lists the current price for each book sold by the publisher and what they would be if
all prices increased by 10%.
SELECT Price, (price * 1.1) AS ‘New Price’, title
FROM Books
SELECT ‘Square Root’ = SQRT(81)
SELECT ‘Rounded‘ = ROUND(4567.9876,2)
SELECT FLOOR (123.45)