Database Flashcards

1
Q

What are migrations used for?

A

Defining the application’s database schema and making it sharable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Which facade is typically used for database agnostic support for creating and manipulating tables across all of Laravel’s supported database systems?

A

Schema

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Create a migration using Artisan!

A

php artisan make:migration create_examples_table

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you run all of your outstanding migrations?

A

php artisan migrate

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Use Artisan to see the SQL statements, that would be executed by the migrations, without actually running them!

A

php artisan migrate –pretend

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How can you stop multiple servers from trying to migrate the same database at the same time, if your application is running across multiple servers?

A

php artisan migrate –isolated

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What do you need to do to roll back the latest migration operation?

A

php artisan migrate:rollback

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Roll back the last 3 migrations!

A

php artisan migrate:rollback –step=3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Use Artisan to see the SQL statements, that would be executed by a rollback, without actually rolling back!

A

php artisan migrate:rollback –pretend

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Which command rolls back all of your applications migrations?

A

php artisan migrate:reset

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How can you roll back and remigrate your database in one command?

A

php artisan migrate:refresh

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Drop all tables from your database and then migrate and seed it in one command!

A

php artisan migrate:fresh –seed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Which method of the Schema facade should you use to make a new database table?

A

Schema::create

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Create a database table, which includes an id, 2 strings and time stamps!

