Home > Articles > Data > SQL Server

SQL Server Query Design

The basics of programming against databases requires a firm understanding of the language used to create objects such as tables and views, read data, update data and remove data and objects. This series of tutorials covers the INSERT, UPDATE, DELETE, and SELECT statements.
This chapter is from the book

The basics of programming against databases requires a firm understanding of the language used to create objects such as tables and views, read data, update data and remove data and objects. You might see these commands referred to as CRUD—for CREATE, READ, UPDATE, and DELETE.

Many new developers rush into this phase of programming as their first step. Instead of jumping right into syntax, however, it's important to understand all of the processes involved in the development cycle. You can find out more about these processes in the series of tutorials that begin with Database Design: Requirements, Entities, and Attributes.

Once you fully understand those concepts, you can begin to work on the heart of the programming task: forming queries. Before I get to the syntax, however, there are a few formalities to deal with.

There are dozens of Transact-SQL commands that fall into two broad categories, or "languages": Data Definition Language (DDL) and Data Manipulation Language (DML). DDL statements create, alter and drop (remove) database objects. Those statements are covered in other tutorials beginning at Database Objects: Databases. The statements I'll focus on in the next few tutorials involve DML.

In this series of tutorials I'll cover the INSERT, UPDATE, DELETE, and SELECT statements. Along the way, I'll map these to the "CRUD" matrix.

There are two methods to get run T-SQL statements against a SQL Server. The first method is to use dynamic SQL, which involves sending SQL statements directly to the database through a client program. If you're using Query Analyzer and typing one of these four commands, that's dynamic SQL. Using Visual Basic or C#, you create can a connection object, build a T-SQL String, and send it to the database server. This is often the most effective way to send the commands, especially if your higher-level programming code builds the query "on the fly." Since the database has no foreknowledge of what the demands are, you can't plan ahead very well to run them any other way.

The second method is to use server-side programming. This involves the use of stored procedures, user-defined functions, and even views in the statements sent to the server. The process in the higher level language remains the same, with the exception that the string you send is the name of the stored procedure with any variables it requires. The statements in the stored procedures or views run on the server, instead of coming from the client program.

The second method has many advantages. For instance, the first time a stored procedure runs, SQL Server places it in a special location in memory called the procedure cache. The next time the stored procedure is called SQL Server accesses the faster memory location rather than direct storage. Designing often-used queries into stored procedures provides a great performance boost.

Which method is best? There's an old saying—"When all you have is a hammer, everything looks like a nail." I've seen fairly heated arguments between developers on whether to use a server-side versus a dynamic-SQL approach in a particular situation. In practice you'll often see a mixture of both, especially in larger, more complex programs.

With that in mind, you can determine the best method use by taking a holistic view of the program, using your previous experience, and testing. That's also the right order to begin the process.

Once you've created the requirements and the outline for the program, stop. Step back, and view the program from end to end. Evaluate the program flow diagrams and see if you can determine any patterns. Follow this step before you write any code.

Patterns form the basis of reusable objects that you should create, which are prime candidates for stored procedures. If there is a common "engine" that evaluates a condition, determine the variables you'll need to pass to make the stored procedure as useful as possible in multiple situations.

Taking a holistic view also includes larger program elements, such as scope, error handling, security, optimization and even data archival.

The original requirements document should contain a good definition of the program's scope. One of the most troubling issues in the modern development world is a disconnect between what the user thinks the program will do and what the developer codes. It's here, more often than not, that the primary stress factors of the programming effort lie. Make sure you have a firm understanding of the program's bounds. If you're not sure, check.

Determine how you'll handle errors early in the process. Of course each component will have unit-level error handling where you deal with any program errors that arise, but you'll want to determine how to handle larger error elements. Questions to ask here are things such as "If the program has an error, would you rather process 'X' roll all the way back to the beginning, or are partial data inserts permissible?" Most often it's best to prevent the user from entering "bad" data (a pessimistic design), but if the data depends on unknown states of data, this might not be possible (an optimistic design). These decisions will determine the transactions you create and even the data-base's original design.

Security is of paramount concern, right from the beginning. Think of the design as a building, and detail all possible entries and exits. This section requires a thorough knowledge of SQL Server access. The task becomes more difficult if the system exports or imports data. If it does, make sure you extend your security boundaries to include the source and destination systems.

Most of the performance of a system lies not in the hardware or database size, but in the proper design and use of indexes and queries. The important thing to remember during the initial design is that it is exponentially more difficult to optimize the design later. I'll explain how to optimize the individual queries in Part 2 of this series, but program optimization encompasses proper design, index creation and use, and effective queries.

Data archival involves a strategy for dealing with the data as time passes. This means that you should determine the effective "life" for each business data element that your program will store. How long will the data be used? Is it governed by any legal or ethical requirements? How often should it be rolled up? Is this the "system of record," where the data is created?

Once you've completed these steps, you're ready to code.

Query Basics

I've covered the holistic view of creating Transact-SQL statements earlier, and I mentioned the "CRUD" matrix—which stands for Create, Read, Update and Delete operations. In this tutorial I'll continue that process with the syntax that forms the basis for all queries.

I'll cover the statements in the "CRUD" order. Most tutorials begin with the SELECT statement, but I think I need to put data into the database before I can select it, so I'll start with the statements that create data. I'm making the assumption that you've already designed your database, tables, and other objects. For this tutorial, I'll use the pubs database.

