Structured Query Language (SQL)
Basic Conditional Select Statements
Used when querying a database. Table names are in [brackets] for clarity, and [brackets] are used when a table
might be interpreted as a command or an sql error. The star (*) means all columns. The following will return data:
select * from [tablename] where tablenameid = 4
select employeesid, lastname, firstname, empnum from [employees] where empnum > 5
select * from [employees] where empnum > 5 and (salary > 75000 or commission > 25000)
Alphabatize it!
One would order by columnname [asc | desc] but if you don't specify, it'll default to ascending.
select * from [employees] order by employeesid
select * from [employees] order by lastname asc, firstname asc
Like
Here we're using the percent (%) to choose from any characters, in this case words that start with the letter M.
select * from [employees] where title like 'M%'
select * from [employees] where title not like 'M%'
In & Between
select * from [employees] where title in ('Ms', 'Miss', 'Mrs')
select * from [employees] where salary between 25000 and 75000
select * from [employees] where salary not between 25000 and 75000
Sum, Avg, Count, Max, Min
Here we're comparing sums, averages and minimums and maximums of salarys of men against women,
title being the destinction.
select sum(salary), avg(salary) from [employees] where title like ('mr%')
select sum(salary), avg(salary) from [employees] where title not like ('mr%')
select min(salary) from [employees] where title like ('mr%')
select min(salary) from [employees] where title not like ('mr%')
select count(employeesid) from [employees] where salary > 75000
Advanced Creation/Deletion Commands
To create a table:
create table benefits (benefitsid integer not null, employeecode char(5) not null, salary decimal(8,2), entereddate date, married logical, comments varchar)
To add a field to a table:
alter table benefits add (age decimal(8,2) null);
To move a table:
alter table [table] rename to [renamedtable]
To copy a table:
select * into [newtable] from [oldtable]
To delete a table:
drop table [table]
To insert a row (add data) to a table:
insert into [benefits] values (21,'E5461',45000,'5/6/98',false,'Remember: you can''t have apostrophies without doubling them!')
insert into [benefits] (employeecode, salary, comments) values ('E5461',45000,'Here, we''re just entering only three colums worth of data!')
To delete rows from a table:
delete from [benefits] where married=false
To update a row from a table:
update [benefits] set married=true where employeesid=21
Links & Downloads
My primer in SQL
In case you're a SQL Newbie
Manuel Soriano's article in Linux Focus
A layered SQL Help
Copyright 1999 Michael Diedrick and Byte Studios