Click here to Skip to main content
Click here to Skip to main content

SQL in ten minutes

By , 31 Mar 2002
 

Introduction

You've probably heard of SQL. What does it mean, you ask. Well, SQL (Structured Query Language) is a very handy tool for database programmers (including ASP programmers). Without SQL, it would be very difficult to perform many common tasks relating to databases. In this article, I will teach you the basics and the common uses of SQL.

What can it do for me?

SQL is capable of achieving many tasks. Those tasks include:

  • Querying a table. To query a table means we select only the records that we need, according to some criteria we set.
  • Updating a table. Using SQL we can update a group of records that meet certain conditions.
  • Deleting records. SQL allows us to delete records in a breeze, whether it's only one record or a group of records.
  • Adding new records. Well, in this area SQL doesn't help us so much, but it's good to know how to use it for inserting records too.

In the next few paragraphs, you'll learn how exactly these four tasks are accomplished. Let's start!

The SQL statement

A SQL statement is a couple of words that tell the database handler what we want to do. The basic structure of a common SQL statement is:

DIRECTIVE fields FROM/INTO table [WHERE (field OP string) 
                                           [conj] (field OP string)]

Explanation:

  • DIRECTIVE - A SQL directive is a word describing what you want to do.
  • fields - This is a list of the fields on which you are going to execute the SQL statement.
  • FROM/INTO - If you query the table, it's FROM. If you insert a new record, it's INTO.
  • table - On which table we are working.
  • [ ] - Text inside the brackets is optional.
  • conj - This is a logical operator, allows us to make more complex SQL statements.
  • OP - A SQL operator.
  • string - The string you are searching for.

Confusing? Not at all! I will explain each of these weird things in the next paragraphs, along with examples to make you understand it.

The directives

Well, as you can see in the SQL statement structure, every SQL statement must start with a directive. So lets start learning those directives!

SELECT

With the SELECT directive, you can make your queries. Here are some examples:

SELECT * from Workers

The simplest SQL statement. This will select ALL records from the "Workers" table. The asterisk (*) sign means all fields. It will select all records because we have not included a WHERE clause.

SELECT WorkerName from Workers

This will select only the WorkerName field from the table "Workers".

SELECT FirstName,Phone from Phonebook

This statement will select the FirstName and Phone fields of the "Phonebook" table.

OK, so this was really nice. But if I want to show only the people who have got a Mercedes? No problem at all! There are two operators that allows us to query and select only records which meet our criteria. These are IS and LIKE. IS means that we want to select only the records in which a field is exactly what we want. Example :

SELECT * from Phonebook WHERE Car IS 'Mercedes'

