You can delete schemas with the Google Cloud console,
Google Cloud CLI, client library, or Pub/Sub API.

> [!CAUTION]
> **Caution:** Deletion is permanent. You cannot restore a schema that is deleted. Any messages published to a topic that used the deleted schema cannot be written to BigQuery using a [BigQuerysubscription](https://docs.cloud.google.com/pubsub/docs/bigquery.md.txt) with [use topic schema](https://docs.cloud.google.com/pubsub/docs/create-bigquery-subscription.md.txt#use-topic-schema) enabled.

## Before you begin

- Understand how [Pub/Sub schemas work](https://docs.cloud.google.com/pubsub/docs/schemas.md.txt).
- [Create a schema](https://docs.cloud.google.com/pubsub/docs/create-schemas.md.txt).

### Required roles and permissions


To get the permissions that
you need to delete and manage schemas,

ask your administrator to grant you the
[Pub/Sub Editor](https://docs.cloud.google.com/iam/docs/roles-permissions/pubsub.md.txt#pubsub.editor) (`roles/pubsub.editor`) IAM role on your project.


For more information about granting roles, see [Manage access to projects, folders, and organizations](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access.md.txt).


This predefined role contains

the permissions required to delete and manage schemas. To see the exact permissions that are
required, expand the **Required permissions** section:


#### Required permissions

The following permissions are required to delete and manage schemas:

- Create schema: `pubsub.schemas.create`
- Attach schema to topic: `pubsub.schemas.attach`
- Commit a schema revision: `pubsub.schemas.commit`
- Delete a schema or a schema revision: `pubsub.schemas.delete`
- Get a schema or schema revisions: `pubsub.schemas.get`
- List schemas: `pubsub.schemas.list`
- List schema revisions: `pubsub.schemas.listRevisions`
- Rollback a schema: `pubsub.schemas.rollback`
- Validate a message: `pubsub.schemas.validate`
- Get the IAM policy for a schema: `pubsub.schemas.getIamPolicy`
- Configure the [IAM policy](https://docs.cloud.google.com/iam/docs/reference/rest/v1/Policy.md.txt) for a schema: `pubsub.schemas.setIamPolicy`


You might also be able to get
these permissions
with [custom roles](https://docs.cloud.google.com/iam/docs/creating-custom-roles.md.txt) or
other [predefined roles](https://docs.cloud.google.com/iam/docs/roles-overview.md.txt#predefined).

You can grant roles and permissions to principals such as users, groups,
domains, or service accounts. You can create a schema in one project and
attach it to a topic located in a different project.
Ensure that you have the required permissions for
each project.

## Delete a schema

Here is a list of important information about deleting schemas:

- If a schema is deleted, all attempts to publish messages to topics associated
  with that schema fail.

- The delete operation for a schema also deletes all the revisions associated with
  the schema.

- You can create a schema with the same name as the one that you just deleted.
  However, the newly created schema is entirely independent of the previously
  deleted one.

- Before deleting a schema, ensure you remove
  [its association from a topic](https://docs.cloud.google.com/pubsub/docs/associate-schema-topic.md.txt#edit-schema-association).

### Console

1. In the Google Cloud console, go to the **Pub/Sub schemas** page.

   [Go to Schemas](https://console.cloud.google.com/cloudpubsub/schema)
2. Select one or more schemas that you want to delete.

3. Click **Delete**.

4. Confirm the delete operation.

### gcloud

```
gcloud pubsub schemas delete SCHEMA_NAME
```

### REST

To delete a schema send a DELETE request like the following:

```
DELETE https://pubsub.googleapis.com/v1/SCHEMA_NAME
```

### C++

Before trying this sample, follow the C++ setup instructions in
[Quickstart: Using Client Libraries](https://docs.cloud.google.com/pubsub/docs/create-topic-client-libraries).
For more information, see the [Pub/Sub C++ API reference documentation](https://googleapis.dev/cpp/google-cloud-pubsub/latest/).

```c++
namespace pubsub = ::google::cloud::pubsub;
[](pubsub::SchemaServiceClient client, std::string const& project_id,
   std::string const& schema_id) {
  google::pubsub::v1::DeleteSchemaRequest request;
  request.set_name(pubsub::Schema(project_id, schema_id).FullName());
  auto status = client.DeleteSchema(request);
  // Note that kNotFound is a possible result when the library retries.
  if (status.code() == google::cloud::StatusCode::kNotFound) {
    std::cout << "The schema was not found\n";
    return;
  }
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "Schema successfully deleted\n";
}
```

### C#

Before trying this sample, follow the C# setup instructions in
[Quickstart: Using Client Libraries](https://docs.cloud.google.com/pubsub/docs/create-topic-client-libraries).
For more information, see the [Pub/Sub C# API reference documentation](https://cloud.google.com/dotnet/docs/reference/Google.Cloud.PubSub.V1/latest).

```c#

using Google.Cloud.PubSub.V1;

public class DeleteSchemaSample
{
    public void DeleteSchema(string projectId, string schemaId)
    {
        SchemaServiceClient schemaService = SchemaServiceClient.Create();
        SchemaName schemaName = SchemaName.FromProjectSchema(projectId, schemaId);
        schemaService.DeleteSchema(schemaName);
    }
}
```

<br />

### Go

<br />

The following sample uses the major version of the Go Pub/Sub client library (v2). If you are still using the v1 library, see
[the migration guide to v2](https://github.com/googleapis/google-cloud-go/blob/main/pubsub/MIGRATING.md).
To see a list of v1 code samples, see [the deprecated code samples](https://docs.cloud.google.com/pubsub/docs/samples.md.txt?language=golang&text=deprecated).

Before trying this sample, follow the Go setup instructions in
[Quickstart: Using Client Libraries](https://docs.cloud.google.com/pubsub/docs/create-topic-client-libraries).
For more information, see the [Pub/Sub Go API reference documentation](https://pkg.go.dev/cloud.google.com/go/pubsub/v2).

```go
import (
	"context"
	"fmt"
	"io"

	pubsub "cloud.google.com/go/pubsub/v2/apiv1"
	"cloud.google.com/go/pubsub/v2/apiv1/pubsubpb"
)

func deleteSchema(w io.Writer, projectID, schemaID string) error {
	// projectID := "my-project-id"
	// schemaID := "my-schema"
	ctx := context.Background()
	client, err := pubsub.NewSchemaClient(ctx)
	if err != nil {
		return fmt.Errorf("pubsub.NewSchemaClient: %w", err)
	}
	defer client.Close()

	req := &pubsubpb.DeleteSchemaRequest{
		Name: fmt.Sprintf("projects/%s/schemas/%s", projectID, schemaID),
	}
	if err := client.DeleteSchema(ctx, req); err != nil {
		return fmt.Errorf("client.DeleteSchema: %w", err)
	}
	fmt.Fprintf(w, "Deleted schema: %s", schemaID)
	return nil
}
```

<br />

### Java

Before trying this sample, follow the Java setup instructions in
[Quickstart: Using Client Libraries](https://docs.cloud.google.com/pubsub/docs/create-topic-client-libraries).
For more information, see the [Pub/Sub Java API reference documentation](https://cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/overview).

```java

import com.google.api.gax.rpc.NotFoundException;
import com.google.cloud.pubsub.v1.SchemaServiceClient;
import com.google.pubsub.v1.SchemaName;
import java.io.IOException;

public class DeleteSchemaExample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String schemaId = "your-schema-id";

    deleteSchemaExample(projectId, schemaId);
  }

  public static void deleteSchemaExample(String projectId, String schemaId) throws IOException {
    SchemaName schemaName = SchemaName.of(projectId, schemaId);

    try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {

      schemaServiceClient.deleteSchema(schemaName);

      System.out.println("Deleted a schema:" + schemaName);

    } catch (NotFoundException e) {
      System.out.println(schemaName + "not found.");
    }
  }
}
```

<br />

### Node.js

Before trying this sample, follow the Node.js setup instructions in
[Quickstart: Using Client Libraries](https://docs.cloud.google.com/pubsub/docs/create-topic-client-libraries).
For more information, see the [Pub/Sub Node.js API reference documentation](https://googleapis.dev/nodejs/pubsub/latest).

```javascript
/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID';

// Imports the Google Cloud client library
const {PubSub} = require('@google-cloud/pubsub');

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function deleteSchema(schemaNameOrId) {
  const schema = pubSubClient.schema(schemaNameOrId);
  const name = await schema.getName();
  await schema.delete();
  console.log(`Schema ${name} deleted.`);
}
```

<br />

### Node.js

Before trying this sample, follow the Node.js setup instructions in
[Quickstart: Using Client Libraries](https://docs.cloud.google.com/pubsub/docs/create-topic-client-libraries).
For more information, see the [Pub/Sub Node.js API reference documentation](https://googleapis.dev/nodejs/pubsub/latest).

```javascript
/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID';

// Imports the Google Cloud client library
import {PubSub} from '@google-cloud/pubsub';

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function deleteSchema(schemaNameOrId: string) {
  const schema = pubSubClient.schema(schemaNameOrId);
  const name = await schema.getName();
  await schema.delete();
  console.log(`Schema ${name} deleted.`);
}
```

<br />

### PHP

Before trying this sample, follow the PHP setup instructions in
[Quickstart: Using Client Libraries](https://docs.cloud.google.com/pubsub/docs/create-topic-client-libraries).
For more information, see the [Pub/Sub PHP API reference documentation](https://cloud.google.com/php/docs/reference/cloud-pubsub/latest).

```php
use Google\Cloud\PubSub\PubSubClient;

/**
 * Delete a schema.
 *
 * @param string $projectId
 * @param string $schemaId
 */
function delete_schema($projectId, $schemaId)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);

    $schema = $pubsub->schema($schemaId);

    if ($schema->exists()) {
        $schema->delete();

        printf('Schema %s deleted.', $schema->name());
    } else {
        printf('Schema %s does not exist.', $schema->name());
    }
}
```

<br />

### Python

Before trying this sample, follow the Python setup instructions in
[Quickstart: Using Client Libraries](https://docs.cloud.google.com/pubsub/docs/create-topic-client-libraries).
For more information, see the [Pub/Sub Python API reference documentation](https://docs.cloud.google.com/python/docs/reference/pubsub/latest.md.txt).

```python
from google.api_core.exceptions import NotFound
from google.cloud.pubsub import SchemaServiceClient

# TODO(developer): Replace these variables before running the sample.
# project_id = "your-project-id"
# schema_id = "your-schema-id"

schema_client = SchemaServiceClient()
schema_path = schema_client.schema_path(project_id, schema_id)

try:
    schema_client.delete_schema(request={"name": schema_path})
    print(f"Deleted a schema:\n{schema_path}")
except NotFound:
    print(f"{schema_id} not found.")
```

<br />

### Ruby

<br />

The following sample uses Ruby Pub/Sub client library v3. If you are still using the v2 library, see
[the migration guide to v3](https://github.com/googleapis/google-cloud-ruby/blob/main/google-cloud-pubsub/MIGRATION_GUIDE.md).
To see a list of Ruby v2 code samples, see [the deprecated code samples](https://docs.cloud.google.com/pubsub/docs/samples.md.txt?language=ruby&text=deprecated).

Before trying this sample, follow the Ruby setup instructions in
[Quickstart: Using Client Libraries](https://docs.cloud.google.com/pubsub/docs/create-topic-client-libraries).
For more information, see the [Pub/Sub Ruby API reference documentation](https://googleapis.dev/ruby/google-cloud-pubsub/latest/Google/Cloud/PubSub.html).

```ruby
# schema_id = "your-schema-id"

pubsub = Google::Cloud::PubSub.new
schemas = pubsub.schemas

result = schemas.delete_schema name: pubsub.schema_path(schema_id)

puts "Schema #{schema_id} deleted."
```

<br />

### Rust

Before trying this sample, follow the Rust setup instructions in
[Quickstart: Using Client Libraries](https://docs.cloud.google.com/pubsub/docs/create-topic-client-libraries).
For more information, see the [Pub/Sub Rust API reference documentation](https://docs.rs/google-cloud-pubsub).

```rust
use google_cloud_pubsub::client::SchemaService;

pub async fn sample(
    client: &SchemaService,
    project_id: &str,
    schema_id: &str,
) -> anyhow::Result<()> {
    client
        .delete_schema()
        .set_name(format!("projects/{project_id}/schemas/{schema_id}"))
        .send()
        .await?;

    println!("successfully deleted schema");
    Ok(())
}
```

<br />

## What's next

- [Delete a schema revision](https://docs.cloud.google.com/pubsub/docs/delete-schema-revision.md.txt)
- [List schemas](https://docs.cloud.google.com/pubsub/docs/list-schemas.md.txt)
- [List revisions of a schema](https://docs.cloud.google.com/pubsub/docs/list-schema-revisions.md.txt)
- [Subscribe to a topic with a schema](https://docs.cloud.google.com/pubsub/docs/schemas-valid.md.txt)