SQL Flashcards
Get all records from a table
SELECT * FROM table;
Get specific fields from a table
SELECT field1,field2 FROM table;
Get only different values from a table
SELECT DISTINCT field FROM table;
Get records with a field equal to a string value and another equal to a numeric value
SELECT * FROM table WHERE field1=’value’ AND field2=1;
Get all records from a table sorted by two fields, ascending
SELECT * FROM table ORDER BY field1,field2;
Get all records from a table sorted by a field, descending
SELECT * FROM table ORDER BY field DESC;
Add a record to a table by filling all columns
INSERT INTO table VALUES (value1, value2, …);
Add a record to a table by filling some columns
INSERT INTO table (field1, field2) VALUES (value1, value2);
Change values for records conditionally
UPDATE table SET field1=value1,field2=value2 WHERE condition;
Remove records conditionally
DELETE FROM table WHERE condition;
Get a certain number of records
SELECT TOP count field1,field2 FROM table;
Get a certain percentage of records
SELECT TOP pcnt PERCENT field1,field2 FROM table;
Get records with field1 starting with ‘happy’
SELECT * FROM table WHERE field1 LIKE ‘happy%’;
Get records with field1 not ending with ‘happy’
SELECT * FROM table WHERE field1 NOT LIKE ‘%happy’
Pattern for many unknown characters
%
Pattern for single unknown character
_
Pattern for character set
[ab-d]
Pattern for NOT character set
[!abc]
Get all records with field1 equal to any values in a set
SELECT * FROM table WHERE field1 IN (‘a’,’b’);
Get all records with field1 alphabetically between two strings
SELECT * FROM table WHERE field1 BETWEEN ‘astring’ AND ‘bstring’;
Create a short name for a table
SELECT o.Field1, c.Field2 FROM table1 as o, table2 as c WHERE condition;
Get associated records from two tables where there is at least one match in both
SELECT t1.f1,t2.f2 FROM t1 INNER JOIN t2 ON t1.f=t2.f
Get associated records from two tables showing all records from first table
SELECT t1.f1,t2.f2 FROM t1 LEFT JOIN t2 ON t1.f1=t2.f2
Get associated records from two tables showing all records from second table
SELECT t1.f1,t2.f2 FROM t1 RIGHT JOIN t2 ON t1.f1=t2.f2