A step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.
A C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.
This tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.
Creating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.
Using SELECT to retrieve dataThis tutorial deeply covers the SELECT statement of the T-SQL/SQL language. Starts from the basics - how to retrieve the values inside a column to ordering data, selecting multiple columns and then tables, joining them... |
On Tuesday, October 5th 2004 at 01:27 PM By Andrew Pociu (View Profile) ![]() ![]() ![]() ![]() (Rated 4.7 with 66 votes) |
|||||||||||||
|
What you will need for this tutorial: The Northwind database (along with the pubs database) is included in any SQL server installation, except for MSDE (Microsoft SQL Server Desktop Engine). So if you don't have this database you can download an utility from MSDN which, if you run it, will install the two databases. Using the SQL Query AnalyzerThe SQL Query Analyzer is a tool where you can test your queries on the available databases. When you start the application you'll be asked to select a SQL Server and the authentication mode. ![]() If you don't see any server name in the list click the '...' button and select a server from that list: ![]() I recommend you select 'Windows Authentication'. A query window is started but first a database on which the query will be executed must be selected. You can select a database from the toolbar on the top: ![]() Select the Northwind database because this is the one we're going to use in this tutorial. Using SELECTSelecting a columnThe SELECT command is the single keyword of DQL (Data Query Language - one of the categories in which T-SQL is divided). Using this keyword you can retrieve data from the database. Let's test it a bit using Query Analyzer. In the query window use the following query to retrieve a column (CategoryName) from a table (Categories):
Note that the keywords 'select' and 'from' are written all uppercase. This is not a requirement, more like a habit. Now run this query by pressing F5 or clicking the '>' shaped button (or play) from the toolbar. The result is the following: ![]() As you probably notice, the query we executed returns the contents of the CategoryName column from the Categories table. If you didn't yet get it (although I think you did), here's how the query works: ![]() This is a screenshot of the entire Categories table viewed with SQL Server Enterprise Manager. Well, I think you realized from the first view what the query 'SELECT CategoryName FROM Categories' does. No wonder, as if you look in a dictionary for the term SQL you'll find something similar: computer language: a standardized language that approximates the structure of natural English for obtaining information from databases. Full form structured query language Microsoft® Encarta® Reference Library 2003. © 1993-2002 Microsoft Corporation. All rights reserved. Selecting multiple columnsYou can select multiple columns from a table by separating their name with a comma:
The result being the following: ![]() Selecting all columns from a tableSure, you can select all the columns from a table by specifying each column name, the way we saw earlier in Selecting multiple columns. But there's another way, a shorter one:
This can be translated in english like 'Select all from categories'. So it retrieves all the columns from that table without having to specify each one of them. It's well known that the * (asterisk) sign is often used in such cases. Selecting only values that meet a criteriaOften when retrieving data from databases you need to return only values that meet a particular criteria. In our Categories table perhaps you may want to retrieve the description (available in the Description column) of a specific product, let's say of Condiments. You may think you can retrieve all the values from that table and then, in your application, search for the one that is equal to 'Condiments'. That would be - pardon me - stupid! Stupid, because you can retrieve only the value you are interested in by specifying this in the query, which is way more efficient:
This can be translated like "Select from the table Categories the value in the column CategoryName that is equal to 'Condiments'. Also select the description for that item". Here you can see the result: ![]() Selecting only values that meet more than one criteriaIn SQL Server Enterprise Manager, still in the database Northwind, open the table Customers where you'll see lots of fictive company names, contact names and titles, cities, countries etc.. On ContactTitle column you can see many 'Owner' values. Of course, if you want to select only the people who are owners, you would do a "SELECT * FROM Customers WHERE ContactTitle = 'Owner'". Still, you want to find all the owners from Mexico. That's not hard at all:
As you can see, the result is composed from 3 values. These 3 all are owners and live in Mexico. We retrieved this with the help of the AND keyword. Sorting resultsUsing SQL you can sort results ascending on descending. When sorting numbers ascending means from 0 up to 1, 2, 3 and so on, and of course, sorting descending is the reverse (ex. start with 56, continue with 55, 54, 53...). When sorting by letters, ascending means you start from A and end with Z, and descending means you start with Z and end with A. So, how do I actually sort?, you ask. Suppose you want to sort the values inside the Customers table ascending, by the name of the country:
The list starts with Argentina and ends with Venezuela. Selecting distinct valuesIn a table, for some obscure reason, you have duplicate records. Let's take the table we're currently working with - Customers. You want the list of all the countries where you have customers in. If you would just return all the countries as they are in the database you would get 'Argentina, Argentina, Argentina, Austria, Austria, Belgium, Belgium...' ...you get the point. There are no three Argentina's but there are 3 customers in that country, so for each one its country is returned. Here's where the DISTINCT keyword helps you out:
So now duplicate values are eliminated and you're happy cause you get the list of countries without duplicates. Selecting with another criteria if the other didn't metMaybe you want to retrieve all the customers from Liechtenstein, but if there are no customers there, you want to retrieve the customers from Switzerland. You can do this using the OR keyword:
In the table there's no customer from tiny Liechtenstein but there are two from Switzerland, therefore these will be displayed. Selecting data from multiple tablesMost of the time when doing SQL queries you'll have to work with multiple tables. Think about this: you have a table where you store your employees and one where you store the orders. Obviously, every row / field in the orders table represents an order. Each order has an employee who's responsible for it. Sure, for every order in the orders table you can specify the employees name, title, phone, address, hire date... But employees usually manage tens of orders, so to include all the employee information for each order is ineffective. If you don't know already how this kind of stuff is done right with most databases, here it is: In the employees table, each employee has an unique ID. In the Northwind databases, Davolio Nancy has ID 1, Fuller Andrew has ID 2 and so on... So why don't we just store this number instead of the name in the orders database. If one order is handled by Fuller Andrew, we'll store his id which is much shorter than storing all the information again and again for each order. Let's see how this works: ![]() Using JOININNER JOINNow, how can we join this two tables so that when we want to return information about an order, to have the name, title and phone of the employee that handles the order... to look like they're all in one database? Using JOIN. Run the following query:
And see the result: ![]() We joined two tables by specifying something that they have in common: the employee ID. LastName, Firstname and Title (in green) are columns from the Employees table and therefore provide information about the employee who's responsible for the order. ShipAddress (in red) is from the Orders table. So what does our query say? "Select the columns LastName, FirstName, Title and ShipAddress from the table Employees and the table Orders where there is a match between the values in column EmployeeID from the Employees table and between the EmployeeID column from the Orders table." - that's what our query says. OK, you say, I understand that the JOIN keyword is used to join two tables using columns with ID's, but what's the role of the INNER keyword (in INNER JOIN)? By specifying INNER, only the rows that match are displayed. For example if in the Orders table there's one order that says it's being handled by employee ID 10 but inside the Employees table there is no Employee with ID 10, the order won't be displayed as it doesn't have a match in the Employee table. There are other types of JOIN (FULL OUTER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, CROSS JOIN). LEFT OUTER JOIN and RIGHT OUTER JOIN and FULL OUTER JOINAs we discussed earlier, using INNER JOIN, the values that don't have a match aren't shown. Using LEFT OUTER JOIN the situation is different. Let's take our case with the Employees and Orders tables and run this query:
This query acts exactly like the earlier one, so it joins two tables. But because instead of using 'INNER JOIN' we used 'LEFT OUTER JOIN' if there is one value (more exactly ID) in the Employees table that doesn't match the value / ID in the Orders table, it will still be displayed. For example I add a new employee named Art Vandelay with the title of CEO in the Employees table. Next I run the query shown above. What do we see if we scroll down to the bottom of the list? Even if there's no order handled by Art Vandelay inside the Orders table (maybe he's too lazy or he's recently hired), a row with LastName, FirstName and Title will still be shown. Of course, we don't have the value for ShipAddress because this is a column inside Orders table where, as I stated earlier, there is no match: ![]() So the ShipAddress value is set to NULL. The difference between LEFT OUTER JOIN and RIGHT OUTER JOIN is simple. While in LEFT OUTER JOIN the rows from the table specified in the FROM clause will still be displayed even if they have no match, in RIGHT OUTER JOIN the rows from the table not specified in the FROM clause will still be displayed, even if they don't match with the values in the other table, therefore the one specified in the FROM clause will have nulls. So if you have an order handled by employee ID 23 (which doesn't exist in the Employees table), the order will still be shown but with the employee information set to null. FULL OUTER JOIN works as you might expect, even if there's no match between neither one of the values in the two tables, the values will still be displayed... this is actually LEFT OUTER JOIN + RIGHT OUTER JOIN. Specifying the table in which the column isLet's take the first query we used to join two tables:
After the ON keyword, we specify the table from which we want the EmployeeID column, as both tables contain a column with this name... think at it, it wouldn't make sense to say '...ON EmployeeID = EmployeeID', the computer wouldn't know at what EmployeeID column you refer to. This case also applies to the column names after the SELECT keyword - LastName, FirstName, Title, ShipAddress. What if in the Orders table you also had a column named Title? How is the computer supposed to know which one you want to select? How are you supposed to know what column you want to select when looking at your code after a few months? In conclusion, always prefix the name of the columns with the name of the table even if there are no columns with the same name in the two tables, because you may add later. So here's how it should be:
Using UNIONSuppose you have two tables of employees (for some obscure reason), one named oldEmployees and the other newEmployees. You'll want to join them so you can see all the employees your company has. You can do this using the UNION keyword, and the query is straightforward:
This will combine the columns of the two tables. Beware that you have to specify the same number of columns in the first SELECT statement as in the second SELECT statement. Also note that the columns need to have the same type (both varchar for example). If the name of one employee is listed in both tables (which frequently happens with first names and last names), only one will be displayed. This can be changed by using UNION ALL instead of UNION. There are some small things I didn't cover here, like CROSS JOIN, which I don't consider very important. If this tutorial is appreciated other SQL tutorials will follow (on using INSERT, UPDATE, DELETE and more advanced topics). Oh, and feel free to comment on this tutorial . |
||||||||||||||
Digg It!
Del.icio.us
Reddit
StumbleIt
Newsvine
Furl
BlinkList
|
||||||||||||||
|
||||||||||||||
Current CommentsI am learning about mysql queries and I have to say this has helped me learn about the SELECT query more than any other pages I've seen. I can't wait for the INSERT, DELETE, and UPDATE ones :)
CROSS JOIN:
mysql> SELECT * FROM tab1e, table
each row in table1 crosses every row in table 2 once.
Higly useless if you ask me. Its slow and suggests you tables aren't normalized and u certainly won't do them on large tables deployed as part of datastores serving high volume web sites
That was
SELECT * FROM table1, table2
Oops, in addition the term CROSS JOIN was adapted by some, but its a classical CARTESIAN product derived from classical mathematics.
it's really nice
Nice page.
I need to know how to select all tables in database from mssql database.
SELECT * FROM sysobjects WHERE type = 'U'
This is just excellent for beginners.It is fantastic
This is just excellent for beginners.It is fantastic
You can use SELECT statement for inserting records into a table.
Syntax:
SELECT <colsname> INTO <insert_table> FROM <select_table>
For Example: There are 6 records in a table named tableA and I want to insert them into a table named tableB. For that ..
SELECT * INTO tableB FROM tableA
Note: tableA and tableB should have same structure. Even this statement can create new table if insertTable is not created already.
I am trying to learn about Oracle SQL. This site is really helpful. I have a question, true or false. If the number of tables to be joined =N, we need to include at least N-1 equality conditions in the select statement so that each common column is referenced at least once?
Thank you for taking the time to show us this sample.
Very helpful. SQL question, I have an association table that stores an ID and numeric (1,2,3...) values that correlate to a users selection. How do I return the actual name of the selection if all I have is the numeric equivalent stored in the association table?
Thanks very much in advance
G
Very nice. Also, very informative and easy to understand. Thanks!
galing
question..
what's the code if i have to select data from three tables??
question..
what's the code if i have to select data from three tables??
how to retrieve all field names in a table using msSQL? like describe tablex in mysql
I believe there are several ways.
I suggest you give a try to the <b>SP_HELP</b> stored procedure:
SP_HELP MyTable
More information at <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_sp_help_304w.asp" target="_blank">http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_sp_help_304w.asp</a>.
hi,
i want to know the sql quary for retriveing, deleting and count duplicate data from a table.
thanks
i am working on a project in which i want to diplay table from my database. Is there some SQL statment for this reason??
like SELECT allTables FROM database
i mean " i want to display all tables names a user can selcet from given database"
I believe the "SP_Tables" stored procedure should do it...
i want to learn sql,this is fantastic,should iget the pdf file on my pc.
Great tutorial. Really helped me to understand what the statements are 'saying' - especially the JOINs. I will use this information to teach some high school students.
In Oracle There is Something Called as DESC <TABLENAME>. Is there any alternative for this in Sql Server.
i need a base for sql server.i need to use normalization and for database.please send some basic tips and tricks to use sql server.so its easy to pickup my growth in software skills.
Wow...GREAT tutorial. The whole section on selecting data from multiple tables was spectacular. Learned a TON!
is there any tutorial for northwind and pub for sql server 2000. Thanks
can u provide the table that contains syntax difference bet sql+ and sql query analyzer .
How to select all rows from two different tables even then there is no unique key that match to both tables??
goalpara, Guwahati,Assam.
good plz clarify to retrieve data after using the delete command in sql server
It's simple.
How to retrieve data from two different queries which returns different no. of columns in jsp?
It's really nice!
i need to configure sqldataadapter. while doing so i don\'t need entire table to be binded to grid but only selected columns. which rows to be selected must be obtained as arguments from another page. here the arguments should be caught and the values should be passed on to the table query so that the table is queried.then the queried table contents must be binded to the grid and displayed.
Dear friends,
I have a doubt in sql server database.If anyone having the solution please share with me please.
How can i retrieve a duplicate value from a table column.
Regards
S.Senthil Kumar
Hi i want query to get only field names of table in ms-access
Hi,
I have a table with Employee Id, Manager Id, Salary say it is arranged as:-
Emp ID Mgr ID Salary
01 2000
02 01 1000
03 01 1800
04 01 2100
05 02 1500
i need a query which displays the employees who is getting more salary than their respective managers, so the output should be:
Emp ID MgrId Salary
04 01 2100
05 02 1500.
Thanks,
Arun.L
I hv same table say \"Patient\" in 2 different databases that are present on different or same server, Now i want to get those different records from the \"Patient\" table that are present in these databases.
I m using sql 2005
Does anyone have any stored procedure or a SQL query that will solve my above problem.
hello
very good
hi
hi..i wanted to know how to retrieve data from 4 tables.there is 1 field in common to 3 tables..but the 4th one has only 1 field in common to another 1 table only..how can i retrieve data from all the 4 tables at once?in one query..using hibernate in project..so,cannot have more than 1 query.thanks.
hi
i want a query to retrieve all column names of a table.
can any one help me with that.
thanks
Hi,
i want a query to retrieve every 5th record in a table.what is the query ?? can anyone help me out !!!
Thanks.
It excellent for biginers. It has real good stuff.
how to get value from this query
select * from table1 where column1='city' union
select * from table2 where column1='city'
I am trying to find use the date which will be less than 0 for date as year but it dose not let me to run it
nice to know new things
nice to know new things
Hi,
if my date format in the table is as dd/mm/yyyy and I want to retrieve it as mm/dd/yyyy. Can any one help me out and let me the query please...
Regards,
Andrew
hi i am really want help if someone can help me i will be thanks
in this link there are explain for system i want the table and diagram for the whole system and the the entity
plz help
hi i am really want help if someone can help me i will be thanks
http://www.grc.upv.es/Software/bluemall/PM²HW²N 2008-BlueMallPaper.pdf
in this link there are explain for system i want the table and diagram for the whole system and the the entity
plz help
Related Tutorials
Related Source Code
SQL Job Search