A
Schema::create('example', function (Blueprint $table) {
    $table->id();
    $table->string('example1');
    $table->string('example2');
    $table->timestamps();
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How can you check if a database includes a table / column / index?

A
Schema::hasTable('exampletable')

Schema::hasColumn('exampletable', 'examplecolumn')

Schema::hasIndex('exampletable', ['examplecolumn'], 'exampleindex')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Create a table that uses the “InnoDB” engine!

A
Schema::create('example', function (Blueprint $table) {
    $table->engine('InnoDB');
    // ...
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Which method do you need to use to perform a schema operation on a database connection that is not your application’s default connection?

A

Schema::connection('sqlite')->create...

(just using sqlite as an example)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Specify the charset encoding as “utf8mb4” for a database during its creation!

A
Schema::create('example', function (Blueprint $table) {
    $table->charset('utf8mb4');
    // ...
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the main characteristic, that a temporary table has?

A

A table, that was created with the temporary method, drops all tables once the connection is closed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How can you add a comment to a table within the Schema::create?

A

$table->comment('Business calculations');

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Add the integer “score” to an already existing table!

A
Schema::table('example', function (Blueprint $table) {
    $table->integer('score');
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How can you rename a table in an existing database?

A

Schema::rename($from, $to);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How can you drop an existing table?

A

Schema::drop('example');

alternatively
Schema::dropIfExists('example');

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What does the boolean() method do?

A

The boolean method creates a BOOLEAN equivalent column:

$table->boolean('confirmed');

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What does the char() method do?

A

The char method creates a CHAR equivalent column with of a given length:

$table->char('name', length: 100);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What does the dateTime() method do?

A

The dateTime method creates a DATETIME equivalent column with an optional fractional seconds precision:

$table->dateTime('created_at', precision: 0);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What does the dateTimeTz() method do?

A

The dateTimeTz method creates a DATETIME (with timezone) equivalent column with an optional fractional seconds precision:

$table->dateTimeTz('created_at', precision: 0);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What does the date() method do?

A

The date method creates a DATE equivalent column:

$table->date('created_at');

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What does the foreignId() method do?

A

The foreignId method creates an UNSIGNED BIGINT equivalent column:

$table->foreignId('user_id');

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What does the id() method do?

A

The id method is an alias of the bigIncrements method. By default, the method will create an id column; however, you may pass a column name if you would like to assign a different name to the column:

$table->id();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What does the ipAdress() method do?

A

The ipAddress method creates a VARCHAR equivalent column:

$table->ipAddress('visitor');

When using PostgreSQL, an INET column will be created.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What does the rememberToken() method do?

A

The rememberToken method creates a nullable, VARCHAR(100) equivalent column that is intended to store the current “remember me” authentication token:

$table->rememberToken();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What does the set() method do?

A

The set method creates a SET equivalent column with the given list of valid values:

$table->set('flavors', ['strawberry', 'vanilla']);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What does the softDeletes() method do?

A

The softDeletes method adds a nullable deleted_at TIMESTAMP equivalent column with an optional fractional seconds precision. This column is intended to store the deleted_at timestamp needed for Eloquent’s “soft delete” functionality:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What does the timestampTz() method do?

A

The timestampTz method creates a TIMESTAMP (with timezone) equivalent column with an optional fractional seconds precision:

$table->timestampTz('added_at', precision: 0);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Create a table called “users” , which includes a column “name” and make the column default to “guest” if nothing else is provided!

A
Schema::create('people', function (Blueprint $table) {
    $table->id();
    $table->string('name')->default('guest');
    // ...
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

While adding columns to an already existing table and already being inside the Schema, add the string column “address” after the column “name”!

A
$table->after('name', function (Blueprint $table) {
    $table->string('address');
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What do you need to do to create a string column in a table with a size limit to the string?

A

$table->string('example', $size);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Given a table with a column with a string “name” that has a size limit of 30, increase the size limit to 50!

A

(within Schema::table)
$table->string('name', 50)->change();

ALWAYS INCLUDE ALL ATTRIBUTES, EVEN THE ONES YOU DON’T CHANGE THE VALUE OF OR THEY WILL BE DELETED!!!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

Within a Schema::table, how do you rename a column?

A

$table->renameColumn('from', 'to');

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Within a Schema::table, how can you drop columns?

A
$table->dropColumn('example'); <- Drops one column
$table->dropColumn(['example1', 'ex2', 'ex3']);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

How can you force the input values for columns to be unique?

A

$table->string('example')->unique();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

If you have already defined a column, how can you make it unique after the fact?

A

$table->unique('examplecolumn');

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

Pass an array of columns to an index!

A

$table->index(['example1', 'example2']);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

Rename an index!

A

$table->renameIndex('from', 'to');

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

Which method should you use to create a foreign key constraint?

A

$table->foreignId('example_id')->constrained();

47
Q

Why should you use foreign key constraints?

A

They force referential integrity at a database level

48
Q

If the foreignId that a column of a different table is referencing gets updated or deleted, how can you ensure the updating or deletion of the column in your other table?

A

While setting up the contrained foreignId, also include:
~~~
$table->foreignId(‘example_id’)
->contrained()
->onUpdate(‘cascade’)
->onDelete(‘cascade’);
~~~

49
Q

Drop the foreignId of the column “example_id”!

A

$table->dropForeign(['example_id']);

50
Q

What is pagination?

A

The dividing of content in a website into separate pages.
For example, if a website is showing you 500 results to a search query but only displays 20 per page, splitting the results up across multiple pages, that’s pagination.

51
Q

Split up the amount of results of a query into multiple subpages using pagination! Include 15 results per page!

A

INSERT QUERY->paginate(15)
also works with Eloquent results, doesn’t need to be a query

52
Q

Why should you sometimes use paginate() and sometimes simplePaginate()?

A

Simple pagination only displays a “next” and “previous” link in your application’s UI, while normal pagination also includes how many pages of records there are in total and which specific one you are currently on. For things like your e-mails mailbox it makes more sense to paginate(), but for things way bigger in size it becomes nonsensical.

53
Q

If multiple paginators are on a single screen and two or more of them use the page as the query string parameter, then there will be a conflict. How could you resolve this?

A

To resolve this conflict, you may pass the name of the query string parameter you wish to use to store the paginator’s current page via the third argument provided to the paginate, simplePaginate, and cursorPaginate methods:

use App\Models\User;
 
$users = User::where('votes', '>', 100)->paginate(
    $perPage = 15, $columns = ['*'], $pageName = 'users'
);
54
Q

Which type of pagination should you use for “infinite” scrolling user interfaces?

A

cursorPaginate();

55
Q

Which type of pagination uses the lowest amount of resources?

A

cursorPaginate();

56
Q

What do you need to do to add something to the end of a paginated link?
add “sort=votes” to the end of $users!

A

(in the Route::get)
$users->appends(['sort' => 'votes']);

57
Q

Return the JSON of “/examples” in the model “Example”

A
Route::get('/examples', function() {
    return Example::paginate();
);
58
Q

How do you export your pagination views using Artisan?

A

php artisan vendor:publish –tag=laravel-pagination

59
Q

Where can you designate a different file as the default pagination view?

A

In the boot() method of App\Providers\AppServiceProvider

60
Q

Which method do you need to use to begin a query in the DB facade? Also add the needed method to retrieve the results of the query!

A

DB::table('example')->get()

61
Q

Retrieve all “users” from the DB facade and output their names!

A
$users = DB::table('users')->get();

foreach ($users as $user) {
    echo $user->name;
}
62
Q

Return the “email” of the first user in the table “users” that has the “name” “John”!

A
$user = DB::table('users')->where('name', 'John')->first();

return $user->email;
63
Q

In a big database processing data from there becomes very time consuming, so splitting the task up becomes mandatory at some point. Optimize this code bit, so that it only processes 100 users at a time:
DB::table(‘users’)->orderBy(‘id’) {
foreach ($users as $user) {
// …
}
});

A
DB::table('users')->orderBy('id')->chunk(100, function (Collection $users) {
    foreach ($users as $user) {
        // ...
    }
});
64
Q

How can you stop processing further chunks from within the closure?

A

return false;

65
Q

What is a problem that can arise from using the chunk() method instead of the chunkById() method?

A

If database records are being updated while chunking results, the chunk results could change in unexpected ways. The chunkById() method automatically paginates the results based on the record’s primary key.

66
Q

What is the main difference between using the chunk() and lazy() methods for streaming query results?

A

Instead of passing each chunk into a callback, the lazy() method returns a LazyCollection, which lets you interact with the results as a single stream.

Again, if retrieved records are being updated while iterating over them, it is best to use the lazyById() or lazyByIdDesc() methods instead.

67
Q

Define $usercount as the amount of “users”!

A

$usercount = DB::table('users')->count();

68
Q

What is the raw() method of the DB facade used for? What makes using it wrongly dangerous?

A

The raw() method allows you to insert an arbitrary string into a query. Due to raw statements being injected into the query as strings, it could open up the possibility of SQL injection vulnerabilities.

69
Q

What is the union() method used for?

A

The union() method unions 2 or more queries together. You may for example create an initial query and then use the union() method to union it with more queries after the fact.

70
Q

Which 3 arguments does the where() method require?

A

where('value 1', ' operator', 'value 2')

you could for example want to look for entries in a table, where users are below the age of 35 by adding:
->where('age', '<', 35)
to your query.

If the operator you want to use is “=”, you don’t have to specify that. To get users at the exact age of 35 you could add this to your query:
->where('age', 35)

71
Q

When chaining together calls to the query builder’s where() method, the where clauses are joined together by an “and” operator by default. How could you make that an “or” instead?

A
->where( // ... )
->orWhere( // ... )
72
Q

You may want to have multiple where conditions being met with an and operator under your orWhere() clause. How can you achieve that?

A
->orWhere(function (Builder $query) {
    $query->where( // ... )
                 ->where( // ... )
73
Q

Which method should you use when you want to add to a query that certain things aren’t the case?

A

->whereNot( // ... )

this can also have multiple things, that are not supposed to be the case added like with the orWhere() function.
orWhereNot() also exists.

74
Q

How can you check if something is inside of a JSON array in a query?

A

->whereJsonContains( // ... )

75
Q

How could you check if a part of a JSON array is above a certain length in a query?

A

->whereJsonLength('example->thing', '>', 1)

This example checks if thing under example is above the length of 1, if you want to use the “=” operator you can again just leave it out and it will default to “=”

76
Q

What method is used to check if a part of a retrieved query is similar to something?

A

->whereLike('name', '%John%')

This would check for entries, where the name is similar to John. By default this is not case sensitive but if you wish for it to be, you can add a “, caseSensitive: true” before closing the bracket

77
Q

Which method should you use to verify if a given column value is contained within a given array?

A

->whereIn('columnname', [ENTER VALUES HERE])

78
Q

In a query, how can you check for entries in a column where the values are within a given range?

A

->whereBetween('columnname', [value 1, value2])

79
Q

How can you check if the values retrieved in a query in a certain column are outside of a certain range?

A

->whereNotBetween('columnname', [value 1, value2])

80
Q

Which method verifies if a value in a column is between two values of two columns in the same table row?

A

->whereBetweenColumns('weight', ['minimum_allowed_weight', 'maximum_allowed_weight])

obviously it can also be about other values but this is just a good example to show the usefulness of this method

81
Q

Which method verifies that the value of a given column is NULL?

A

->whereNull('columnname')

there are also the variants:
~~~
whereNotNull()
orWhereNull()
orWhereNotNull()
~~~

82
Q

How can you compare a columns value against a date to find values that have the given date?

A

->whereDate('created_at', '2001-02-14')

date needs to be in the format i have given in this example

83
Q

Verify that something was “created_at” during a certain month!

A

->whereMonth('created_at', '02')

add a 0 to the number of the month if it is a single digit number

84
Q

Which method checks for the specific time of day the value of a column contains?

A

->whereTime('created_at', '=', '11:20:45')

85
Q

How could you check if the value contained within 2 columns is equal?

A

->whereColumn('first_name', 'last_name')

86
Q

Within a query, create the necessary where clauses to check if the retrieved values have the name John AND EITHER over 100 votes or the title “Admin”!

A
->where('name', '=', 'John')
->where(function (Builder $query) {
    $query->where('votes', '>', 100)
                 ->orWhere('title', '=', 'Admin');
})
87
Q

Always group orWhere() calls in order to avoid unexpected behavior when global scopes are applied!

A

This card is not supposed to ask any question that you should answer, just keep this as a reminder to ALWAYS GROUP YOUR orWhere CALLS!

88
Q

Which method allows you to sort the results of the query by a given column and which parameters does it accept?

A
->orderBy('columnname', 'asc')
->orderBy('columnname', 'desc')

(asc = ascending / desc = descending)

89
Q

What do you need to do to sort the results of a query by when they were entered into the database? How does it work?

A
->latest() sorts by latest
->oldest() sorts by oldest

They check the “created_at” column and sort by those values depending on which of the 2 methods you use.

90
Q

How can you randomize the order of the results retrieved by a query?

A

->inRandomOrder()

91
Q

Which method undoes all “order by” clauses that have been applied to a query?

A

->reorder()->get();

92
Q

How can you group query results?

A
->groupBy('example')
->having('example', '>'; 100)

the having() method works very similarly to the where() method in this situation

93
Q

Let’s assume that a query outputs a bunch of items, but you are only interested in the 11th-15th entry of what the query finds. Make the query only output those!

A

->skip(10)->take(5)->get();

94
Q

Create a where clause that only gets applied under a certain condition!

A
->when($condition, function (Builder $query, string $condition) {
    $query->where('example', $condition);
})
->get();
95
Q

If conditions have an else clause that you can add after them that gets executed if the condition is not met. What is the equivalent for the when() method?

A

When a when() condition is not met, the part after it does not get executed, but if a second “, function (Builder $query) { …” exists after the first one, then that will be executed instead so this way you can have the “else” equivalent to this “if” like conditional.

96
Q

How can you add entries into a table using a query?

A
DB::table('example')->insert([
    'email' => 'ex@amp.le',
    'age' => 23
]);
97
Q

Insert multiple entries into a table in one query!

A
DB::table('example')->insert([
    ['email' => 'exa@mp.le', 'age' =>16],
    ['email' => 'e@xamp.le', 'age' => 24],
]);
98
Q

Insert ‘id’, ‘name’, ‘email’, ‘email_verified_at’ into ‘new_users’ using the values of the entry in ‘users’, where ‘updates_at’ is equal to the time span between now and last month!

A
DB::table('new_users')->insertUsing([
    'id', 'name', 'email', 'email_verified_at'
], DB::table('users')->select(
    'id', 'name', 'email', 'email_verified_at'
)->where('updated_at', '<=', now()->subMonth()));
99
Q

How can you insert something in a way that adds what you have entered if it doesnt exist in the table yet, but also updates the values in certain columns when the entry already exists in the database table?

A
DB::table('flights')->upsert(
    [
        ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
        ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
    ],
    ['departure', 'destination'],
    ['price']
);

The first argument is an array of values to be inserted into the database table, the second argument lists the column(s) that uniquely identify records with the associated table and the third and final argument is an array of columns that should be updated, if an entry with the unique identifiers already exists.

100
Q

How can you update values in a table?

A

DB::table('example')->where('id', 1)->update(['coolness' => 1]);

101
Q

Which method can you use to either insert an item if it doesn’t exist, or update selected values if it does?

A

->updateOrInsert()

The first argument is an array of values to be searched in the database in case of them existing, the second and last argument is an array of values that should be updated and what their new values should be.

102
Q

How can you delete records from a table?

A

->delete()
you can also specify a where clause before the deletion argument so that only specific entries get deleted.

103
Q

What does truncating a table mean and which method do you use to do it?

A

Truncating a table removes all records from the table and resets the auto-incrementing ID to zero. Be especially careful because CASCADE behavior will be applied.

104
Q

What does a shared lock do?

A

Calling the sharedLock() method will prevent a selected row from being modified until the transaction the sharedLock() is called upon in is completed.

105
Q

What is the difference between a sharedLock() and lockForUpdate()?

A

A “for update” lock prevents the selected records from being modified or from being selected by another shared lock.

106
Q

Which methods let you see the debug information?

A
->dump();
->dd();

dump will display the debug information and let the code keep running while dd will end the code and display the debug information.

107
Q

What does a seeder class do?

A

A seeder class seeds your database with data

108
Q

Where should you add your seeder classes to so that they will be ran in an order of your choosing?

A

In the call() method of the DatabaseSeeder in database/seeders

109
Q

Create a seeder using Artisan!

A

php artisan make:seeder ExampleSeeder

110
Q

What is the only method contained in a seeder?

111
Q

Add 3 seeders to the DatabaseSeeder to be ran!

A

(within run() method)

$this->call([
    TestSeeder::class,
    ExampleSeeder::class,
    BeispielSeeder::class,
]);
112
Q

How can you stop your seeder from dispatching model events?

A

use WithoutModelEvents;

113
Q

Seed your database using Artisan!

A

php artisan db:seed

114
Q

Freshly migrate and then seed your database using Artisan!

A

php artisan migrate:fresh –seed