Home > SQL Server Tips > SQL Server for the 'Reluctant' DBA > SQL language crash course (just enough to be dangerous)
SQL Server Tips:
EMAIL THIS
 TIPS & NEWSLETTERS TOPICS 

SQL SERVER FOR THE 'RELUCTANT' DBA

SQL language crash course (just enough to be dangerous)


Don Jones, Contributor
09.16.2009
Rating: -4.15- (out of 5)


Expert advice on database administration
Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google


The SQL language – which stands for "Structured Query Language" though these days "SQL" is pretty much a word itself – is shared by most major relational database management platforms including Microsoft SQL Server.

There are many American National Standards Institute (ANSI) standards for SQL and the very basics of the syntax have been standardized for some time.

You can't get far in the SQL Server world without some SQL up your sleeve. Here are the basics of the SQL language.

SELECT (for starters)

A SELECT query tells SQL Server what data you want from it. Technically speaking, SQL Server follows an ANSI-standard SQL syntax. This means most of the queries that I'll be showing you also work on other SQL-based platforms like MySQL and Oracle.

A basic SELECT query takes the following form:

SELECT { * | column,column,column } FROM table [WHERE criteria] [ORDER BY column]

After the keyword SELECT, specify * if every column from the table should be included. Otherwise you should provide a comma-delimited list of column names that you want.

Then use the FROM keyword to specify the table name the columns live in.

By default, SQL Server will return every row in the table. You can also specify a WHERE clause, which lists criteria for the rows you want returned.

For example, …WHERE OrderAmount = 1.00 will return only the rows where the OrderAmount column contains the value 1.00.

The columns specified in the WHERE clause do not have to be in the list of columns you SELECT. In other words, you can filter out rows based on columns you won't actually see.

In my example, it makes sense to do this since I'm only getting the rows that have 1.00 in OrderAmount. I don't need to see the OrderAmount column in my query output because I know what that column will contain.

Here are some more WHERE examples to give you an idea of what SQL Server can do:

  • …WHERE DateOrdered BETWEEN '7/1/2000' AND '7/1/2001'
  • …WHERE OrderAmount > 5000 AND OrderAmount < 2000
  • …WHERE CustomerName LIKE '%one%'
  • …WHERE (OrderAmount > 5000 AND OrderAmount < 2000) OR (SpecialOrder = 'Express')
  • …WHERE InvoiceNumber IN (1002,476382,7261)

You've seen the use of the following operators: BETWEEN, AND, LIKE (which uses % as wildcards), OR, and IN .

The BETWEEN operator specifies ranges (note that dates are treated as strings and included in single quotes).

The IN operator provides a comma-separated list of acceptable values.

A useful alternative for the IN operator is a subquery:

…WHERE InvoiceNumber IN (SELECT InvoiceNumber FROM BadOrders)

The subquery executes first, and theWHERE clause will include all rows where the InvoiceNumber appears in the BadOrders table. Finally, the optional ORDER BY clause lets you specify the order that the rows are returned. Once again you can specify columns not included in the output. For example, you might sort on a date field you don't need to look at.

Here are some more examples:

  • …ORDER BY DateOrdered
  • …ORDER BY DateOrdered DESCENDING
  • …ORDER BY DateOrdered,InvoiceNumber

The default sort order is ascending, and you can specify the ASCENDING keyword if you wish. The DESCENDING keyword reverses that order. The last example shows two columns for sorting: Rows will come out sorted first by date ordered and then by invoice number for rows that have the same DateOrdered value.

The final option I want point out is you can select a subset of matching rows. For example:

SELECT TOP 10 * FROM Orders WHERE OrderAmount > 5000 ORDER BY DateOrdered DESCENDING

This query grabs all the rows that have an order amount more than 5,000 and orders them with the most recently-placed order first. It will then send you only the first 10 of those rows, and will include every column in the table.

You can also specify …TOP 10 PERCENT… rather than a fixed number.

All combined, these are useful for grabbing "pages" of data from the server. Similarly, a BOTTOM keyword does exactly the opposite of the TOP keyword.

There are several more options associated with SELECT that we'll take a more detailed look at below.

INSERT

Now that you know how to get data out of the database, let's work on putting some in. The INSERT query allows you to add new rows to the database. To do this you need to specify a table to put the data in, the columns you are providing values for and then the values themselves. Rows are inserted one at a time.

The query looks like this:

INSERT INTO table (column,column,column) VALUES(value,value,value)

There is a way to omit the column list, but from a practical perspective it's easier to include it.

The values are listed in the same order as the columns – that's how SQL Server knows which value goes where. You need to specify columns and values for any column that doesn't either (a) have a default value or (b) allow an empty (null) value. Both the default and the "nullability" of a column is defined in the table's design.

Here's an INSERT example:

INSERT INTO Orders (Invoice,Amount,ShipMethod) VALUES(10383,30.00,'Express')

Note that date and text values are enclosed in single quotation marks. This can present problems if the string contains a single quote such as:

INSERT INTO Customers (Name,ZIP) VALUES ('Tim O'Leary','89123')

This results in an error because SQL Server will see Tim O as one value and not understand why Leary' is in there.

The trick is to replace all literal single quotes with a double-single quote. I know, that's like saying "put your seat back up," but here's what it looks like:

INSERT INTO Customers (Name,ZIP) VALUES ('Tim O''Leary','89123')

The dual single quotes after O and before Leary will be interpreted as one single quote when SQL Server executes the query. And that's about all there is to it!

The two biggest "gotchas" involve making sure you specify every column that requires a value (and not provided by default), and getting your punctuation – those single quotes and commas – correct.

UPDATE

When you need to make a change to existing data, an UPDATE query is your best friend.

This type of query is designed to update multiple rows at once and takes the following basic form:

UPDATE table SET column = value, column = value [WHERE criteria]

To change the completed column on every row in the Orders table, enter:

UPDATE Orders SET Completed = 1

However, you probably won't always want to change every row. In this case, add a WHERE clause:

UPDATE Orders SET Completed = 1 WHERE DateOrdered = DATE()

I threw in the built-in SQL Server DATE() function, which provides the current date, and as a result, I don't need to use single quotation marks.

I could also set multiple columns:

UPDATE Customers SET LastOrder = DATE(), OrderCount = OrderCount + 1, Frequent = 'Yes' WHERE CustomerID = 758392

Once again, I used the DATE() function and this time I also incremented the contents of the OrderCount column (by taking whatever was in that column already and adding 1), and then set the Frequent column to contain the string value Yes.

SQL Server's built-in functions can be very useful, and most can be used in WHERE clauses as well as in the SET clause. Many can also be used in a SELECT statement (we'll get to that later). A complete list of functions is available in the Microsoft Developer Network library. While this list for SQL Server 2000, they all work in 2005 and 2008 as well. The later versions just add more.

DELETE

Finally, there's the DELETE query, which removes rows from a table.

This query is almost always combined with a WHERE clause:

DELETE FROM Customers WHERE Inactive = 1

Without a WHERE clause, every row in the table will be deleted –something to avoid in most circumstances!


SQL SERVER FOR THE RELUCTANT DBA
Part 1: How SQL Server really works
Part 2: Understanding backup and recovery
Part 3: Optimizing indexes
Part 4: SQL language crash course
Part 5: SQL Server security made simple
Part 6: High-availability options and caveats

ABOUT THE AUTHOR:   
Don Jones is a co-founder of Concentrated Technology LLC, the author of more than 30 IT books and a speaker at technical conferences worldwide. Contact him through his website at www.ConcentratedTech.com.

Rate this Tip
To rate tips, you must be a member of SearchSQLServer.com.
Register now to start rating these tips. Log in if you are already a member.




Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google



RELATED CONTENT
SQL/Transact SQL (T-SQL)
Using DELETE and TRUNCATE TABLE statements to delete data in SQL Server
Working with IntelliSense in SQL Server 2008 Management Studio
SQL Server Mailbag: Stored procedures, triggers and SSRS reports
Working with sparse columns in SQL Server 2008
Determining the source of full transaction logs in SQL Server
New GROUP BY option provides better data control in SQL Server 2008
Using the OPENROWSET function in SQL Server
Loading data files with SQL Server's BULK INSERT statement
Importing and exporting bulk data with SQL Server's bcp utility
Testing transaction log autogrowth behavior in SQL Server
SQL/Transact SQL (T-SQL) Research

Microsoft SQL Server Tools and Utilities
Microsoft SQL Server Tools Guide
How SQL Server 2008 components impact SharePoint implementations
SQL Server Mailbag: Data restoration and DB property management
Setting up SQL Server Service Broker for secure communication
Microsoft SQL Server 2008 Resource Governor primer
The sqlcmd utility in SQL Server
Performance analysis tools for SQL Server
Software security tools to improve your skills in a single day
Surface Area Configuration and other security tools in SQL Server 2005
Securing IIS and SQL Server as part of an online platform

SQL Server for the 'Reluctant' DBA
SQL Server high availability: Options and caveats
SQL Server security made simple and sensible
Optimizing SQL Server indexes –- even when they're not your indexes
How to 'do' SQL Server disaster recovery
The short course on how SQL Server really works

RELATED GLOSSARY TERMS
Terms from Whatis.com − the technology online dictionary
ACID  (SearchSQLServer.com)
Collaboration Data Objects  (SearchSQLServer.com)
commit  (SearchSQLServer.com)
container  (SearchSQLServer.com)
DAO  (SearchSQLServer.com)
fetch  (SearchSQLServer.com)
OLE DB  (SearchSQLServer.com)
query  (SearchSQLServer.com)
SQL  (SearchSQLServer.com)
T-SQL  (SearchSQLServer.com)

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary

DISCLAIMER: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.



SQL Server Development - .NET, C#, T-SQL, Visual Basic
HomeNewsTopicsITKnowledge ExchangeTipsAsk the ExpertsMultimediaWhite PapersIT Downloads
About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
SEARCH 
TechTarget provides technology professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective purchase decisions and managing their organizations' technology projects - with its network of technology-specific websites, events and online magazines.

TechTarget Corporate Web Site  |  Media Kits  |  Site Map




All Rights Reserved, Copyright 2005 - 2009, TechTarget | Read our Privacy Policy
  TechTarget - The IT Media ROI Experts