This statement will select only the people who own a Mercedes (two people). Note that we don't use quotes in the field and table name, only in the search string. I also used * to select all fields. Note the use of a single quote (') and not double quote("). This is because the SQL statement is a string itself, and strings in programming languages are delimited in double quotes. Another example:

SELECT Car from Phonebook WHERE City IS 'NY'

Here we'll get a table showing the cars of the people living in New York in our phonebook. Well I told you before about IS and LIKE. You know how to use IS already, so let's start using LIKE too. LIKE allows us to define criteria for search. To use LIKE, you will need to know the meaning of a wildcard. A wildcard tells the computer that any other character (or characters) can be placed instead. For example, if the wildcard is @, then saying something like A@ means we search for the names starting with A. But if we say @A, then we mean names ending with A, because the A is after the wildcard. In SQL, the wildcard is not @, but %. Example for the usage of LIKE:

SELECT * from Phonebook WHERE Car LIKE 'M%'

This SQL will get us only the people who own a car brand beginning with "M". Note that if there was a car brand which is named "M" it will be selected too, because the % can be anything, even nothing - that means that there can be some characters after the M, but if there are no more chars its ok too.

SELECT * from Phonebook WHERE FirstName LIKE '%ou%'

This will select only the people who have a first name containing the sequence "ou".

SELECT * from Phonebook WHERE LastName LIKE '%'

This will simply select all records because % means everything.

SELECT * from Phonebook WHERE Car IS 'Mercedes' AND FirstName LIKE '%D%'

Here we used the conj you heard before. It will select for us, only the people who own a Mercedes AND that their first name contains a D.

SELECT * from Workers WHERE ((Department IS 'Sales') OR (Wage > 3000))

Ok - Here we used parenthesis to make reading this statement easier. Also, we used the > operator to select only those workers who work in the "Sales" department OR those workers with a wage of 3000 and higher. You can also use the < and = operators (= is like IS).

DELETE

Well, you know how to query tables. Now to deleting some records. The DELETE directive works exactly the same as SELECT, only it deletes records instead of selecting them. Examples:

DELETE from Workers WHERE FirstName IS 'Moses'

The statement will delete all the workers who are named "Moses". Note that you don't have to write * because you can't delete only certain fields. When you delete a record, or records, all the fields must be deleted. You may, however, put an *, but its not obligatory.

DELETE from Phonebook WHERE City IS 'NY'

Are you nutz!? To delete all your friends from New York!?

DELETE from Phonebook WHERE ((Car IS 'Mercedes') OR (Car IS 'Jaguar'))

Yep, we all feel jealous sometimes for our friends having (very) expensive cars!

UPDATE

So you wanna update some records ha? You've come to the right place! Well, the UPDATE directive is a bit different from SELECT and DELETE directives. This is how you write an UPDATE statement:

UPDATE table SET fields=values
  • table - The table name which we are updating records.
  • fields - The field name, and
  • values - The new values for the fields.

Example:

UPDATE Phonebook SET Lastname='Doe'

This will update all the records in your phonebook, so the last name of all your friends will be "Doe".

UPDATE Phonebook SET Car='None' WHERE 
         ((Car IS 'Ferrari') OR (Car IS 'Lambourghini'))

All your friends with race cars will now have NO car at all! You can also update several fields at once:

UPDATE Phonebook SET FirstName='Bill',LastName='Gates'

This will change all your friends to Bill Gates. It won't, however, make them acquire his budget.

INSERT

This is our last directive. INSERT will help you to add records to your tables. This is how we use it:

INSERT INTO table (fields) VALUES(values)
  • table - What table we are working on
  • fields - The list of fields that we want to give initial values, separated by commas.
  • values - The initial values we want to assign for the fields in the list.

Examples:

INSERT INTO Phonebook (FirstName,LastName) VALUES ('Bill','Gates')

Here we add a new record, and fill in the FirstName and LastName fields of the new record with the values "Bill" and "Gates". The other fields will be empty for now.

INSERT INTO Phonebook (FirstName,Phone) VALUES ('Tim','717-233-344')

I think this explains itself.

To sum up

So, what have we learned in this article? If you've read the whole thing, you now know how to use SQL to:

  • Query your tables.
  • Delete some records from your tables.
  • Update your records.
  • Insert new records.

SQL can do more complicated tasks, but this will give you a good start with SQL. I hope you find this useful!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Dan Pomerchik
Israel Israel
Member
Born in the darkside of the center of Israel (Petah Tiqva city), raised by my two parents, one of them is a computer man.
Started with the basic language, quickly moving on to Pascal than to borland C for dos. Playing for fun with VB and hopefully Visual C++ time will come..

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Generalgood intro articlememberDonsw21 Feb '09 - 6:15 
this is a good introductory article, you might want to suggest additional readings or books if they want more,
 
cheers,
Donsw
My Recent Article : Optimistic Concurrency with C# using the IOC and DI Design Patterns

GeneralInclude video in databasemember22teddy2227 Mar '07 - 5:56 
I was wondering if it is possible to include a video in the database so that when I call it in my website it no only displays the name, description or length (v_id, v_descript, v_length) but the actual video attached to it as well.
 
Thanks alot
GeneralhimemberMember #383788816 Feb '07 - 20:54 
how to connect sql with help of c source code
QuestionHow do i Sum (add) two Values from Diferent tablesmemberIridania13 Nov '06 - 4:31 
Hi i have two (2) Questions:
 
1st: I wold like to add (sum) two columns from differents tables i have to do a store procedure or a funtion.
2nd: how do i do thatConfused | :confused:
 
La Light

GeneralGreat article. Thanks!memberj0xeff15 Feb '06 - 20:13 
Big Grin | :-D
Questionhow to use column numbers in select querymemberHiral Patel15 Dec '05 - 5:35 
Hi
 
I wanted to use specific column numbers instead of column names in select query. Any help would be appreciated.
Thanks in advance.
 
Hiral.
GeneralRedbrix's University of Milverfieldmemberdamien fulham14 Nov '05 - 20:15 
Hello,
 
Newbie here. Any of you please, able to provide a .sql dump for use with Redbrix's demo (offline) so that it is similar to Redbrix online demo? Sigh | :sigh:
 
It's easier for me to learn things from a completed, done database, than to start it from scratch.
 
Thanks Wink | ;)
GeneralRe: Redbrix's University of Milverfieldmemberabhishek_it200525 Jul '06 - 21:51 
OMG | :OMG: Unsure | :~ Dead | X| Poke tongue | ;-P Laugh | :laugh: Sigh | :sigh: Cry | :(( Sleepy | :zzz: :->
GeneralConverting columns to recordsmemberMark G Hahn12 Oct '05 - 17:38 
What select statement would allow me to do this...
 
Orginal table:
 
ID COL1 COL2 COL3
01 aaaa bbbb cccc
02 cccc dddd eeee
03 bbbb ffff aaaa
 
Result needed:
 
ID COL
01 aaaa
01 bbbb
01 cccc
02 cccc
02 dddd
02 eeee
03 bbbb
03 ffff
03 aaaa
 
This one has me stumped.
AnswerRe: Converting columns to recordsmemberDinobot_Slag17 Jul '07 - 5:29 
select ID, COL1 as COL from table
union
select ID, COL2 as COL from table
union
select ID, COL3 as COL from table
order by ID
GeneralAdding records at the top of a tablesussGiancarlo26 Oct '05 - 16:48 
Hi, Can someone please tell me how can I add a data row at the beginning of a table instead of at the end?
 
Thank you,
Giancarlo2.
GeneralRe: Adding records at the top of a tablememberreal_valo10 Aug '06 - 2:26 
As far as I know, this can't be done, but I may be wrong ofcourse. Please post a mess here if you find out.
 
Now I have a question: why do (did) you need it on top of your table?
 
If something can go wrong, it will. (murphy)
Questionhow can i copy an object?memberCamilo Sanchez19 Jul '05 - 12:19 
i'm making an asp.net application in wich i have a table for storing the users data.
i want to store an object of a class that i designed for storing information about each user into one record in that table.
i tried this:
//-------------------------------------------------------------------------
dataSet11.Tables["User"].Rows[n]["tag"]=new MyInfoClass();
//-------------------------------------------------------------------------
where:
User is my table;
n is an integer (the index of the user in the table)
tag is the column name, which fieldtype is oleobject
MyInfoClass is the name of the class that i want to store
 
when i run this whithin my application, visual studio tells me that MyInfoClass must implement IConvertible
 
i want to store it without doing so

 
if you have any suggestion or idea about this i'll be very gratefull
 

GeneralSQL server connectivity InC/C++memberPrabhdeep19 Jun '05 - 18:48 
Hi Friends Please tell me how to get connected to SQL server through C Code
I need it badly man please help..
 

If Anybody Knows How To Do It Please Mail @prabhdeeep@gmail.com
 
Thank You Bro's Smile | :)
 
Prabhdeep
GeneralRe: SQL server connectivity InC/C++memberalexandros__12 Sep '05 - 0:54 
I've the same problem.
If you know a good way to use sql servers from c/c++, please answer in this thread or send me a mail at alexandros__@msn.com
 
Thanks!
 
Alex
GeneralasasdsussAnonymous9 Apr '05 - 1:27 
Confused | :confused: WTF | :WTF: OMG | :OMG: Sleepy | :zzz:
GeneralSQL Help/Examplememberkaritoppinen11 Jun '04 - 8:35 
If I INSERT data into a table 'table_1' from my C++ application and want the SQL Server to INSERT portions of data from 'table_1' into 'table_2' and 'table_3', how do I solve that in a correct way? Do I have to do INSETR from my C++ application into 'table_2' and 'table_3' or is there a better way to let the SQL Server handle that??
 
KT
Generalproblem in update statementsussARATHI VASUPAL29 May '04 - 17:41 
I am facing problem in updating a table with the variables having single quote.It is saying as 'Syntax error (missing operator) in query expression and i am unable to trace the error.The syntax i am using is "update table_name set code='"& s1 &"',notes='"& text8.text &"' where plaque_no='"& str1 &"'"
Here the notes field is containing the text with the single quote and i am facing the problem here.
Please if anybody can help me in this regard as early as posible,I will be very grateful.
Thanx,
Arathi.

GeneralRe: problem in update statementsussAnonymous23 Dec '04 - 20:44 
try the query
'"&str1"' & '"text8.text"'
GeneralUPDATE STATEMENTsussARATHI VASUPAL29 May '04 - 17:32 
I am trying to update a table with a set of values.I am facing problem if there is a single quote in the variables.
It is saying that there is a 'Syntax error (missing operator)in query expression'.I am unable to trace the error and i hope somebody will help me to solve this problem and i will be very grateful if anybody helps me in this regard.
Thanx,
Arathi.
QuestionHow do I use variables?memberT10006 Jan '04 - 0:07 
I want to use variables in this funktion. How do I do that?
SQL seams unsuable if can´t use variables?
 
ex:
"UPDATE HighScore SET Highscore=m_Score "
This does not work...I get the variable name in the database. Not whats in the variable?
 
And one more question.
If only want to searh the first(or the latest) record. How do I do?
AnswerRe: How do I use variables?memberT10006 Jan '04 - 2:00 
Ops, on the last question I meant.
How to UPDATE the first(or the latest) "field" in a record even if it is empty whit a variable as m_Score.
 
Would be greatfull if someone could help me whit this problem!
AnswerRe: How do I use variables?susswgdesigner23 Jan '04 - 22:58 
yeh we can use variables in the functions of SQL as bellow.
 
create table(varchar2(value1),number(value2),date(value3),char(value4));
 
after that we will insert the values in each variable.
 

Thanks
Raj Khatri
GeneralRe: How do I use variables?memberreal_valo10 Aug '06 - 2:08 
Variables can be easily used anywhere in the query.
Here's an eg:
 
UPDATE table
SET age=&age.
WHERE name LIKE '&name';
 
As you can see, the *key* is the "&" character; it means that you want
to use a variable with the name that folows it. If the variable type you
want to use is VARCHAR2 (* - in SQL language - a text) you need to place the variable (including the "&" character) between apostrophes (') and if the  
variable type is NUMBER(*) there's no need for them.
 
Eg. creating a very simple table:
 
create table myTable (
"&field1" VARCHAR2(&dim1),
"&field2" NUMBER(&dim2)
);
 
Then you will be asked to enter the values you want.
 
It is highly necessary the use of " " here.
 
May the force be with me!
Generalyour article helps alotmemberYescode31 Dec '03 - 22:27 
thank you so much

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 1 Apr 2002
Article Copyright 2002 by Dan Pomerchik
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid