SQL Module #58 Flashcards
What does SQL mean?
Structured Query Language
What command is used in SQL in order to create a table?
CREATE TABLE
What other information is needed when creating a table?
Table names and the data types that they will hold.
What are some of the most common data types you’ll see in an SQL table?
• CHAR • TEXT • VARCHAR • DATE • TIME • DATETIME • TIMESTAMP --------------------------------------------------- Numeric Types include: • TINYINT 1 byte (0-255) • INT 4 bytes • BIGINT 8 bytes • SMALLINT 2 bytes • DECIMAL • FLOAT
What does the syntax look like for a table with 2 columns (1 integer, 1 variable string lenght)?
CREATE TABLE people (
age INT,
name CHAR(20)
);
Once the table is created, how are values added to it?
INSERT INTO people VALUES (37, ‘Flavio’)
How are multiple values specified?
By separating the values with a comma. Example:
37, ‘Flavio’ ), (8, ‘Roger’
How is data added into a table?
Use the INSERT INTO command, example:
INSERT INTO people VALUES ( 37, ‘Flavio’ ), (8, ‘Roger’)
How can you query data from SQL?
By using the SELECT command.
You can narrow the query by selecting a single column:
SELECT name FROM people; OR SELECT COUNT(*) from people;
How are rows in a table filtered in SQL?
By adding the WHERE clause:
SELECT age FROM people WHERE name=’Flavio’;
When data is returned from a query, how can we adjust the order of the data? For example descending to acending?
By using the ORDER BY clause:
SELECT * FROM people ORDER BY name DESC;
or order by name:
SELECT * FROM people ORDER BY name;
Are empty values (empty cells) acceptable in SQL?
Yes, and they are represented as NULL, example:
INSERT INTO people VALUES (null, null); in this instance both columns have an empty cell or NULL value.
If a an entire row has a value of null, that can be problematic. How can we solve for that?
Declare constraints on the table preventing null values. Essentially write a rule, that forbids it. Example: Use NOT NULL
CREATE TABLE people (
age INT NOT NULL,
name CHAR(20) NOT NULL
);
Sometimes data contains a lot of repeated values. Say we didn’t want that to happen, what is the solution?
By using the UNIQUE key constraint. Example:
CREATE TABLE people (
age INT NOT NULL,
name CHAR(20) NOT NULL UNIQUE
);
What would happen if you used the UNIQUE key constraint and then tried to add duplicate values to the table?
You’d get an error:
ERROR: duplicate key value violates unique constraint “people_name_key”
DETAIL: Key (name)=(Flavio) already exists.