The "Create" part of the CRUD matrix corresponds to the T-SQL INSERT statement. The INSERT statement has the following syntax:

INSERT INTO table (columns)
VALUES (value, or DEFAULT)
<<table hints>>

The INTO is actually optional, but I'm old school, so I still use it. What follows is the table name, and then the columns you want to put data into. You don't have to have the columns listed, if you're inserting data into all of them or if you use another syntax, like this:

INSERT INTO table
DEFAULT VALUES
GO

The caveat for this kind of insert is that each column must have a default value assigned.

When you're inserting data into a column, the data type must match what the column calls for. You must single-quote character strings, and you don't quote numeric values.

Here's an example of putting a new author in the pubs database:

INSERT INTO pubs.dbo.authors (
au_id
, au_lname
, au_fname
, contract)
VALUES (
’123-45-6789’
, ’Woody’
, ’Buck’
, 1)
GO

Note that I'm following the syntax I mention throughout all the tutorials with the commas at the front of the field lists. SQL Server ignores the whitespace anyway; I do this just to make sure I don't miss anything.

One other note—it's usually a good idea to have the table name prefaced as I have here. You'll actually save a microsecond or two when the statement is compiled if you do that. You can also bracket the field names with [], which is required if the field name has spaces in it. (You didn't do that when you created your database, did you?)

Notice also that I've only filled out four fields. The others either have defaults, or aren't required to have a value—they allow NULLs.

There are a couple of things to note about the INSERT statement. If you're inserting data into a table that has a column with IDENTITY set, then the table will automatically create a new value when you run an INSERT state-ment—assuming that you don't try to put one there explicitly. If you do want to explicitly use a value, you'll need to use the IDENTITY INSERT predicate first. You can find out more about that in Books Online.

You can also insert data into a table based on the result of a SELECT statement. Let's assume that you've got a duplicate of the authors table called authors2:

INSERT INTO authors2
SELECT *
FROM authors
GO

The reason this statement works is that the column names are in the same order, and the data types all match.

You can also use the results from a stored procedure this way. I'll show you that process a little later on.

Now that I've got the "C" in "CRUD", let's change the data around. You can use the UPDATE statement to change data once it's in the table. Here's the syntax:

UPDATE tablename
SET
columname=’Value’
WHERE columnname = ’ColumnValue’
GO

You can update as many columns as you want, and the WHERE is optional. If you don't specify the WHERE clause, you'll update all the columns in the column list to have the same value.

Let's use the UPDATE syntax to give Buck a home and a phone number:

UPDATE pubs.dbo.authors
SET
phone=’123 123-1234’
, address=’1313 Mockingbird Lane’
, city=’Tampa’
, state=’FL’
, zip=’12345’
WHERE au_fname = ’Buck’
GO

You have the full WHERE joining syntax available in this command and you can also use subselects as a condition for the update.

Next, I can get rid of data—the "D" in "CRUD". There are a couple of things you need to learn about this command even before you learn the syntax. For one thing, a delete is a delete. You can't get it back. Make sure you really want to do that when you call the statement.

Second, make sure you're looking for DELETE. If you want to get rid of an object completely such as a table or view, you're looking for the DROP command. DELETE removes rows, always.

Finally DELETE uses the transaction log. This means that if you have to delete an entire table, it's often more optimal to use the TRUNCATE command, like this:

TRUNCATE TABLE test1
GO

If you want to delete rows based on a condition, however, you do want the DELETE command. Here's the syntax:

DELETE FROM tablename
WHERE condition

The FROM is optional. Again, the condition has the full power of any of the selection logic in the other statements.

Let's get rid of Buck's entry:

DELETE FROM authors
WHERE au_fname = ’Buck’ AND au_lname = ’Woody’
GO

Now that I've created, updated and deleted data, I can use the SELECT command to see the data. This is the most commonly used command in T-SQL, and I've covered it before in the tutorial titled Getting Started with Transact-SQL. The basic syntax looks like this:

SELECT
fields
FROM tables
WHERE conditions
ORDER BY sort
Only the SELECT is required--here’s an example:
SELECT ’Buck’
GO

I won't cover the basics again here, but let's take a look at a couple of simple tricks you can do with the SELECT command. You've seen one already—you can select a constant with a single command. You can do the same thing with a variable.

To format the results of a SELECT command, you can use either a comma or a plus sign (+). A common request is to format results on one line at a time, with all the trailing spaces removed, like a standard mailing address looks. Here's a query that does just that:

SELECT
au_fname + ’ ’ + au_lname + CHAR(13) +
address + CHAR(13) +
city + ’ ’ + state + ’ ’ + zip + CHAR(13)+ CHAR(13)
FROM authors
GO

Here's how that happens. The plus-signs concatenate the fields rather than use standard spacing on them that you see with a comma. Because of that, you have to add spaces, which you can do with the +’’+ as I've got here, or you could use + SPACE(1) + instead.

At the end of each "row", I include the CHAR(13) function for a carriage-return line-feed. You can see that I end each row with a plus-sign rather than begin the next one with a comma—that's for the formatting again. In essence this is one long string. At the end I throw in a couple of returns for more spacing.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020