SQL Flashcards
What is a foreign key?
A foreign key is a column or group of columns in a relational database table that refers to the primary key of another table.
What is schema?
- a collection of Tables, which can be split and grouped according to logic.
- In MySQL, Schema and Database are integrated into one.
Command to display table column info.
SHOW FULL COLUMNS FROM table_name;
Command to delete table
DROP TABLE table_name;
Delete data in table (keep the table).
TRUNCATE table_name;
what are the number data types in SQL?
- BIGINT, INT, MEDIUMINT, SMALLINT, TINYINT
- DOUBLE, FLOAT, DECIMAL
What are the text types in SQL?
CHAR, VARCHAR (variable length –> VARCHAR(45)), can be set, TEXT, LONGTEXT
what are date time data types in SQL?
DATE, MONTH, YEAR, DATETIME , TIMESTAMP (limited to a range between 1970-01-01 00:00:01 and 2038-01-19 03:14:07)
Add column ‘age’ to table ‘users’ with data type INT and null values allowed. Insert after column ‘name’.
ALTER TABLE users
ADD COLUMN age
INT NULL AFTER name
;
Command to change existing column.
ALTER TABLE new_schema
.users
CHANGE COLUMN id
id
INT(11) NOT NULL AUTO_INCREMENT,
CHANGE COLUMN name
user_name
VARCHAR(45) NOT NULL DEFAULT ‘No Name’;
Command to display all data in a table
SELECT * FROM <table_name>;</table_name>
Show all data for user with id=2
SELECT * FROM users
WHERE id
= 2;
What is the difference between WHERE and HAVING clauses?
the WHERE clause is used to filter records before they are grouped and aggregated, while the HAVING clause is used to filter groups after they have been formed.
SELECT * FROM customers
WHERE city = ‘New York’;
########
SELECT city, COUNT() as count
FROM customers
GROUP BY city
HAVING COUNT() > 2;
example query to find all occurrences of error code 403
SELECT system_number, DATE(date_time) as error_date, COUNT(*) as error_count
FROM table_name
WHERE error_code = 403
GROUP BY system_number, error_date;
Types of constraints in SQL
NOT NULL Constraint: This constraint ensures that a column cannot contain null values. It forces the column to have a value for every row.
UNIQUE Constraint: This constraint ensures that each value in a column is unique, meaning that no two rows can have the same value in that column.
PRIMARY KEY Constraint: This constraint is a combination of NOT NULL and UNIQUE constraints. It ensures that a column or a group of columns uniquely identifies each row in a table.
FOREIGN KEY Constraint: This constraint ensures that the values in a column or a group of columns in one table match the values in another table’s primary key column(s).
CHECK Constraint: This constraint ensures that a value in a column meets a specific condition, such as a range of values, a regular expression, or a list of allowed values.
DEFAULT Constraint: This constraint sets a default value for a column when no value is provided.